Saturday, 2 December 2017

Data Security(Encryption) in Android

Hello guys !!! hope you all are doing well. Today i am going to shed some light on data security in Android.
First start with basic , what is data security or encryption in Android?
Hiding plain data with some sort of changed format by using algo with key to convert and retrieve data is called data encryption.
Here Plain data will be any data(personal, financial etc) without any sort of hiding. So that any user can easily accessed your data.

Of course everything works vice versa, if you have a cipher data and you know the algorithm and have a key, you will get original plain data with ease.
Algorithm Types
As we saw a very basic example of encryption. Nowadays algorithms are more complex and are separated on Symmetric and Asymmetric (there’s also a Hash Functions, that do not require a key, I will discuss it in later blog).

Symmetric : —  the oldest and best-known technique. 
  • The encryption key and the decryption key are the same
  •  it is generally categorized as being either Stream Cipher or Block cipher
The most common Symmetric AES — the Advanced Encryption Standard (AES) is the algorithm trusted as the standard by the U.S. Government and numerous organizations.

Asymmetric  :—  a modern branch of cryptography. 

  • known as public-key cryptography in which the algorithms employ a pair of keys (a public key and a private key) 
  • use a different component of the pair for different steps of the algorithm
The most common Asymmetric algorithm is RSA — a public-key encryption algorithm and the standard for encrypting data sent over the internet.

Stream cipher : —  a symmetric encryption algorithm that processes the data a bit or a byte at a time with a key resulting in a randomized cipher data or plain data.

Block cipher  :—  deterministic algorithm operating on fixed-length groups of bits, called blocks. Block ciphers are important elementary components in the design of many cryptographic protocols, and are widely used to implement encryption of bulk data.

Modes & Paddings
Block cipher has different Modes and Paddings that increases it protection level.
Modes : —  a mode of operation describes how to repeatedly apply a cipher’s single-block operation to securely transform amounts of data larger than a block.
Padding : —  block cipher works on units of a fixed size (known as a block size), but messages come in a variety of lengths. So some modes (namely ECB and CBC) require that the final block be padded before encryption.

Most common modes :-
ECB : —  Electronic Codebook, the simplest of the encryption modes. The message is divided into blocks, and each block is encrypted separately.
CBC : —  Cipher Block Chaining, each cipher data block depends on all plain data blocks processed up to that point. To make each message unique, an initialization vector must be used in the first block.
But simply because algorithm is not symmetric does not mean it can not have modes and paddings. Thats, for instance, RSA algorithm can be used with ECB mode and PKCS1Padding.

Key Types
There are three key types: 

  • Secret key, 
  • Private key and 
  • Public key.
Secret key — a single secret key which is used in conventional symmetric encryption to encrypt and decrypt a message.
Private key — the secret component of a pair of cryptographic keys used for decryption in asymmetric cryptography.
Public key — The public component of a pair of cryptographic keys used for encryption in asymmetric cryptography.
Together Public and Private keys forms a public-private cryptographic Key Pair.


How Data security works in Android
Java Cryptography Architecture
  • Android data security builds on the Java Cryptography Architecture (JCA)
  • In Android JCA provides API for digital signatures, certificates, encryption, keys generation and management
KeyGenerator — provides the public API for generating symmetric cryptographic keys.
KeyPairGenerator — an engine class which is capable of generating a private key and its related public key utilizing the algorithm it was initialized with.
SecretKey — a secret (symmetric) key. The purpose of this interface is to group (and provide type safety for) all secret key interfaces (e.g., SecretKeySpec).
PrivateKey — a private (asymmetric) key. The purpose of this interface is to group (and provide type safety for) all private key interfaces(e.g., RSAPrivateKey).
PublicKey — a public key. This interface contains no methods or constants. It merely serves to group (and provide type safety for) all public key interfaces(e.g., RSAPublicKey).
KeyPair — this class is a simple holder for a key pair (a public key and a private key). It does not enforce any security, and, when initialized, should be treated like a PrivateKey.
SecureRandom — generates cryptographically secure pseudo-random numbers. We will not use it directly in this series, but it is widely used inside of KeyGenerator, KeyPairGenerator components and Keys implementations.
KeyStore — database with a well secured mechanism of data protection, that is used to save, get and remove keys. Requires entrance password and passwords for each of the keys. In other words it is protected file that you need to create, read and update (with provided API).
Certificate — certificate used to validate and save asymmetric keys.
Cipher — provides access to implementations of cryptographic ciphers for encryption, decryption, wrapping, unwrapping and signing.
Provider — defines a set of extensible implementations, independent API’s. Providers are the groups of different Algorithms or their customizations. There are 3rd party providers, such as Bouncy Castle and Spongy Castle (android version of Bouncy Castle), as well as providers available out of box, such as cut-down version of Bouncy Castle (we will take a bit deeper look on them, later on, during this article).
Android Key Store
AndroidKeyStore was introduced in API level 18.
Feature of Android Key Store(AKS):- 
  •  Lets you store cryptographic keys in a container to make it more difficult to extract from the device
  • Once keys are in the key store, they can be used for cryptographic operations with the key material remaining non-exportable
  • It offers facilities to restrict when and how keys can be used, such as requiring user authentication for key use or restricting keys to be used only in certain cryptographic modes
