Immanuel

Friday, July 17, 2015

PHP MVC

VC - > Model View Controller

It is the very famous design used by most developers, it help the developer to reuse the components and to create the loosely coupled web application.


The above picture shows how this MVC Works.

We will create the three folder called model,view,controller.
The folder and files which we will be using are




Controller is the one which handle the request and give appropriate response page.

Controller.php




  

include_once("model/Model.php");

class Controller {
     public $model;

     public function __construct()  
     {  
          $this->model = new Model();
     } 
     public function invoke()
     {
          if (!isset($_GET['book']))
          {
               // no special book is requested, we'll show a list of all available books
               $books = $this->model->getBookList();
               include 'view/booklist.php';
          }
          else
          {
               // show the requested book
               $book = $this->model->getBook($_GET['book']);
               include 'view/viewbook.php';
          }
     }
}

?>

Model
 Model is the basic layer where the data lies

Book.php

class Book {
public $title;
public $author;
public $description;
public function __construct($title, $author, $description)  
    {  
        $this->title = $title;
   $this->author = $author;
   $this->description = $description;
    } 
}

?>

Model.php

include_once("model/Book.php");
class Model {
public function getBookList()
{
// here goes some hardcoded values to simulate the database
return array(
"Jungle Book" => new Book("Jungle Book", "R. Kipling", "A classic book."),
"Moonwalker" => new Book("Moonwalker", "J. Walker", ""),
"PHP for Dummies" => new Book("PHP for Dummies", "Some Smart Guy", "")
);
}
public function getBook($title)
{
// we use the previous function to get all the books and then we return the requested one.
// in a real life scenario this will be done through a db select command
$allBooks = $this->getBookList();
return $allBooks[$title];
}
}
?>

View

It is the output which user can view at client side

booklist.php



Title
Author
Description


foreach ($books as $title => $book)
{
echo '
'.$book->title.'
'.$book->author.'
'.$book->description.'
';
}

?>


viewbook.php




echo 'Title:' . $book->title . '
';
echo 'Author:' . $book->author . '
';
echo 'Description:' . $book->description . '
';

?>


Root File

This file will be the index of this web application, this is only file name that user can see in web browser.

index.php





Happy Hacking :)





Wednesday, February 19, 2014

Install Oracle Java in Ubuntu 13.10

Hello all,

This blog is about installing oracle java in Ubuntu 13.10. Oracle Java is the important run time environment for installing Android Studio and Hadoop end etc.

By default Ubuntu gives open jdk that is good but still i prefer to use oracle java.

Follow the following steps to install

1. Check for java in Ubuntu

dpkg --list | grep -i jdk

2. Add Repository to ubuntu

sudo add-apt-repository ppa:webupd8team/java
 
3. Update list and install oracle JAVA

sudo apt-get update && sudo apt-get install oracle-jdk7-installer

4. Accept the license agreement and enable JDK

update-alternatives --display java
 
5.Check Ubuntu Java Version
java -version
 
If you see this in terminal then all works good
 
java version “1.7.0_25″
Java(TM) SE Runtime Environment (build 1.7.0_25-b15)
Java HotSpot(TM) Server VM (build 23.3-b01, mixed mode)
 
6.Check  Java  Compiler Version
 
javac -version
It should show something like this
javac 1.7.0_25
.
7. Add JAVA_HOME to environment variable

Edit /etc/environment and add JAVA_HOME=/usr/lib/jvm/java-7-oracle to the end of the file
sudo nano /etc/environment
 
8. Append to the end of the file
JAVA_HOME=/usr/lib/jvm/java-7-oracle
 
Happy Hacking:) 
 
  

Tuesday, February 4, 2014

Android Web login Using JSON Example

Logging in to the web site in android mobile can be achieved by loading the entire page in Web view but this has lots of drawbacks
1. Your web site should be mobile compatibility and more responsive
2. Network bandwidth
3. Time delay

This can be overcome by using the HttpClient and JSON in Android.

We are about to create a native android application that will have a login and register form which is used to login / register the user to the website that is running PHP (You  can your any other also) in internet.
JSON (Java Script Object Notation) is the intermediate data transfer agent between web server and Android Mobile

