28
1 Android Applications Android Security - SS 2016

Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

1

Android Applications

Android Security - SS 2016

Page 2: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

BIG PICTURE

(Android Anatomy and Physiology, Patrick Brady)

Java

Dalvik

Native (C/C++)

OS

Android Security - SS 2016 2

Page 3: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

APPLICATIONS

§ Thirdpartyapplications

- Installedbytheuser

- e.g.,fromGooglePlay,AmazonStore,etc.

§ Anumberofcore(“system”)applications(cannotbeuninstalled)- Contacts,Settings,Browser,Phone,…

- Specialflaginthepackagemanagertomarkthemassystemapplication

- ComplementtheimplementationoftheapplicationframeworkAPI

• Contactsmanagement,initiatingphonecalls,SMS/MMSmanagement,…

3Android Security - SS 2016

Page 4: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

APPLICATION PACKAGES (APK)

§ APKissimplyapackagingformatlikeJAR,ZIP,orTAR

Android Security - SS 2016 4

Page 5: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

APPLICATION PACKAGES (APK)

§ APKissimplyapackagingformatlikeJAR,ZIP,orTAR

§ Componentsofapplications- Activity: Userinterface

- Service: Backgroundservice- ContentProvider: SQL-likedatabase- Broadcastreceiver: Mailboxforbroadcastedmessages

§ Applicationscancontainnativecode(C/C++sharedlibraries)andresources(e.g.,images)- Nativecodeprovidedassharedlibraryfilesthatcanbedynamicallylinkedintothe

process

- Resourcesandassets:Stringvalues,layoutdefinitions,drawables (pictures),rawdata

§ META-INFcontainstheapplicationcertificateandpackagemanifest- Packagemanifestnottobemistakenwiththeapplicationmanifest!

APK

Classes.dex Native libs Resources

Android Security - SS 2016 5

META-INF ApplicationManifest

Page 6: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

APPLICATION PACKAGES (APK)

§ APKissimplyapackagingformatlikeJAR,ZIP,orTAR

Android Security - SS 2016 6

Page 7: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

APPLICATION MANIFEST.XML

§ Declaresapplicationmeta-dataandallcomponents

- Names,filters,permissions,…

§ Verybasicexample:

7Android Security - SS 2016

<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.android.app"android:versionCode="1” android:versionName="1.0" >

<uses-sdk android:minSdkVersion="18” android:targetSdkVersion="18" />

<applicationandroid:icon="@drawable/ic_launcher"android:label="@string/app_name”><activity android:name="com.example.android.app.MainActivity” android:label="@string/app_name”>

<intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" />

</intent-filter></activity><receiver android:name=”.MyReceiver" >

<intent-filter><action android:name="android.intent.action.BOOT_COMPLETED" />

</intent-filter></receiver>...

</application></manifest>

Packageinfo(Packagename,Version)

Appinfo(Launchericon,etc.)

Activitycomponent

BroadcastReceiver component

Page 8: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

ACTIVITY COMPONENT

§ Representsasinglescreeninyourapplication

- ComposedofdifferentViews (Buttons,lists,text,…)

- CanbesplitintodifferentFragments (≈Sub-Activitiesonsamescreenatatime)

§ Activitylifecycle:

8Android Security - SS 2016

Page 9: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

EXAMPLE ACTIVITY COMPONENT

Android Security - SS 2016 9

<LinearLayout 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:gravity="center_horizontal"...tools:context="app.android.example.com.myapplication.LoginActivity">

<ScrollViewandroid:id="@+id/login_form"android:layout_width="match_parent"android:layout_height="match_parent">

<LinearLayoutandroid:id="@+id/email_login_form"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical">

<android.support.design.widget.TextInputLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content">

<AutoCompleteTextViewandroid:id="@+id/email"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="@string/prompt_email"android:inputType="textEmailAddress"android:maxLines="1"android:singleLine="true" />

</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content">

<EditTextandroid:id="@+id/password"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="@string/prompt_password"...android:inputType="textPassword"android:maxLines="1"android:singleLine="true" />

</android.support.design.widget.TextInputLayout>

<Buttonandroid:id="@+id/email_sign_in_button"...android:text="@string/action_sign_in"android:textStyle="bold" />

</LinearLayout></ScrollView>

</LinearLayout>

Page 10: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

EXAMPLE ACTIVITY COMPONENT

package app.android.example;

...

