Tuesday, 21 October 2014

Simple tips to secure Android app




Android has security features built into the operating system that significantly reduce the frequency and impact of application security issues but as application developer, its our job to secure application. The level of security is depends upon application type & domain. There are  few security aspects we need not forget. I am collecting those common tips in this article.



Here, I list down most common things that developers should take care to protect the application.


1. Do not store private or sensitive data on SDCard. To store file on internal storage, use following methods with private mode (Context.MODE_PRIVATE) openFileOutput & openFileInput. If you really wants to store data in sdcard then encrypt it. You will find many encryption libraries. I prefer conceal from facebook.    



2. Restrict ContentProvider using exported flag set as false. It’s not the case that every time we develop ContentProvider for data exchange between applications but ContentProvider can be developed for single application or private.



<provider android:exported="false" android:name="MyContentProvider" android:authorities="com.example.mycontentprovider" />


3. Restrict WebView to access local data. HTML5 and related technologies have become popular  to develop Mobile Web App app or Hybrid app. For Hybrid uses WebView to display content from locally store HTML or fetch HTML and other content from the server.  Major security concerns for WebView are setAllowFileAccess() and setAllowContentAccess() methods.


4. Do not pass sensitive information through Broadcast & Intent. Use LocalBroadcastManager for broadcast data within process / app. LocalBroadcastManager is available in Support Library V4.


5. Don’t print sensitive information in LogCat. Information like username, password, web service URL, request or response, etc detail.



6. Remove unnecessary Log before publishing app.



7. Don’t process malicious Intents.  Before process Intent received in onReceive method of BroadcastReceiver, validate callers package name, action and other information.



8. Protect your Service with Permission. Use exposed flag as  false When Service is developed for your app only.
 

9. Restrict access to Activities. If the activity is intended solely for the internal use of the app then use exported flag set as false.


<activity android:name=".view.MyActivity" android:exported="false"> </activity>


10.  Make sure that debug mode is false before publish APK.
 


11. Encrypt sensitive data even if you store in internal storage.
 


12. For cross app functionality, validate calling application before response. 
 


13. Properly verify server certificate TLS/SSL for HTTPS web call.
 


14. Use NDK whenever you feel that information is not safe in Java code because It can decompile easily. i.e. Constant.
 


15. Use ProGuard that shrinks, optimizes, and obfuscates your code.
 


16. Remove unwanted / unused <user-permission> from AndroidManifest.xml
 


17. Loading classes.dex outside of application is major security risk. DexClassLoader allowed developer to load classes.dex on demand.



Monday, 20 October 2014

In Depth : Android Boot Sequence / Process


What happened when I press power on button in my Android device ?
What is Android boot sequence ?
What is linux kernel ?
What is different between desktop linux kernel and Android linux kernel ?
What is bootloader ?
What is Zygote ?
What is x86 and ARM linux ?
What is init.rc ?
What is System Server ?

Many questions pop-up in mind when we think about Android boot sequence.


Here I am explaining Android boot process. I hope you will find answer of above questions.