Pre-requestion 
1. Android Development Environment in your system
            Refer:http://arunimmanuel.blogspot.in/2012/07/installing-android-in-windows.html
            (or)
            Download latest Android studio from google  http://developer.android.com/sdk/installing/studio.html
2. Web site with PHP, MYSQL which give JSON array output.

Steps to be followed
Create a Signup page in Web server named signup.html



Sign Up


User Name:

Password:



Then create signup.php
$Uname = $_POST["txtUname"];
$Pass = $_POST["txtPass"];
$con=mysqli_connect("YOUR_HOST","YOUR_USERNAME","YOUR_PASS","YOUR_DB");
// Check connection
if (mysqli_connect_errno())
{
$response["success"] = 0;
 $response["message"] = "Database Error!";
die(json_encode($response));
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
try{

mysqli_query($con,"INSERT INTO login VALUES ('$Uname','$Pass')");
$response["success"] = 1;
 $response["message"] = "Registration successful!";
die(json_encode($response));
}
catch(Exception $e){
$response["success"] = 0;
 $response["message"] = "Cannot Add";
die(json_encode($response));
}
mysqli_close($con);

?>


Create login page login.html




User Name:


Password:



Create login.php

$Uname = $_POST["txtUName"];
$Pass = $_POST["txtPass"];

$con=mysqli_connect("YOUR_HOST","YOUR_USERNAME","YOUR_PASS","YOUR_DB");// Check connection
if (mysqli_connect_errno())
  {
$response["success"] = 0;
 $response["message"] = "Database Error!";
die(json_encode($response));
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM login where UName='$Uname' AND Pass='$Pass'");

while($row = mysqli_fetch_array($result))
  {
$response["success"] = 1;
 $response["message"] = "Login successful!";
die(json_encode($response));
header("Location: home.php");
  }

mysqli_close($con);
?>


Now create a new Android Project

My MainActivity is renamed to Login

Create login.xml

Code for login.xml

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

   


Create register.xml

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

            android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/password"
        android:layout_centerVertical="true"
        android:text="Username" />

            android:id="@+id/username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:ems="10" />

            android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/username"
        android:layout_below="@+id/username"
        android:text="Password" />

            android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="16dp"
        android:gravity="center"
        android:text="Android Remote Server Tutorial"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textStyle="bold" />

            android:id="@+id/password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/TextView01"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="textPassword" />

   


Now inflate these activity and views in respective Java files

I have Login.java and Register.java

Login.java

package com.android.json.login;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity implements OnClickListener{
   
    private EditText user, pass;
    private Button mSubmit, mRegister;
   
     // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();
   
    //php login script location:
   
    //localhost : 
    //testing on your device
    //put your local ip instead,  on windows, run CMD > ipconfig
    //or in mac's terminal type ifconfig and look for the ip under en0 or en1
   // private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php";
   
    //testing on Emulator:
    private static final String LOGIN_URL = "http://arunimmanuel.000space.com/Social/login.php";
   
  //testing from a real server:
    //private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
   
    //JSON element ids from repsonse of php script:
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
       
        //setup input fields
        user = (EditText)findViewById(R.id.username);
        pass = (EditText)findViewById(R.id.password);
       
        //setup buttons
        mSubmit = (Button)findViewById(R.id.login);
        mRegister = (Button)findViewById(R.id.register);
       
        //register listeners
        mSubmit.setOnClickListener(this);
        mRegister.setOnClickListener(this);
       
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.login:
                new AttemptLogin().execute();
            break;
        case R.id.register:
                Intent i = new Intent(this, Register.class);
                startActivity(i);
            break;

        default:
            break;
        }
    }
   
    class AttemptLogin extends AsyncTask {

         /**
         * Before starting background thread Show Progress Dialog
         * */
        boolean failure = false;
       
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Login.this);
            pDialog.setMessage("Attempting login...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
       
        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
             // Check for success tag
            int success;
            String username = user.getText().toString();
            String password = pass.getText().toString();
            try {
                // Building Parameters
                List params = new ArrayList();
                params.add(new BasicNameValuePair("txtUName", username));
                params.add(new BasicNameValuePair("txtPass", password));

                Log.d("request!", "starting");
                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(
                       LOGIN_URL, "POST", params);

                // check your log for json response
                Log.d("Login attempt", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("Login Successful!", json.toString());
                    Intent i = new Intent(Login.this, Home.class);
                    finish();
                    startActivity(i);
                    return json.getString(TAG_MESSAGE);
                }else{
                    Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);     
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
           return null; 
        }
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if (file_url != null){
                Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
            }
        }     
    }
 }