public class LoginActivity extends AppCompatActivity {

...

// UI references.private AutoCompleteTextView mEmailView;private EditText mPasswordView;private View mProgressView;private View mLoginFormView;

@Overrideprotected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);setContentView(R.layout.activity_login);// Set up the login form.mEmailView = (AutoCompleteTextView) findViewById(R.id.email);populateAutoComplete();

mPasswordView = (EditText) findViewById(R.id.password);mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

@Overridepublic boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {

if (id == R.id.login || id == EditorInfo.IME_NULL) {attemptLogin();return true;

}return false;

}});

Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);mEmailSignInButton.setOnClickListener(new OnClickListener() {

@Overridepublic void onClick(View view) {

attemptLogin();}

});

mLoginFormView = findViewById(R.id.login_form);mProgressView = findViewById(R.id.login_progress);

}

...}

Android Security - SS 2016 10

• Declare some UI elements• View is basic class for UI elements

• Find UI objects, which have been declared in activity_login.xml, using their ID

• Find password text input UI• Set action to be performed

on event, e.g., enter key pressed

• Find button UI element• Set action to be performed

when button is clicked

• Find some other UI elements

Page 11: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

INTENT MESSAGE

§ Dataobjectthatrepresentstheintent todosomething

- LaunchinganActivity,startingaService,broadcastamessage,…

• Payloadandattributesdescribetheintendedaction

- Canbesentandreceivedbyanapplication

• TransmittedbetweenapplicationsviaBinder-basedIPC

11Android Security - SS 2016

https://developer.android.com/guide/components/intents-filters.html

Page 12: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

INTENT MESSAGE

§ Receivercanbedescribedexplicitorimplicit

- Explicit:Settargetcomponentname

• “com.example.app.MainActivity”• Intent(Context packageContext, Class<?> cls)

Createanintentforaspecificcomponent.

Intent(String action, Uri uri, Context packageContext, Class<?> cls)Createanintentforaspecificcomponentwithaspecifiedactionanddata.

- Implicit:SetanActionstring,Category,andData;theAndroidframeworkwillfindasuitablereceiverforthisIntent

• Action=Intent.ACTION_VIEW ;Data=“http://www.google.com”willopenappthatcanshowthewebsite,e.g.,thedefaultbrowserapp

• Intent(String action)Createanintentwithagivenaction.

Intent(String action, Uri uri)Createanintentwithagivenactionandforagivendataurl.

12Android Security - SS 2016

Page 13: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

EXAMPLE SENDING INTENTS

Intent intent = new Intent(Intent.ACTION_VIEW);intent.setData(Uri.parse("http://www.google.com"));activity.startActivity(intent);

Android Security - SS 2016 13

Intent intent = new Intent(Intent.ACTION_VIEW); //geo:lat,long?z=zoomlevel&q=question-string intent.setData(Uri.parse("geo:0,0?z=4&q=bakery"));activity.startActivity(intent);

Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:555–555–5555")); activity.startActivity(intent);

Will implicitly start an application that can handle http URIs, e.g., a browser, which then will react to this data, here, e.g., showing the Google website

Will implicitly start an application that can handle geo URIs, e.g., Google Maps app, which then will react to this data, here, e.g., searching maps for the terms ”bakery” at the give location

Will implicitly start an application that can handle ACTION_CALL action strings and tel URI, e.g., Telephony app, which then will react to this data, here, e.g., calling the number 555-555-5555

Intent intent = new Intent("app.android.example.MainActivity"); activity.startActivity(intent); Explicitly start the component

MainActivity of the app with the package name app.android.example(no payload provided here)

Intent newAct = new Intent(this, MainActivity.class);startActivity(newAct); Explicitly start the component

MainActivity within the same package as the caller (no payload provided here)

Page 14: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

INTENT-FILTERS

§ DeclaredinthemanifestforIntent-receivingcomponentstospecifywhichkindsofIntents(e.g.,actionstring,classname,datapayload)thiscomponentswantstoreceive

Android Security - SS 2016 14

<activity android:name="MainActivity"><!-- This activity is the main entry, should appear in app launcher --><intent-filter>

<action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" />

</intent-filter></activity>

<activity android:name="ShareActivity"><!-- This activity handles "SEND" actions with text data --><intent-filter>

<action android:name="android.intent.action.SEND"/><category android:name="android.intent.category.DEFAULT"/><data android:mimeType="text/plain"/>