Android is linux based open source operating system, x86 (x86 is a series of computer microprocessor instruction set architectures based on the Intel 8086 CPU.) is most likely system where linux kernel is deployed however all Android devices are running on ARM process (ARM (formerly Advanced RISC Machine, which was formerly Acorn RISC Machine)) except Intel’s Xolo device (http://xolo.in/xolo-x900-features). Xolo comes with Atom 1.6 GHz x86 processor. Android boot sequence or I can say embedded device or ARM based linux has minor difference compare to desktop version.  In this article I am going to explain boot sequence for Android only. Inside the linux boot process is good article for desktop based linux boot sequence.
Android device execute following steps when you press power switch
Android Boot Sequence / Process
Android Boot Sequence / Process
Step 1 : Power On and System Startup

When power start Boot ROM code start execution from pre defined location which is hardwired on ROM. It load Bootloader into RAM and start execution

Step 2 : Bootloader

Bootloader is small program which runs before Android operating system running. Bootloader is first program to run so It is specific for board and processor. Device manufacturer either use popular bootloaders like redboot,uboot, qi bootloader or they develop own bootloaders, It’s not part of Android Operating System. bootloader is the place where OEMs and Carriers put there locks and restrictions.

Bootloader perform execution in two stages, first stage It to detect external RAM and load program which helps in second stage, In second stage bootloader setup network, memory, etc. which requires to run kernel, bootloader is able to provide configuration parameters or inputs to the kernel for specific purpose.  

Android bootloader can be found at 
<Android Source>\bootable\bootloader\legacy\usbloaderlegacy loader contain two important files that need to address here.
1. init.s - Initializes stacks, zeros the BSS segments, call _main() in main.c
2. main.c - Initializes hardware (clocks, board, keypad, console), creates Linux tags

Refer this link to know more about Android bootloader :
https://motorola-global-portal.custhelp.com/app/answers/detail/a_id/86208/~/bootloader-frequently-asked-questions

Step 3: Kernel

Android kernel start similar way as desktop linux kernel starts, as kernel launch it start setup cache, protected memory, scheduling, loads drivers. When kernel finish system setup first thing it look for “init” in system files and launch root process or first process of system.  

Step 4: init process

init it very first process, we can say it is root process or grandmother of all processes. init process has two responsibilities 1. mount directories like /sys, /dev, /proc and 2. run init.rc script.

  • init process can be found at init : <android source>/system/core/init
  • init.rc file can be found in source tree at <android source>/system/core/rootdir/init.rc
  • readme.txt file can be found in source tree at <andorid source>/system/core/init/readme.txt

Android has specific format and rules for init.rc files. In Android we call it as “Android Init Language”

The Android Init Language consists of four broad classes of statements,which are Actions, Commands, Services, and Options.

Action : Actions are named sequences of commands.  Actions have a trigger which is used to determine when the action should occur.

Syntax
on <trigger>
  <command>
  <command>
  <command>

Service :  Services are programs which init launches and (optionally) restarts when they exit.  Syntax

service <name> <pathname> [ <argument> ]*
  <option>
  <option>
  ...

Options : Options are modifiers to services.  They affect how and when init runs the service.

Let’s take a look of default init.rc file. Here I have listed only major events and services.


Action / ServiceDescription
on early-initSet init and its forked children's oom_adj.
Set the security context for the init process.
on initsetup the global environment
Create cgroup mount point for cpu accounting
and many
on fsmount mtd partitions
on post-fschange permissions of system directories
on post-fs-datachange permission of /data folders and sub folders
on bootbasic network init ,Memory Management ,etc
service servicemanagerstart system manager to manage all native services like location, audio, shared preference etc..
service zygotestart zygote as app_process

At this stage you can see “Android” logo on device screen.

Step 5: Zygote and Dalvik

In a Java, We know that separate Virtual Machine(VMs) instance will popup in memory for separate per app, In case of Android app should launch as quick as possible, If Android os launch different instance of Dalvik VM for every app then it consume lots of memory and time. so, to overcome this problem Android OS as system named “Zygote”. Zygote enable shared code across Dalvik VM, lower memory footprint and minimal startup time. Zygote is a VM process that starts at system boot time as we know in previous step. Zygote preloads and initialize core library classes.  Normally there core classes are read-only and part of Android SDK or Core frameworks. In Java VM each instance has it’s own copy of core library class files and heap objects.

Zygote loading process

1. Load ZygoteInit class,
Source Code :<Android Source> /frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
2. registerZygoteSocket() -  Registers a server socket for zygote command connections
3. preloadClasses() - “preloaded-classes” is simple text file contains list of classes that need to be preloaded, you cna find “preloaded-classes” file at <Android Source>/frameworks/base
4. preloadResources() - preloadReaources means native themes and layouts, everything that include android.R file will be load using this method.

At this time you can see bootanimation


Step 6: System  Service or Services

After complete above steps, runtime request Zygote to launch system servers. System Servers are written in native and java both, System servers we can consider as process, The same system server is available as System Services in Android SDK. System server contain all system services.

Zygote fork new process to launch system services. You can find source code in ZygoteInit class and “startSystemServer” method.

Core Services:
1.     Starting Power Manager
2.     Creating Activity Manager
3.     Starting Telephony Registry
4.     Starting Package Manager
5.     Set Activity Manager Service as System Process
6.     Starting Context Manager
7.     Starting System Context Providers
8.     Starting Battery Service
9.     Starting Alarm Manager
10.   Starting Sensor Service
11.   Starting Window Manager
12.   Starting Bluetooth Service
13.   Starting Mount Service

Other services
1.    Starting Status Bar Service
2.     Starting Hardware Service
3.     Starting NetStat Service
4.     Starting Connectivity Service
5.     Starting Notification Manager
6.     Starting DeviceStorageMonitor Service
7.     Starting Location Manager
8.     Starting Search Service
9.     Starting Clipboard Service
10.   Starting Checkin Service
11.   Starting Wallpaper Service
12.   Starting Audio Service
13.   Starting HeadsetObserver
14.   Starting AdbSettingsObserver
Step 7 : Boot Completed

Once System Services up and running in memory, Android has completed booting process, At this time “ACTION_BOOT_COMPLETED” standard broadcast action will fire.

Monday, 21 July 2014

Android - Reading images from assets file




Hi all here is my first blog, I am really exited. Here is my first Android application example.

MainActivity.java file

public class MainActivity extends ActionBarActivity {

@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ImageView image = (ImageView) findViewById(R.id.image);

try {
Drawable d = Drawable.createFromStream(getAssets().open("ic_launcher.png"), null); // here I am calling my image from asset file

image.setBackgroundDrawable(d);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

and our layout file will be activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.nktech.assetimagereader.MainActivity" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
 
    <ImageView
        android:id="@+id/image"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_below="@+id/text"/>

</RelativeLayout>

android in asset file I have ic_launcher.png image file (assets/ic_laucher.png)