Register.java

package com.android.json.login;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Register extends Activity implements OnClickListener{
   
    private EditText user, pass;
    private Button  mRegister;
   
     // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();
   
    //php login script
   
    //localhost : 
    //testing on your device
    //put your local ip instead,  on windows, run CMD > ipconfig
    //or in mac's terminal type ifconfig and look for the ip under en0 or en1
   // private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/register.php";
   
    //testing on Emulator:
    private static final String LOGIN_URL = "http://arunimmanuel.000space.com/Social/signup.php";
   
  //testing from a real server:
    //private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/register.php";
   
    //ids
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
       
        user = (EditText)findViewById(R.id.username);
        pass = (EditText)findViewById(R.id.password);
       

        mRegister = (Button)findViewById(R.id.register);
        mRegister.setOnClickListener(this);
       
    }


    public void onClick(View v) {
        // TODO Auto-generated method stub
       
                new CreateUser().execute();
       
    }
   
    class CreateUser extends AsyncTask {

         /**
         * Before starting background thread Show Progress Dialog
         * */
        boolean failure = false;
       
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Register.this);
            pDialog.setMessage("Creating User...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
       
        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
             // Check for success tag
            int success;
            String username = user.getText().toString();
            String password = pass.getText().toString();
            try {
                // Building Parameters
                List params = new ArrayList();
                params.add(new BasicNameValuePair("txtUname", username));
                params.add(new BasicNameValuePair("txtPass", password));

                Log.d("request!", "starting");
               
                //Posting user data to script
                JSONObject json = jsonParser.makeHttpRequest(
                       LOGIN_URL, "POST", params);

                // full json response
                Log.d("Login attempt", json.toString());

                // json success element
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("User Created!", json.toString());                 
                    finish();
                    return json.getString(TAG_MESSAGE);
                }else{
                    Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);
                   
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
           
        }
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if (file_url != null){
                Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
            }

        }
       
    }
  }


We need JSON parser class to parse the JSON response
JSONParser.java

package com.android.json.login;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }          

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

Now update the Manifest
1. Permission to Access Internet
2. Add new Activity to Manifest

AndroidManifest.xml



            android:name = ".Register"/>
                    android:name=".Home"/>


Download Source code from GitHub : https://github.com/arunimmanuelpro/Android-JSON
Happy Hacking :)

Sunday, February 2, 2014

Getting Started with Git in Eclipse

Hello Every one after long time i am posting this post, this will explain how simply you can use GIT(Version Control System) for your projects on Eclipse.
Pre request
1. Eclipse
2. Account on https://github.com

First i will push my android project into github repository
1. Log into your github

2. Click on "New Repository" in your dashboard which is found in bottom right


3. Enter the Name of your repository, i have entered as "Sample" and click on "Create Repository"


4. After creating the repository you can see the repository page, now click on http and copy the URL as shown below


Now we have created the repository in github and we have to create the Android project in eclipse

5. Right Click on the Android Project ->Team -> Share Project


6. Set Git in a Dialog that appear, ignore Warning just click OK and Click on Next

7. For the first time you have to create a local repository click on create and enter the name and click finish


8. Check the repository name and click finish


9. Now commit your code to the local repository Right Click on the project ->Team ->Commit



10. Authorize yourself with username and email address of git


11. Now a new screen will appear enter the comit message and select the files that want to be commited and click Commit


12. Now we will push this to the remote git Right Click on project title -> Team -> Remote->Push


13. Enter the username and password of the git and Click Next





14. Wait for a minute and Click Finish


15. Go to github site and refresh your repository page you can see the android folder and its content is added to the repository.


Hope this one will help.Happy hacking :)

Friday, October 11, 2013

Intrusion Detection

It has been many days that i blogged and shared my knowledge. Now i am going to share about the topic which i took seminar also its my UG research topic.



Intrusion Detection
Intruders
Generally reffered to the hacker or cracker
Three classes of intruder
1.     Masquerader: An individual who is not authorized to use a computer.
2.     Misfeasor: A legitimate user who access data,program ,resources for which he is not authorized
3.     Clandestine User: An individual who seizes supervisory control of the system.