</intent-filter><!-- This activity also handles "SEND" and "SEND_MULTIPLE" with media data --><intent-filter>

<action android:name="android.intent.action.SEND"/><action android:name="android.intent.action.SEND_MULTIPLE"/><category android:name="android.intent.category.DEFAULT"/><data android:mimeType="application/vnd.google.panorama360+jpg"/><data android:mimeType="image/*"/><data android:mimeType="video/*"/>

</intent-filter></activity>

Page 15: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

USER-CHOICE FOR APPLICATION?

§ Whatifmultipleapplications’intent-filtersmatchanIntent?

- UserhassetadefaultapplicationforthisactionorSystemasksusertoselectatargetapplication

Android Security - SS 2016 15

Page 16: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

SERVICE COMPONENTS

§ Backgroundprocesseswithoutuserinteraction

- Potentiallylongrunning

• E.g.pollingemailsfromawebserver

§ Canbelocaltotheapporremote(providedbyanotherapp)

- Remote:Interfacecanbedefinedindomain-specificlanguageAndroidInterfaceDefinitionLanguage(AIDL)

• AIDLcompilercreatesskeletonforimplementationofservice(stub)andaproxy objectabstractingtheserviceandencapsulating

• CommonapproachtoimplementtheAndroidapplicationframeworkAPI(Locationmanager,Wi-Fimanager,etc.)

§ Canbestarted byaclientorbebound byoneormoreclients

16Android Security - SS 2016

Page 17: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

SERVICE LIFECYCLE

17Android Security - SS 2016

Page 18: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

STUBS AND PROXIES:ABSTRACT

18Android Security - SS 2016

AppA AppB

Component(e.g.Activity)

BServiceProxyint foo(String);

BServiceStub

Stub implementationint foo(String) { return 42; }

Call foo(“bar”)

KernelBinder-based Inter-Process Communication (IPC)

Page 19: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

EXAMPLE SERVICE INTERFACE DEFINITION IN AIDL

MyService.aidl:

package com.example.android;

interface MyService {

int foo(in String bar);

}

Android Security - SS 2016 19

Page 20: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

EXAMPLE AUTO-GENERATED PROXY AND STUB FROM AIDL

IMyService.java:

/** This file is auto-generated. DO NOT MODIFY.* Original file: /Users/sven/android_coding_share/apps/TestApp/src/com/example/android/MyService.aidl*/