AndroidKeyStore is a JCA Provider implementation, where:
  • No KeyStore passwords is required (really, at all)
  • Key material never enters the application process
  • Key material may be bound to the secure hardware (Trust Zone)
  • Asymmetric keys are available from 18 +
  • Symmetric keys are available from 23 +
Notes:- 
  • If device manufacture supports Trusted Execution Environment(TTE), your keys will be saved there (the most secure option);
  • If device manufacture doesn’t support TTE, keys will be stored in emulated software environment, provided by the system.
  • In both cases, your keys will be automatically removed from the system after deleting the application. 
Also keys material is never exposed, even to us (we will see this later on). We will just work with key references, that is passed to KeyStore System Service, where, under the cover, all dirty work with key materials is done .
Sample Project 
In this project we will save user Secrets, locally, and keep them protected using Encryption, Fingerprint and Confirm Credentials API’s. 
User creates a master password (during sign up process). This password will be used to protect Secrets: to add new, view, edit and delete already created Secrets, user needs to enter master password.
What is Secret ? Anything user want to kept protected: gmail password, credit card pin code
Download Sample Code from Github(coming soon)
In Next Blog I will discuss Lock Screen, Choose a Key, Key Storage, Key Generation, Key Management, Encryption & Decryption, Usage Example

Thanks
Happy Coding!!!!

Sunday, 2 July 2017

Exception handling in JNI and throwing it in Java

Hello Guys!!! Hope You all are doing well.
Today I am going to discuss “Exception handling in JNI and how to throw exception in java from JNI”.
Exception handling generally makes error reporting and handling more readable and easier. But it will be difficult if more than one programming language is used. Here I explain exception handling in JNI (Java Native Interface).
Check for errors and exceptions: JNI side
1.Many JNI functions return a special value to indicate failure. As for example :- FindClass function returns NULL to indicate it failed to load the class. In that case we can simply check the return value to see if an error occurs.
2. Many other functions do not use the return value to signal failure; instead an exception is thrown. JNI defines two functions to check for exceptions, as follows:
  • jboolean ExceptionCheck(JNIEnv *env);
  • jthrowable ExceptionOccurred(JNIEnv *env);
The first function returns JNI_TRUE to indicate that an exception occurs, and JNI_FALSE otherwise. The second function returns a local reference to the exception. When the second function is used, an additional JNI function can be called to examine the details of the exception:
  • void ExceptionDescribe(JNIEnv *env);
The function prints the exception and a back trace of the stack to the logcat. 
In my example code, I used both approaches to check for occurrence of exceptions and ExceptionDescribe to print out the exception details.
There are generally two ways to handle an exception in JNI side.
  1. The first approach is to free the resources allocated at JNI and return. This will leave the responsibility of handling the exception to the caller of the native method.
  2. The second practice is to clear the exception and continue executing. This is done through the following JNI function call: void ExceptionClear(JNIEnv *env);
In my example code 'ExceptionDemo', we used the second approach to clear java.lang.NullPointerException, and the first approach to return java.lang.RuntimeException to the caller, which is the Java method callExceptionDemo at  ExceptionHandlingActivity.java


Throw exceptions in the native code:

JNI provides two functions to throw an exception from native code. They have the following prototypes:

  • jint Throw(JNIEnv *env, jthrowable obj);
  • jint ThrowNew(JNIEnv *env, jclass clazz, const char *message);