Intrusion Techniques
Typically a system would contain the file which stores passwords. If such files are stored with no protection, then it is easy matter to gain access to the system. The password file can be protected in two ways
1.     One-way encryption: password will be encrypted with a key and stored in a file
2.     Access control: Access to the password file is limited to one or a very few accounts.
To break this password the intruder will try the following techniques
1.     Try the default password of the standard accounts.
2.     Exhaustively try all short passwords
3.     Try words in the systems online directory
4.     Collect information about the user
5.     Try user’s phone number
6.     Try all legitimate license plate number
7.     Use a Trojan horse and by pass restriction on access
8.     Tap the line between remote user and host system
Intrusion Detection
Intrusion detection is based on the assumption of the intruder differs from that of a legitimate user in ways that can be quantified.
Approaches to intrusion detection

1.     Statically anomaly detection: It collects all the statistical data relating to the users behavior.
a.     Threshold Detection : Defining threshold, Independent of user, frequency of occurrence of various events
b.     Profile based: A profile of the activity of each user is developed and used to detect changes.
2.     Rule based detection: define a set of rules that can be used to decide that the given behavior is an intruder.
a.     Anomaly detection: rules are developed to detect deviation from previous usage pattern
b.     Penetration identification: An expert system is used to identify the intruders
Audit Records
            A fundamental tool of intrusion detection. Two planes are used
1.     Native Audit records: all multiuser operating system has the accounting software that collects information about the events that occurs in the system. This is very useful for the intrusion detection
2.     Detection-specific audit records: A collection facility can be implemented that generated audit records containing only that information required by the intrusion detection system.
Each audit records contains fields
·        Subject: Initiators of actions.
·        Action: Operation performed by the subject
·        Object: Receptors if actions
·        Exception-condition: Denotes if any exception conditions occurs
·        Resources-usage: A list of quantitative elements in which each statement gives the amount of resource used.
·        Time-Stamp: Unique time-and-date stamp
Statically Anomaly Detection
Profile-based detection needs the following metrics
·        Counter: A non-negative integer which can be increased but not decreased until it is reset by the management action.
·        Gauge: A non-negative integer that can be incremented or decremented. It measures the current value of the some entity.
·        Interval timer: The length between two related events.
·        Resource utilization: quantity of recourse consumed during a specified period.
Rule-based detection
It detects by observing the events in the system and applying a set of rules that lead to a decision regarding weather the given pattern of activity is or is not suspicious.
            Rule-based anomaly detection: similar to statical anomaly detection, here historically audit records are analyzed to identify usage pattern and to generate automatically rules that describe those patterns.
Rule-based penetration identification: it takes very different approach to intrusion detection, one based on expert system technology. This will use of rules for identifying known penetration.
Simple example of the types of rules
1.     Users should not read files in other users personal directories
2.     Users must not write on other users file
3.     User who log in after hours often access the same files they used earlier
4.     User should not log in more than one time in a single system
5.     User do not make duplicate copies of system programs
Distributed Intrusion Detection
·        A distributed intrusion detection system may need to deal with different audit record formats.
·        One or more nodes in a network will serve as collection and analysis point for data from the system on network. Thus, entire raw audit data or summary data must be transmitted over network.
·        Either a centralized or decentralized architecture can be used
·        Central architecture will have a single point of analysis and collection
·        Decentralized architecture will have more than one analysis center, but this must coordinate the activity and exchange information.
A good distributed intrusion detection system will contain the following
·        Host agent module: A audit collection module operating as a background process on a monitored system.
·        LAN Monitoring agent module: it analyzes the LAN traffic and reports the results to the central manager.
·        Central manager module: receives report from host agent and LAN monitoring module and processes and correlates these report to detect intrusion.

This is independent design for any operating system; this is quite general and flexible architecture. The central manager module will conclude the presence of intrusion from the results.

Honeypots
Honeypots are decoy systems that are designed to lure a potential attacker away from critical system. These are designed to
·        Divert the attacker from central system
·        Collect information about the attacker activity
·        Encourage the attacker to stay on the system long enough for administrators to respond.
Initial efforts involved a single honeypot computer with IP address designed to attacker hacker.

 Cheers
 
Twitter Bird Gadget