package com.example.android;public interface MyService extends android.os.IInterface{/** Local-side IPC implementation stub class. */public static abstract class Stub extends android.os.Binder implements com.example.android.MyService{private static final java.lang.String DESCRIPTOR = "com.example.android.MyService";...

@Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException{switch (code){...case TRANSACTION_bar:{data.enforceInterface(DESCRIPTOR);String _arg0;_arg0 = data.readString();int _result = this.foo(_arg0);reply.writeNoException();reply.writeInt(_result);return true;}...private static class Proxy implements com.example.roundtrip2.IRR2Service{private android.os.IBinder mRemote;Proxy(android.os.IBinder remote){...@Override public int foo(String bar) throws android.os.RemoteException{android.os.Parcel _data = android.os.Parcel.obtain();android.os.Parcel _reply = android.os.Parcel.obtain();int _result;try {_data.writeInterfaceToken(DESCRIPTOR);_data.writeString(bar);mRemote.transact(Stub.TRANSACTION_foo, _data, _reply, 0);_reply.readException();_result = _reply.readInt();}...return _result;}...

Android Security - SS 2016 20

Stub: Receiving side, i.e., has to be subclassed by the Service implementation (e.g., takes care of reading the Parcel and calling method implementation)

Proxy: Used by sender to call the service (e.g., takes care of writing a Parcel and sending (“transact”) it to remote process

Page 21: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

EXAMPLE STUB IMPLEMENTATION

MyService.java:

public class MyService extends Service {

...

@Overridepublic IBinder onBind(Intent intent) {

return mBinder;}

private final MyService.Stub mBinder = new MyService.Stub() {public int foo(String bar) {

return 42;};

}

...

}

Android Security - SS 2016 21

Page 22: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

STUBS AND PROXIES:CONCRETE EXAMPLE

22Android Security - SS 2016

Source: https://thenewcircle.com/s/post/1340/Deep_Dive_Into_Binder_Presentation.htm#slide-11

1

2

3

4

5

Page 23: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

CONTENTPROVIDER COMPONENTS

§ Standardizedmechanismtosharedataamongapplications

- Contactsdata,SMSdata,mediametadata,…

§ SQLite-likedatamanagement

- Insert,Delete,Update,Query

§ URIstoaddressContentProviders andtheirdata:

23Android Security - SS 2016

content://com.example.android.BookProvider/book/23

Scheme Authorityname PathSegments

id Title Author ID

1 Embedded Android 1

23 Pro Android 4 42

id Name

1 K. Yaghmour

42 S. Komatinie & D. MacLean

com.example.android.BookProvider

Table: book Table: author

Page 24: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

EXAMPLE QUERYING A PROVIDER

String URL = "content://com.example.android.BookProvider/book/";

mCursor = getContentResolver().query(URL, // The content URI of the books tablemProjection, // String[] of table columns to return for each rowmSelectionClause // Selection criteria (“where” clause)mSelectionArgs, // Selection criteria (arguments for “where” clause)mSortOrder); // The sort order for the returned rows

int numcols = mCursor.getColumnCount();String[] colnames = mCursor.getColumnNames();

mCursor.moveToFirst();while (cursor.moveToNext()) {

// Do something with the rowint id = mCursor.getInt(0); // id is first columnString author = mCursor.getString(1); // Author name is in 2nd columnint author_id = mCursor.getInt(2); // Author ID is in 3rd column (x-ref to author table)

}mCursor.close();

Android Security - SS 2016 24

Page 25: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

BROADCASTRECEIVER COMPONENTS

§ MailboxforbroadcastIntentmessages- Definefilterswhichkindofmessagestoreceive

• Actionstring,category,…

§ Registeredintheapplicationmanifestordynamicallyatruntime- registerReceiver(BroadcastReceiver receiver, IntentFilter filter)

§ Veryshort-lived,boundtoprocessingtheIntent- Kick-offlonger-livedworkloadstoActivitiesorServices

§ CommonoperationstolistentowithaBroadcastReceiver- Locationchanges

- Userpresence(unlockingthescreen)

- Finishedbootingofthedevice(“autostart”ofapp)

- SMS/MMSreceived

- etc

25Android Security - SS 2016

Page 26: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

EXAMPLE SENDER AND RECEIVER

TestSender.java:

...Intent intent = new Intent();intent.setAction(“com.android.example.TEST_BROADCAST”);intent.putExtra(“message”, “Hello World!”);sendBroadcast(intent);

Manifestofreceivingapp:...<receiver android:name=".TestReceiver">

<intent-filter> <action android:name=" com.android.example.TEST_BROADCAST "/></intent-filter> </receiver> ...

TestReceiver.java:

public class TestReceiver extends BroadcastReceiver { private static final String tag = "TestReceiver";

@Override public void onReceive(Context context, Intent intent) { String message = intent.getStringExtra("message");Log.d(tag, message); // Log message content

}

}

Android Security - SS 2016 26

Page 27: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

ANDROID RUNTIME

§ Dalvik VirtualMachine(DVM;priortoAndroid5.0)- VMoptimizedforembeddedenvironments

- Runsoptimizedfileformat“.dex”andDalvik bytecode generatedfromJava.class/.jarfilesatbuildtime

- ReliesonunderlyingLinuxkernelforthreadingandlow-levelmemorymanagement

§ AndroidRuntime(ART;sinceAndroid5.0)- IntroducedAhead-of-time(AOT)compilationof.dex fileswithon-devicedex2oatcompiler

toolincludingcodeoptimizingbackens

- AddressperformanceissuesofDVM

§ CoreLibraries- Providemostofthefunctionalityavailableinthe

corelibrariesofJava

- ProvidescoreAPIsofJava(familiarprogrammingenvironment)

Android Security - SS 2016 27

ART

Page 28: Android Applications - Universität des Saarlandes...Can be local to the app or remote (provided by another app) - Remote: Interface can be defined in domain-specific language Android

RECAP

§ Androidappsconsistofseveralcomponents (Activities,Services,etc.)

§ ComponentsareregisteredinthesystemthroughtheapplicationManifest.xml

- BroadcastReceivers canalsoberegisteredatruntime

§ PrimarychannelforInter-Component-Communication areIntents

- BoundservicesandContentProviders canalsobecontacteddirectlyafterreceivingareferencesfromtheAndroidsystem

Android Security - SS 2016 28