The first function accepts a reference to a jthrowable object and throws the exception, while the second function accepts a reference to an exception class. It will create an exception object of the clazz class with the message argument and throw it.
In the ExceptionDemo native method, we used the ThrowNew function to throw java.lang.NullPointerException and a Throw function to throw java.lang.RuntimeException.

Fatal error: 
A special type of error is the fatal error, which is not recoverable. JNI defines a function FatalError, as follows, to raise a fatal error:
  • void FatalError(JNIEnv *env, const char *msg);
This function accepts a message and prints it to logcat. After that, the VM instance for the application is terminated. 
In my example the usage of this function, you find in  FatalErrorDemo and Java method callFatalErrorDemo.
Note:- 
  1. After FatalError function no other code is executed, in neither the native nor Java code, because FatalError never returns, and the VM instance is terminated.
  2. C++ exception is currently not supported on Android JNI programming. Therefore, we should handle C++ exceptions within C++ code. Alternatively, we can write a C wrapper to throw an exception or return an error code to Java.
exceptiontest.c
#include <jni.h>
#include <stdio.h>
#include "ExceptionHandling.h"

JNIEXPORT void JNICALL Java_ExceptionHandling_ExceptionDemo(JNIEnv *pEnv, jobject pObj) {
//  jboolean ExceptionCheck(JNIEnv *env);
//  jthrowable ExceptionOccurred(JNIEnv *env);
    //if no exception pending
    jboolean ifExceptionPending =(*pEnv)->ExceptionCheck(pEnv);
    printf("\n ExceptionCheckDemo :1 %d \n", ifExceptionPending);
    fflush(stdout);

    jthrowable exception = (*pEnv)->ExceptionOccurred(pEnv);
    printf("\n ExceptionOccurred :2 returned NULL? : %d \n",(*pEnv)->IsSameObject(pEnv, exception, NULL));
    fflush(stdout);

    //search for a class which are not available, which will cause an exception
    (*pEnv)->FindClass(pEnv, "java/lang/XXYY");
    //use ExceptionCheck to check
    ifExceptionPending =(*pEnv)->ExceptionCheck(pEnv);
    printf("\nExceptionCheck:3 after finding non-existing class: %d\n", ifExceptionPending);
    fflush(stdout);

    (*pEnv)->ExceptionClear(pEnv);  //clear the exception, so we can proceed
    ifExceptionPending =(*pEnv)->ExceptionCheck(pEnv);
    printf("\nExceptionCheck:4 after clear: %d\n",ifExceptionPending);
    fflush(stdout);

    //throw a java.lang.NullPointerException using ThrowNew
    jclass cls = (*pEnv)->FindClass(pEnv, "java/lang/NullPointerException");
    jint st = (*pEnv)->ThrowNew(pEnv, cls, "throw null pointer exception");
    if (st == 0) {
        printf("\nCheckDemo:5 null pointer exception thrown using ThrowNew\n");
        fflush(stdout);
        (*pEnv)->DeleteLocalRef(pEnv, cls);
    }

    //use ExceptionOccurred to check
    jthrowable exObj = (*pEnv)->ExceptionOccurred(pEnv);
    if (exObj == NULL) {
        printf("\nExceptionCheckDemo :6 no exception\n");
        fflush(stdout);
    } else {
        printf("\nExceptionCheckDemo :7 there's pending exception, call ExceptionDescribe\n");
        fflush(stdout);
        (*pEnv)->ExceptionDescribe(pEnv);   //this does not clear the exception

        ifExceptionPending =(*pEnv)->ExceptionCheck(pEnv);
        printf("\nExceptionCheckDemo :8 ExceptionCheck after ExceptionDescribe: %d\n",ifExceptionPending);
        fflush(stdout);

        (*pEnv)->ExceptionClear(pEnv);      //clear the exception, so we can proceed
        ifExceptionPending =(*pEnv)->ExceptionCheck(pEnv);
        printf("\nExceptionCheckDemo :9 ExceptionCheck after clear: %d\n",ifExceptionPending);
        fflush(stdout);
        (*pEnv)->DeleteLocalRef(pEnv, exObj);
    }

    //throw a java.lang.RuntimeException using Throw
    cls = (*pEnv)->FindClass(pEnv, "java/lang/RuntimeException");
    jmethodID exConstructor = (*pEnv)->GetMethodID(pEnv, cls, "<init>","(Ljava/lang/String;)V");
    //passing UTF-8 string directly to exConstructor won't work because it expects jstring
    //jthrowable rtExObj = (*pEnv)->NewObject(pEnv, reCls, exConstructor, "throw runtime exception");
    jstring msg = (*pEnv)->NewStringUTF(pEnv, "throw runtime exception");
    exObj = (*pEnv)->NewObject(pEnv, cls, exConstructor, msg);
    (*pEnv)->DeleteLocalRef(pEnv, msg);
    if (exObj == NULL) {
        printf("\nExceptionCheckDemo :10 create RuntimeException failed\n");
        fflush(stdout);
    } else {
        jint st = (*pEnv)->Throw(pEnv, exObj);
        if (st == 0) {
            printf("\nExceptionCheckDemo :11 exception thrown using Throw\n");
            fflush(stdout);
            (*pEnv)->DeleteLocalRef(pEnv, cls);
            (*pEnv)->DeleteLocalRef(pEnv, exObj);
        }
        //do not clear the exception, let the caller handle it
    }
}

JNIEXPORT void JNICALL Java_ExceptionHandling_FatalErrorDemo(JNIEnv *pEnv, jobject pObj) {
    (*pEnv)->FatalError(pEnv, "fatal error");
    printf("\nFatalErrorDemo :12 after calling FatalError\n");
    fflush(stdout);
}

//jboolean ExceptionCheck(JNIEnv *env);
//Determines if an exception has been thrown. The exception stays thrown until either the
//native code calls ExceptionClear, or the caller of the native method handles the exception.
//Returns the JNI_TRUE if there is a pending exception, or
//JNI_FALSE if there is no pending exception.

//void ExceptionClear(JNIEnv *env);
//Clears any pending exception that is currently being thrown in the current thread.
//If no exception is currently being thrown, this function has no effect.
//This function has no effect on exceptions pending on other threads.

//void ExceptionDescribe(JNIEnv *env);
//Prints the pending exception and a backtrace of the stack to the system error-reporting
//channel System.out.err. This is a convenience routine provided for debugging.

//jthrowable ExceptionOccurred(JNIEnv *env);
//Determines if an exception is pending in the current thread. The exception stays pending until either
//the native code calls ExceptionClear, or the caller of the native method handles the exception.

//void FatalError(JNIEnv *env, const char *msg);
//Raises a fatal error and does not expect the virtual machine implementation to recover.
//Prints the message in a system debugging channel, such as stderr, and terminates
//the virtual machine instance. This function does not return.

//jint Throw(JNIEnv *env, jthrowable obj);
//Causes a java.lang.Throwable object to be thrown. A thrown exception will be pending in the current thread,
//but does not immediately disrupt native code execution.
//Returns zero on success; otherwise, returns a negative value
//if the specified exception cannot be thrown.

//jint ThrowNew(JNIEnv *env, jclass clazz, const char *message);
//Constructs an exception object from the specified class with the message specified by message
//and causes that exception to be thrown.
ExceptionHandling.java
import java.io.File;
import java.lang.reflect.Field ;

public class ExceptionHandling{

    static {
            String libPath = null;
    try{
      String mPath = new File (".").getCanonicalPath()+"/";
       String langKey = "java.library.path" ;
       System.setProperty ( langKey, mPath ) ;

       libPath = System.getProperty("java.library.path");
       System.out.println("java.library.path=" + libPath);
    }catch(Exception e){
      e.printStackTrace();
    }
    System.load(libPath+"libExceptionHandling.so");
       // System.loadLibrary("ExceptionHandling");
    }

public static void main(String[] args) {
    ExceptionHandling obj = new ExceptionHandling();

    obj.callExceptionDemo();
       // obj.callFatalErrorDemo();

}

    private void callExceptionDemo() {
        try {
            ExceptionDemo();
        } catch (RuntimeException e) {
            String msg = e.getMessage();
            //tv.setText(msg);
            System.out.println(msg);
        }
    }

    private void callFatalErrorDemo() {
        FatalErrorDemo();
        //tv.setText("after calling FatalErrorDemo");
        System.out.println("after calling FatalErrorDemo");
    }

    private native void ExceptionDemo();
    private native void FatalErrorDemo();

}
Thanks
Saurabh 
Happy Coding!!!!

Please put your comment in comment box. It will encourage me. 

Build a Custom Kernel Module for Android

Hi Guys!!!Hope you are doing well !!!. Today I will describe how you can write a custom kernel module(Hello world) for Android and load it a...