Android Security - Misra, Anmol

871

description

Android Security is must as cyber crimes and cyber abuses are increasing day by day...!!!

Transcript of Android Security - Misra, Anmol

Page 1: Android Security - Misra, Anmol
Page 2: Android Security - Misra, Anmol

ANDROIDSECURITY

ATTACKS AND DEFENSES

ABHISHEK DUBEY |ANMOL MISRA

Page 3: Android Security - Misra, Anmol
Page 4: Android Security - Misra, Anmol

CRC PressTaylor & Francis Group6000 Broken Sound Parkway NW, Suite 300Boca Raton, FL 33487-2742

© 2013 by Taylor & Francis Group, LLCCRC Press is an imprint of Taylor & FrancisGroup, an Informa business

No claim to original U.S. Government worksVersion Date: 20130403

International Standard Book Number-13: 978-1-4822-0986-0 (eBook - ePub)

This book contains information obtained fromauthentic and highly regarded sources.Reasonable e orts have been made to publishreliable data and information, but the author and

Page 5: Android Security - Misra, Anmol

publisher cannot assume responsibility for thevalidity of all materials or the consequences oftheir use. The authors and publishers haveattempted to trace the copyright holders of allmaterial reproduced in this publication andapologize to copyright holders if permission topublish in this form has not been obtained. If anycopyright material has not been acknowledgedplease write and let us know so we may rectify inany future reprint.

Except as permitted under U.S. Copyright Law,no part of this book may be reprinted,reproduced, transmitted, or utilized in any formby any electronic, mechanical, or other means,now known or hereafter invented, includingphotocopying, micro lming, and recording, or inany information storage or retrieval system,

Page 6: Android Security - Misra, Anmol

without written permission from the publishers.

For permission to photocopy or use materialelectronically from this work, please accesswww.copyright.com(http://www.copyright.com/) or contact theCopyright Clearance Center, Inc. (CCC), 222Rosewood Drive, Danvers, MA 01923, 978-750-8400. CCC is a not-for-pro t organization thatprovides licenses and registration for a variety ofusers. For organizations that have been granted aphotocopy license by the CCC, a separate systemof payment has been arranged.

Trademark Notice: Product or corporate namesmay be trademarks or registered trademarks, andare used only for identi cation and explanationwithout intent to infringe.

Page 7: Android Security - Misra, Anmol

Visit the Taylor & Francis Web site athttp://www.taylorandfrancis.com

and the CRC Press Web site athttp://www.crcpress.com

Page 8: Android Security - Misra, Anmol

Dedication

To Mom, Dad, Sekhar, andAnupam- Anmol

To Maa, Papa, and Anubha- Abhishek

Page 9: Android Security - Misra, Anmol

Contents

Dedication

Foreword

Preface

About the Authors

Acknowledgments

Chapter 1 Introduction1.1 Why Android1.2 Evolution of Mobile

Page 10: Android Security - Misra, Anmol

Threats1.3 Android Overview1.4 Android Marketplaces1.5 Summary

Chapter 2 Android Architecture2.1 Android Architecture

Overview2.1.1 Linux Kernel2.1.2 Libraries2.1.3 Android Runtime2.1.4 Application

Framework2.1.5 Applications

2.2 Android Start Up and

Page 11: Android Security - Misra, Anmol

Zygote2.3 Android SDK and Tools

2.3.1 Downloading andInstalling theAndroid SDK 29

2.3.2 Developing withEclipse and ADT

2.3.3 Android Tools2.3.4 DDMS2.3.5 ADB2.3.6 ProGuard

2.4 Anatomy of the “HelloWorld” Application2.4.1 Understanding

Hello World

Page 12: Android Security - Misra, Anmol

2.5 Summary

Chapter 3 Android ApplicationArchitecture

3.1 Application Components3.1.1 Activities3.1.2 Intents3.1.3 Broadcast Receivers3.1.4 Services3.1.5 Content Providers

3.2 Activity Lifecycles3.3 Summary

Chapter 4 Android (in)Security4.1 Android Security Model

Page 13: Android Security - Misra, Anmol

4.2 Permission Enforcement—Linux

4.3 Android’s ManifestPermissions4.3.1 Requesting

Permissions4.3.2 Putting It All

Together4.4 Mobile Security Issues

4.4.1 Device4.4.2 Patching4.4.3 External Storage4.4.4 Keyboards4.4.5 Data Privacy4.4.6 Application

Page 14: Android Security - Misra, Anmol

Security4.4.7 Legacy Code

4.5 Recent Android Attacks—AWalkthrough4.5.1 Analysis of

DroidDream Variant4.5.2 Analysis of Zsone4.5.3 Analysis of Zitmo

Trojan4.6 Summary

Chapter 5 Pen Testing Android5.1 Penetration Testing

Methodology5.1.1 External

Page 15: Android Security - Misra, Anmol

Penetration Test5.1.2 Internal

Penetration Test5.1.3 Penetration Test

Methodologies5.1.4 Static Analysis5.1.5 Steps to Pen Test

Android OS andDevices 100

5.2 Tools for PenetrationTesting Android5.2.1 Nmap5.2.2 BusyBox5.2.3 Wireshark5.2.4 Vulnerabilities in

Page 16: Android Security - Misra, Anmol

the Android OS5.3 Penetration Testing—

Android Applications5.3.1 Android

Applications5.3.2 Application

Security5.4 Miscellaneous Issues5.5 Summary

Chapter 6 Reverse EngineeringAndroid Applications

6.1 Introduction6.2 What is Malware?6.3 Identifying Android

Page 17: Android Security - Misra, Anmol

Malware6.4 Reverse Engineering

Methodology for AndroidApplications

6.5 Summary

Chapter 7 Modifying theBehavior of AndroidApplications withoutSource Code

7.1 Introduction7.1.1 To Add Malicious

Behavior7.1.2 To Eliminate

Malicious Behavior7.1.3 To Bypass Intended

Page 18: Android Security - Misra, Anmol

Functionality7.2 DEX File Format7.3 Case Study: Modifying the

Behavior of an Application7.4 Real World Example 1—

Google Wallet Vulnerability161

7.5 Real World Example 2—Skype Vulnerability (CVE-2011-1717)

7.6 Defensive Strategies7.6.1 Perform Code

Obfuscation7.6.2 Perform Server Side

Processing

Page 19: Android Security - Misra, Anmol

7.6.3 Perform IterativeHashing and UseSalt

7.6.4 Choose the RightLocation forSensitiveInformation

7.6.5 Cryptography7.6.6 Conclusion

7.7 Summary

Chapter 8 Hacking Android8.1 Introduction8.2 Android File System

8.2.1 Mount Points

Page 20: Android Security - Misra, Anmol

8.2.2 File Systems8.2.3 Directory Structure

8.3 Android Application Data8.3.1 Storage Options8.3.2 /data/data

8.4 Rooting Android Devices8.5 Imaging Android8.6 Accessing Application

Databases8.7 Extracting Data from

Android Devices8.8 Summary

Chapter 9 Securing Android forthe Enterprise

Page 21: Android Security - Misra, Anmol

Environment9.1 Android in Enterprise

9.1.1 Security Concernsfor Android inEnterprise

9.1.2 End-UserAwareness

9.1.3 Compliance/AuditConsiderations

9.1.4 RecommendedSecurity Practicesfor Mobile Devices

9.2 Hardening Android9.2.1 Deploying Android

Securely

Page 22: Android Security - Misra, Anmol

9.2.2 DeviceAdministration

9.3 Summary

Chapter 10 Browser Security andFuture ThreatLandscape

10.1 Mobile HTML Security10.1.1 Cross-Site

Scripting10.1.2 SQL Injection10.1.3 Cross-Site Request

Forgery10.1.4 Phishing

10.2 Mobile Browser Security

Page 23: Android Security - Misra, Anmol

10.3 10.2.1 BrowserVulnerabilities

10.4 The Future Landscape10.3.1 The Phone as a

Spying/TrackingDevice

10.3.2 ControllingCorporate Networksand Other Devicesthrough MobileDevices

10.3.3 Mobile Walletsand NFC

10.4 Summary

Appendix A

Page 24: Android Security - Misra, Anmol

Appendix BB.1 ViewsB.2 Code ViewsB.3 Keyboard ShortcutsB.4 Options

Appendix C

Glossary

Index

Page 25: Android Security - Misra, Anmol

Foreword

Ever-present cyber threats havebeen increasing against mobiledevices in recent years. As Androidemerges as the leading platform formobile devices, security issuesassociated with the Androidplatform become a growingconcern for personal andenterprise customers. AndroidSecurity: Attacks and Defensesprovides the reader with a sense ofpreparedness by breaking downthe history of Android and its

Page 26: Android Security - Misra, Anmol

features and addressing themethods of attack, ultimatelygiving professionals, from mobileapplication developers to securityarchitects, an understanding of thenecessary groundwork for a gooddefense.

In the context and broad realmof mobility, Dubey and Misra bringinto focus the rise of Android to thescene and the security challenges ofthis particular platform. They gobeyond the basic security conceptsthat are already readily availableto application developers to tackleessential and advanced topics suchas attack countermeasures, the

Page 27: Android Security - Misra, Anmol

integration of Android within theenterprise, and the associatedregulatory and compliance risks toan enterprise. By reading thisbook, anyone with an interest inmobile security will be able to getup to speed on the Androidplatform and will gain a strategicperspective on how to protectpersonal and enterprise customersfrom the growing threats to mobiledevices. It is a must-have forsecurity architects and consultantsas well as enterprise securitymanagers who are working withmobile devices and applications.

Dr. Dena Haritos Tsamitis

Page 28: Android Security - Misra, Anmol

Director, Information NetworkingInstitute (INI)

Director of Education, Training,and Outreach, CyLab

Carnegie Mellon University

Dr. Dena Haritos Tsamitis headsthe Information NetworkingInstitute (INI), a global,interdisciplinary departmentwithin Carnegie MellonUniversity’s College ofEngineering. She oversees the INI’sgraduate programs in informationnetworking, information securitytechnology and management, andinformation technology. Under her

Page 29: Android Security - Misra, Anmol

leadership, the INI expanded itsprograms to global locations andled the design of bicoastalprograms in information security,mobility, and softwaremanagement in collaboration withCarnegie Mellon’s Silicon Valleycampus. Dena also directseducation, training and outreachfor Carnegie Mellon CyLab. Sheserves as the principal investigatoron two educational programs ininformation assurance funded bythe NSF—the CyberCorpsScholarship for Service and theInformation Assurance CapacityBuilding Program—and she is also

Page 30: Android Security - Misra, Anmol

the principal investigator on theDOD-funded Information AssuranceScholarship Program. She receivedthe 2012 Barbara Lazarus Awardfor Graduate Student and JuniorFaculty Mentoring from CarnegieMellon and the 2008 Women ofIn uence Award, presented by AltaAssociates and CSO Magazine, forher achievements in informationsecurity and education.

Page 31: Android Security - Misra, Anmol

Preface

The launch of the Apple iPhone in2007 started a new era in theworld of mobile devices andapplications. Google’s Androidplatform has emerged as a seriousplayer in the mobile devicesmarket, and by 2012, moreAndroid devices were being soldthan iPhones. With mobile devicesbecoming mainstream, we haveseen the evolution of threatsagainst them. Android’s popularityhas brought it attention from the

Page 32: Android Security - Misra, Anmol

“bad guys,” and we have seenattacks against the platform on theuptick.

About the Book

In this book, we analyze theAndroid platform and applicationsin the context of security concernsand threats. This book is targetedtowards anyone who is interestedin learning about Android securityor the strengths and weaknesses ofthis platform from a securityperspective. We describe theAndroid OS and applicationarchitecture and then proceed toreview security features provided

Page 33: Android Security - Misra, Anmol

by the platform. We then describemethodology for analyzing andsecurity testing the platform andapplications. Towards the end, wecover implications of Androiddevices in the enterpriseenvironment as well as steps toharden devices and applications.Even though the book focuses onthe Android platform, many ofthese issues and principles can beapplied to other leading platformsas well.

Assumptions

This book assumes that the readeris familiar with operating systems

Page 34: Android Security - Misra, Anmol

and security concepts. Knowledgeof penetration testing, threatmodeling, and common Webapplication and browservulnerabilities is recommended butnot required.

Audience

Our book is targeted at securityarchitects, system administrators,enterprise SDLC managers,developers, white-hat hackers,penetration testers, IT architects,CIOs, students, and regular users. Ifyou want to learn about Androidsecurity features, possible attacksand means to prevent them, you

Page 35: Android Security - Misra, Anmol

will nd various chapters in thisbook as a useful starting point. Ourgoal is to provide readers withenough information so that theycan quickly get up and running onAndroid, with all of the basics ofthe Android platform and relatedsecurity issues under their belts. Ifyou are an Android hacker, or ifyou are very well versed in securityconcerns of the platform, this bookis not for you.

Support

Errata and support for this bookare available on the CRC Presswebsite and on our site:

Page 36: Android Security - Misra, Anmol

www.androidinsecurity.com. Oursite will also have downloads forapplications and tools created bythe user. Sample applicationscreated by the authors areavailable on our website under theResource section. Readers shoulddownload apk les from ourwebsite and use them inconjunction with the text, whereverneeded.Username: androidPassword: ISBN-10 number of thebook—1439896461

Structure

Page 37: Android Security - Misra, Anmol

Our book is divided into 10chapters. Chapter 1 provides anintroduction to the mobilelandscape. Chapters 2 and 3introduce the reader to the AndroidOS and application architecture,respectively. Chapter 4 delves intoAndroid security features. Chapters5 through 9 cover various aspectsof security for the Android platformand applications. The last chapterlooks at the future landscape ofthreats. Appendixes A and B (foundtowards the end of the book) talkabout the severity ratings ofAndroid permissions and the JEBDecompiler, respectively. Appendix

Page 38: Android Security - Misra, Anmol

C shows how to crackSecureApp.apk from Chapter 7 andis available online on the book’swebsite(www.androidinsecurity.com).

Page 39: Android Security - Misra, Anmol

About the Authors

Anmol Misra

Anmol is a contributing author ofthe book Defending the Cloud:Waging War in Cyberspace (In nityPublishing, December 2011). Hisexpertise includes mobile andapplication security, vulnerabilitymanagement, application andinfrastructure security assessments,and security code reviews.

He is currently ProgramManager of the Critical Business

Page 40: Android Security - Misra, Anmol

Security External (CBSE) team atCisco. The CBSE team is part of theInformation Security Team(InfoSec) at Cisco and isresponsible for the security ofCisco’s Cloud Hosted Services. Priorto joining Cisco, Anmol was aSenior Consultant with Ernst &Young LLP. In his role, he advisedFortune 500 clients on defining andimproving Information Securityprograms and practices. He helpedlarge corporations to reduce ITsecurity risk and achieve regulatorycompliance by improving theirsecurity posture.

Anmol holds a master’s degree in

Page 41: Android Security - Misra, Anmol

Information Networking fromCarnegie Mellon University. Healso holds a Bachelor ofEngineering degree in ComputerEngineering. He served as VicePresident of Alumni Relations forthe Bay Area chapter of theCarnegie Mellon AlumniAssociation.

In his free time, Anmol enjoyslong walks on the beaches of SanFrancisco. He is a voracious readerof non ction books—especially,history and economics—and is anaspiring photographer.

Abhishek Dubey

Page 42: Android Security - Misra, Anmol

Abhishek has a wide variety ofexperience in information security,including reverse engineering,malware analysis, andvulnerability detection. He iscurrently working as a Lead/SeniorEngineer of the Security Servicesand Cloud Operations team atCisco. Prior to joining Cisco,Abhishek was Senior Researcher inthe Advanced Threat ResearchGroup at Webroot Software.

Abhishek holds a master’s degreein Information Security andTechnology Management fromCarnegie Mellon University andalso holds a B.Tech degree in

Page 43: Android Security - Misra, Anmol

Computer Science and Engineering.He is currently pursuing studies inStrategic Decisions and RiskManagement at StanfordUniversity. He has served as VicePresident of Operations andAlliances for the Bay Area chapterof the Carnegie Mellon AlumniAssociation. This alumni chapter is5,000 students strong.

In his free time, Abhishek is anavid distance runner andphotographer. He also enjoys rockclimbing and being a foodie.

Page 44: Android Security - Misra, Anmol

Acknowledgments

Writing a book is never a soloproject and is not possible withouthelp from many people. First, wewould like to thank our Editor,John Wyzalek at CRC Press, for hispatience and constant commitmentto the project. We would also liketo thank the production team atDerry eld Publishing—TheronShreve and Marje Pollack. Theronhas guided us from start to nishduring the production of this book.Marje has been patient through our

Page 45: Android Security - Misra, Anmol

many revisions and has helped usto convert our “write-ups” into theexciting book you have in yourhands.

We would like to thank DenaTsamtis (Director, InformationNetworking Institute, Director ofEducation, Training, and Outreach,CyLab, Carnegie MellonUniversity), James Ransome(Senior Director, Product Security,McAfee Inc), and Gary Bahadur(CEO at Razient) for their help andguidance over the years. We wouldalso like to thank Nicolas Falliere(Founder, JEB Decompiler) forgiving us early access to the JEB

Page 46: Android Security - Misra, Anmol

Decompiler. Many others havehelped us along the way, as well,but it is not possible to list all oftheir names here.

- Anmol & Abhishek

I would like to take thisopportunity to express myprofound gratitude to my mentorsDavid Veach (Senior Manager atCisco) and Mukund Gadgil (VicePresident of Engineering-Upheels.com) for their continuedand exemplary guidance. I havelearned so much from both of youover the years. I couldn’t be morethankful to my friends Anuj,

Page 47: Android Security - Misra, Anmol

Varang, Erica, and Smita who haveconstantly pushed me over theyears to achieve my goals and whohave been there with me throughthick and thin. You all are“Legendary Awesome”! Lastly, Iwould like thank Maa, Papa, andmy sister, Anubha, for yourunquestioned support in everythingI have done. All my achievementsin life are because of you.

- Abhishek

I would like to thank Bill Vourthis(Senior Manager at Ernst &Young), David Ho (Manager atCisco), and Vinod (Jay)

Page 48: Android Security - Misra, Anmol

Jayaprakash (Senior Manager atErnst & Young) for their guidanceand encouragement over the years.I would also like to give myheartfelt thanks to my mentorNitesh Dhanjani (ExecutiveDirector at Ernst & Young) for hisguidance and encouragement. Iwould like to thank my family—Mom, Dad, and my brothers,Sekhar and Anupam—forsupporting me in all my endeavorsand for just being there. Mom, Dad– You are the backbone of ourfamily and all I have achieved isbecause of you. It has not beeneasy to put up with my intense

Page 49: Android Security - Misra, Anmol

schedule. Now that I have nishedthis book, I promise I will be timelyin replying to calls and e-mails.

- Anmol

Page 50: Android Security - Misra, Anmol

Chapter 1Introduction

In this chapter, we introduce thereader to the mobile deviceslandscape and demonstrate whyAndroid security matters. Weanalyze the evolution of mobilesecurity threats, from basic phonesto smartphones (including onesrunning the Android platform). Wemove on to introduce Androidhistory, releases, and marketplacesfor Android applications.

1.1 Why Android

Page 51: Android Security - Misra, Anmol

The number of mobile and Internetusers on mobile devices has beenskyrocketing. If statistics are anyindication, the adoption of mobiledevices in emerging and advancedeconomies has just started and isslated for huge growth in the nextdecade (see Figure 1.1).

According to data availablethrough Wikipedia (see Figures 1.2a n d 1.3), the Android platformruns on 64% of smartphones andon about 23.5% of all phones(http://en.wikipedia.org/wiki/Mobile_operating_systemApproximately 37% of all phonestoday are smartphones, leaving awhopping 60%+ of phones open

Page 52: Android Security - Misra, Anmol

to future adoption. Given thatAndroid’s share of the smartphonemarket has been rising steadily, theAndroid platform is slated forsimilar growth in the near future.Emerging markets and advancedeconomies alike are slated forincreased smartphone adoption,with Android at the heart of it.Even during the recent economicdownturn, the number ofsmartphone users continued toincrease steadily. Mobile deviceswill form the majority of Internet-accessing devices (dwar ng serversand personal computers [PCs]) inthe near future.

Page 53: Android Security - Misra, Anmol
Page 54: Android Security - Misra, Anmol

Figure 1.1 Basic vs. Smartphone Ownership inthe United States

Page 55: Android Security - Misra, Anmol

Figure 1.2 Global Smartphone Adoption(Source:http://en.wikipedia.org/wiki/Mobile_operating_system

Until recently, smartphones werenot “must-have” items and wereconsidered only for tech-savvy orgadget geeks. The rst Windowshandheld devices (Windows CE)were introduced in 1996. The rsttrue mobile smartphone arrived inthe year 2000, when the EricssonR380 was released, and it featuredNokia’s Symbian operating system.For awhile, there were cell phonesand PDAs—separate devices(anyone remember iPaq?).

Page 56: Android Security - Misra, Anmol

In 2002, both Microsoft and RIMreleased smartphones (Windows CEand Blackberry), respectively.While corporate adoption pickedup after the release of theBlackberry, the end-user marketreally started picking up after theintroduction of Apple’s iPhone, in2007. By then, RIM had a majorityshare of the corporate market.Around the same time, Googledecided to jump into the mobiledevice market. If mobile deviceswere going to represent most useractivity in the future, it meant thatusers would be using them forsearching the Internet—a core

Page 57: Android Security - Misra, Anmol

Google service. Advertising dollarswould also be increasingly focusedon mobile devices, as mobiledevices allow for much moretargeted ads. Searching “pizza” ona desktop/laptop can provideinformation about a user’s locationthrough the IP address, amongother information. However, with acell phone, the user’s GPS locationcan be used to display “relevantads” of places nearby.

The Open Handset Alliance(OHA) made its debut in 2007, andin 2008, Android was released.

The computational power ofmobile devices has grown

Page 58: Android Security - Misra, Anmol

exponentially (see Figure 1.4). TheHTC EVO 4G phone has theQualcomm 8650 1 Ghz processor, 1GB ROM (used for systemsoftware), and 512 MB of RAM. Inaddition, it has 802.11b/g,Bluetooth capability, an 8.0 MPcamera, GPS, and HDMI output.The phone speci cations arepowerful enough to beat a desktopcon guration for a typical user afew years ago. Again, this trend islikely to continue.

Page 59: Android Security - Misra, Anmol

Figure 1.3 Global Smartphone Sales Q1 (Source:http://en.wikipedia.org/wiki/Mobile_operating_system

Page 60: Android Security - Misra, Anmol

Figure 1.4 Comparison of Apple iPhone, DroidX,and an Old PC

Android’s share of mobile deviceshas been increasing at a steadyrate (see Figure 1.5). Androiddevices surpassed iPhone sales by2011. By mid-2011, there were

Page 61: Android Security - Misra, Anmol

about half a million Android deviceactivations per day (see Figure1.6) . Figure 1.7 shows the numberof carriers as well as manufacturersthat have turned to Android.

After the launch of the iPad,many manufacturers turned toAndroid as the platform for theiro erings. The Samsung Galaxy Tabis a perfect example of this. Othermanufacturers (e.g., Dell, Toshiba)have also started o ering tabletswith Android as their platform (seeFigure 1.8). A trend is likely tocontinue wherein the tablet marketuses two major platforms—IOS andAndroid.

Page 62: Android Security - Misra, Anmol

1.2 Evolution of Mobile Threats

As mobile devices have evolvedfrom basic to smartphones, threatsto mobile devices have evolved inparallel. Smartphones have alarger attack surface compared tobasic phones in the past. Inaddition, the usage patterns ofmobile devices have also evolved.Basic phones were primarily usedfor text messaging and phone calls.Today smartphones are used foreverything one can imagine usinga computer for—performingroutine banking transactions,logging onto Facebook, directions,maintaining health and exercise

Page 63: Android Security - Misra, Anmol

records, and so forth.

Page 64: Android Security - Misra, Anmol
Page 65: Android Security - Misra, Anmol

Figure 1.5 Mobile OS Market Share

Page 66: Android Security - Misra, Anmol
Page 67: Android Security - Misra, Anmol

Figure 1.6 Number of Android Activations perDay (Jan. 11–Dec. 11)

Figure 1.7 Android Phones for Major Carriers

For a long time, Nokia’s SymbianOS was the primary target ofattackers due to its penetration inthe mobile market. As the market

Page 68: Android Security - Misra, Anmol

share of Symbian continues todecline and there is acorresponding increase in the shareof Android devices and iPhones,attackers are targeting theseplatforms today.

Symbian is still the leadingplatform for phones outside theUnited States and will be a targetof attackers in the foreseeablefuture. However, Android andiPhone attacks are increasing innumber and sophistication. Thisre ects the fact that bad guys willalways go after the most popularplatform. As Android continues togain in popularity, threats against

Page 69: Android Security - Misra, Anmol

it will continue to rise.

Figure 1.8 Android Devices from MajorManufacturers

Looking at the threat landscape

Page 70: Android Security - Misra, Anmol

for Android devices, it is clear thatattacks against Android users andapplications have increased quite abit over the last couple of years. AsAndroid adoption picks up, so doesthe focus of attackers to target theplatform and its users. Androidmalware has seen an upwardtrend, as well.

This trend does not only apply toAndroid devices. Mobile phoneshave increased in theirfunctionality as well as attacksurfaces. The type of data we haveon a typical smartphone and thethings we do with our phone todayare vastly di erent from just a few

Page 71: Android Security - Misra, Anmol

years ago.Attacks on basic phones targeted

Short Message Service (SMS),phone numbers, and limited dataavailable to those devices. Anexample of such an attack is thetargeting of premium SMS services.Attackers send text messages topremium rate numbers or makecalls to these numbers. An attackon an Android or smartphone isdi erent and more sophisticated—for example, a maliciousapplication accessing a user’ssensitive information (personaldata, banking information, chatlogs) and sending it to potential

Page 72: Android Security - Misra, Anmol

attackers. Smartphones aresusceptible to a plethora ofapplication-based attacks targetingsensitive information.

The following is a sample dataset on a typical smartphone:

1. Corporate and personal e-mails

2. Contacts (along with their e-mail and personal addresses)

3. Banking information4. Instant Messaging logs5. Pictures6. Videos

Page 73: Android Security - Misra, Anmol

7. Credit card Information8. Location and GPS data9. Health information10. Calendar and schedule

information

Attacks on a smartphone runningon the Android platform couldresult in leakage of the above dataset. Some possible attacks that aremore devastating include socialengineering, phishing, spoo ng,spyware, and malware—forexample, a mobile applicationsubscribing a user to a premiumservice. The user would then incur

Page 74: Android Security - Misra, Anmol

data and usage charges, in additionto subscription fees. Smartphonebrowsers are miniature comparedto their desktop counterparts.Therefore, encryption functionalityon a smartphone OS as well asbrowser can be limited and cantake more time to respondcompared to on a PC—forexample, revoking certi cates frommobile browsers.

Until now, we have focused onattacks on applications andprotocols used for communicationon the Web. Another class ofattacks is on the cellulartechnology itself. GSM and CDMA

Page 75: Android Security - Misra, Anmol

are the most widely usedcommunication standards. Carriersuse one or the other standard forproviding cellular service (i.e.,calls, SMS). As the adoption ofcellular devices increase, thesestandards have come underincreasing scrutiny fromresearchers and attacks frommalicious users.

GSM is used on a majority ofcellular phones in the world (200+countries, 4 billion+ users). GSMuses A5/1 encryption to provideover-the-air communicationprivacy (i.e., to encrypt SMS andtelephone conversations). Although

Page 76: Android Security - Misra, Anmol

it was initially kept a secret, it wasreversed engineered, and somedetails became public knowledgethrough leaks. In the early 1990s,A5/1 was shown to be broken inresearch papers/academia. By2009, researcher Karsten Nohldemonstrated an attack that couldallow someone to determine theencryption key used for protectingSMS and telephone conversations.Even more interesting was the factthat this could be accomplishedwith relatively inexpensiveequipment. A5/1 uses a 64-bit keyand can be attacked usinghardware available today. Given

Page 77: Android Security - Misra, Anmol

two encrypted, known plaintextmessages, the secret key can befound in a precomputed table.Given the increasing use of cellulardevices for Radio FrequencyIdenti cation (RFID)/Near FieldCommunication (NFC), this canresult in the compromise of notonly SMS and voicecommunications but also of data(e.g., credit card payments).

Many users are not aware of therisks and threats to their mobiledevices, which are similar to thoseon a PC. Although the majority ofusers use some kind of protectionon their desktops or laptops (e.g.,

Page 78: Android Security - Misra, Anmol

antivirus software), they areoblivious to the need to protecttheir mobile devices. The majorityof users are not technically savvyenough to understand theimplications of performing certainactions on their cellular devices.Jail-breaking or rooting is anexample. Users are also placingtheir trust in applications theyinstall from an applicationrepository, whether it be the AppStore (iPhone) or the AndroidMarket. Malware applicationswere found on the Android Marketdisguised as popular applications.For a typical user, a $0.99

Page 79: Android Security - Misra, Anmol

application download is becomingroutine practice, and if a userregularly downloads and installsan application, the security orbehavior of an application mightgo unnoticed.

Increasingly, workers arebringing their own devices to workand shunning their company-sponsored devices. The use ofAndroid devices and iPhonescontinues to rise in the businessenvironment. However, corporatepolicies have not kept up withusers as they still focus on securing“full- edged” PC devices more thanmobile devices. This exposes their

Page 80: Android Security - Misra, Anmol

environment to attacks thatleverage mobile devices and users.In fact, it might be easier tocompromise mobile devices inmany cases than their desktopcounterparts, where corporatedollars are still being spent.Threats yet to materialize but notconsidered as such byresearchers/business enterprisesare those coming from state-sponsored entities, such asgovernment intelligence agencies.One can imagine attacks possiblein cyber-warfare, such as thespreading of mobile malware,which could clog the

Page 81: Android Security - Misra, Anmol

communication medium.

1.3 Android Overview

Android is more than just anoperating system. It is a completesoftware stack. Android is based onthe Linux kernel and builds on asolid foundation provided by Linux.It is developed by the OHA, whichis led by Google. In this section, webrie y cover the history ofAndroid, releases, and features ona typical Android device.

Android did not start at Google.Google acquired Android Inc. in2005. As mentioned earlier, Googlewas instrumental in creating the

Page 82: Android Security - Misra, Anmol

OHA, in 2007. Initially, a total ofeighty-six companies came togetherto form the OHA. Android code wasopen sourced by Google under theApache license. The Android OpenSource Project (AOSP) was taskedwith maintaining and furtherdevelopment of Android. Majortelecommunication companies,such as HTC, LG, Motorola, andQualcomm, are members of theOHA. This group is committed tothe development of open standardsfor mobile devices. The AOSP, ledby Google, develops and maintainsthe Android platform.

Android is open source and

Page 83: Android Security - Misra, Anmol

business friendly. Its source code isavailable under the Apache Licenseversion 2.0. Linux Kernel changesare available under GNU v2.0. Allapplications on Android arecreated equal. For example,although there is a built-in browser,a user can download anotherbrowser (e.g., Firefox, Opera), andit will be treated the same as abuilt-in browser. The user canchoose to replace built-inapplications with applications oftheir choice. Licensingconsiderations were one of thereasons Android developed theDalvik virtual machine instead of

Page 84: Android Security - Misra, Anmol

using the Java virtual machine.Many versions of Android have

been released since its originalrelease, each adding new featuresand capabilities and xing bugs inthe previous releases. Each is nameafter a dessert (in alphabeticalorder).

Figure 1.9 presents a summary ofAndroid releases and the mainfeatures corresponding to eachrelease, and Figure 1.10 shows thedistribution of Android releases ondevices currently in use.

The Android software stackprovides many features for users

Page 85: Android Security - Misra, Anmol

and developers, as well as formanufacturers. A summary ofmajor Android features is outlinedin Figure 1.11.

Page 86: Android Security - Misra, Anmol
Page 87: Android Security - Misra, Anmol

Figure 1.9 Android Releases

Figure 1.10 Distribution of Android Versions onDevices

1.4 Android Marketplaces

Android applications can bedownloaded and installed frommultiple Android Markets.Although the Android Market fromGoogle is the largest repository,

Page 88: Android Security - Misra, Anmol

there are other places where userscan download applications (e.g.,Amazon). This is very di erentfrom the iPhone App Store. There isno rigorous veri cation of anapplication (or security review ofan application) when it is uploadedto the market. One can easilydevelop a malicious application(e.g., a free version of a popularsoftware) and upload it to theGoogle Android Market. Mostlikely, it will be discovered andremoved. However, since there aremultiple marketplaces, one willstill be able to target Android usersfrom secondary sources (see Figure

Page 89: Android Security - Misra, Anmol

1.12). Android leaves it up to theuser to accept the risk if theychoose to install software fromuntrusted sources. This is less thanideal and should be compared tothe Apple App Store, where everyapplication goes through a securityreview before it is approved forpublic distribution. Problemsregarding the Android Marketmodel are summarized below:

Page 90: Android Security - Misra, Anmol

Figure 1.11 Major Android Features

1. There is no rigorous scrutinyof an application, even on theprimary Android Market.

2. The user has the responsibilityfor verifying (and accepting)the risk of an application

Page 91: Android Security - Misra, Anmol

available from secondarymarkets.

3. Android applications withexplicit content (e.g., adultcontent) can be downloadedand installed withoutveri cation (e.g., by a minorwith a cell phone device).

Table 1.1 shows a selected list ofAndroid application markets.

Page 92: Android Security - Misra, Anmol

Figure 1.12 Installing Applications fromUnknown Sources

Table 1.1 – Android Application

Page 93: Android Security - Misra, Anmol

Markets

Market Name

Google AndroidMarket

https://play.google.com/store*

AmazonAppstore

http://www.amazon.com/b?node=2350149011*

SlideMe http://slideme.org/*

GetJar http://www.getjar.com/*

Soc.io http://soc.io/*

1 Mobile http://www.1mobile.com/*

Appbrain http://www.appbrain.com/*

Page 94: Android Security - Misra, Anmol

AppsLib http://appslib.com/*Handango http://www.handango.com*

Motorolahttp://www.motorola.com/Consumers/US-EN/Consumer-Product-and-Services/APPS/App-Picks*

GoApk http://bbs.anzhi.com/*

Androidblip http://www.androidblip.com/*

AndroidPit http://www.androidpit.com/*

Appoke http://appoke.com/*

AppstoreHQ http://www.appstorehq.com/*

BlapkMarket http://blapkmarket.com/en/login/*

Page 95: Android Security - Misra, Anmol

Camangi http://www.camangimarket.com/index.html*Indiroid https://indiroid.com/*

Insyde Market http://www.insydemarket.com/*

Appstoreconnect http://appstoreconnect.com/publish/*

Mobihand http://www.mobihand.com/*

Applanet http://applanet.net/*

Handster http://www.handster.com/*

Phoload http://www.phoload.com/*

1.5 Summary

In this chapter, we reviewed themobile devices landscape and theexplosion in the adoption of mobile

Page 96: Android Security - Misra, Anmol

devices. Android has emerged asthe leading platform of choice forsmart phones and tablets (analternative to the iPad). Wereviewed statistics on Androidadoption and market share. Wethen covered the evolution ofthreats against mobile devices—both against the applications aswell as against the cellulartechnology itself. We concluded thechapter with an overview ofAndroid marketplaces and theirpossible impact on Androidsecurity. Taken together, we canconclude that Android security isbecoming an important issue to

Page 97: Android Security - Misra, Anmol

users, corporations, developers,and security professionals. Startingwith Chapter 2, we will cover theunderpinnings of the Androidplatform and then move on todiscuss Android security issues.

Page 98: Android Security - Misra, Anmol

Chapter 2Android Architecture

In this chapter, we introduce thereader to Android architecture. Wecover various layers in the Androidsoftware stack, from the Linuxkernel to applications, as well asthe extent to which they havesecurity implications. We thenwalk the reader through theAndroid start-up process and setupof the Android environment, andwe present the various toolsavailable to us through the AndroidSoftware Development Kit (SDK).

Page 99: Android Security - Misra, Anmol

We also provide hands-oninstruction for downloading andinstalling the Android SDK andinteracting with shell commands.

2.1 Android ArchitectureOverview

Android can be thought of as asoftware stack comprising di erentlayers, each layer manifesting well-de ned behavior and providingspeci c services to the layer aboveit. Android uses the Linux kernel,which is at the bottom of the stack.Above the Linux kernel are nativelibraries and Android runtime (theDalvik Virtual Machine [VM] and

Page 100: Android Security - Misra, Anmol

Core Libraries). Built on top of thisis the Application framework,which enables Android to interactwith the native libraries andkernel. The topmost layercomprises the Androidapplications. The following is adetailed discussion of each of thesela ye r s . Figure 2.1 depicts theconceptual layers in the AndroidStack, and Figure 2.2 describes thevarious components found withineach of these layers.

Page 101: Android Security - Misra, Anmol

Figure 2.1 Conceptual Layers in the AndroidStack

2.1.1 Linux Kernel

The Linux kernel is found at thebottom of the Android stack. It isnot the traditional Linux systemthat is usually seen (e.g., Ubuntu).Rather, Android has taken theLinux kernel code and modi ed itto run in an embeddedenvironment. Thus, it does not

Page 102: Android Security - Misra, Anmol

have all the features of atraditional Linux distribution.Speci cally, there is no Xwindowing system in the AndroidLinux kernel. Nor are there all theGNU utilities generally found in/bin in a traditional Linuxenvironment (e.g., sed, etc.). Inaddition, many of thecon guration les are missing, thatis, the /etc/shadow le for storingpassword hashes. Table 2.1 showsthe Android version and thecorresponding Linux kernel versionthat it is based on. The Androidteam forked the Linux kernel to usewithin an embedded environment.

Page 103: Android Security - Misra, Anmol

The Android team maintains thisfork. Changes in the Linux kernelare incorporated in the fork for usein future Android releases. This isimportant because many securitychanges and enhancements aremade to the Linux kernel on anongoing basis, and by activelyaccommodating these in theAndroid fork of the Linux kernel,the users get the best of what Linuxhas to offer.

The Android Kernel fork hasmade many enhancements to theoriginal Linux kernel, and recentlya decision was made by the LinuxCommunity to include these

Page 104: Android Security - Misra, Anmol

enhancements in the next Linuxkernel release (3.3).

Linux provides Android with asolid foundation to build upon.Among the features that Androidrelies on are the hardwareabstraction and drivers, security,and process and memorymanagement. By relying on Linuxfor hardware abstraction, Androidcan be ported to variety of devices.The Linux kernel also has a robustdevice driver model formanufacturers to use. Of utmostimportance (except for security),the Linux kernel provides ahardware abstraction layer in the

Page 105: Android Security - Misra, Anmol

Android stack. Linux has a well-understood and tested drivermodel. Hardware drivers for manycommon devices are built into thekernel and are freely available.There is an active developmentcommunity that writes drivers forthe Linux kernel. This is animportant consideration on twofronts: It enables Android tosupport a vast array of devices,especially from a tablet viewpoint,and it makes it easy formanufacturers and developers towrite drivers in a well-understoodway. Android relies on Linux forbasic OS functionality, that is, I/O,

Page 106: Android Security - Misra, Anmol

memory, and process management.Figure 2.3 shows the Linux kernelversion (cat/proc/version) forAndroid 2.3.3.

Page 107: Android Security - Misra, Anmol
Page 108: Android Security - Misra, Anmol

Figure 2.2 Different Components within Layersof the Android Stack (Source:http://en.wikipedia.org/wiki/Android_[operating_system]

Table 2.1 – Linux KernelVersions for Android Releases

Android VersionLinux Kernel

Version

Android Cupcake1.5

Linux Kernel2.6.27

Android Donut 1.6Linux Kernel2.6.29

Android Éclair Linux Kernel

Page 109: Android Security - Misra, Anmol

2.0/2.1 2.6.29

Android Froyo 2.2Linux Kernel2.6.32

AndroidGingerbread 2.3.×

Linux Kernel2.6.35

AndroidHoneycomb 3.×

Linux Kernel2.6.36

Android IcecreamSandwich 4.×

Linux Kernel3.0.1

From a security standpoint,Linux provides a simple but secureuser- and permissions-based model

Page 110: Android Security - Misra, Anmol

for Android to build on. Inaddition, the Linux kernel providesAndroid with process isolation anda secure IPC. Android has alsotrimmed down the Linux kernel,thus reducing the attack surface. Atthe core, the Linux kernel allowsan Android application to run as aseparate user (and process). TheLinux user-based permissions modelprevents one application fromreading another application’sinformation or from interferingwith its execution (e.g., memory,CPU, devices). Android has alsomade certain enhancements to theLinux kernel for security purposes

Page 111: Android Security - Misra, Anmol

—for example, restricting access tonetworking and Bluetooth features,depending on the group ID of thecalling process. This isaccomplished through theANDROID_PARANOID_NETWORKkernel build option. Only certaingroup IDs, for example, havespecial access to networking orBluetooth features). These arede ned in/include/linux/android_aids.h (in-kernel source tree). In CodeSnippet 1, the kernel groupAID_INET is de ned with group ID3003. A calling process will need tobe a member of this group to

Page 112: Android Security - Misra, Anmol

create/open IPv4 and IPv6 sockets.

Figure 2.3 Linux Kernel Version

Page 113: Android Security - Misra, Anmol

Code Snippet 1 –include/linux/android_aid.h

Once these kernel groups arede ned ininclude/linux/android_aid.h, theyare then mapped to the logical

Page 114: Android Security - Misra, Anmol

group “inet” in the/system/core/include/private/android_filesystem_config.h

le. Code Snippet 2, below, is fromthe android_ lesystem_con g.h le.Note that the logical name “inet” ismapped to “AID_INET”. AID_INETand has group ID 3003.

Page 115: Android Security - Misra, Anmol
Page 116: Android Security - Misra, Anmol

Code Snippet 2 –android_filesystem_config.h

When an Android applicationrequests permission to access theInternet, it is essentially seekingpermission to open the IPv4 andIPv6 sockets. Applicationpermissions are then mapped tothe “inet” group name through the/system/etc/permissions/platform.xml

le. The following snippet of xmlmaps the application’s permissionto AID_INET:

Page 117: Android Security - Misra, Anmol

Figure 2.4 shows an applicationthat has permissions to access the

Internet.

In addition to mapping theKernel group IDs to logical names,there are other importantcomponents of theandroid_ lesystem_con g.h le,from a security standpoint. This filealso de nes ownership rules forvarious directories and les in theAndroid le system. For example,/data/app directory is owned bythe AID_SYSTEM user and group(see Figure 2.5). This mapping isde ned here through the following

Page 118: Android Security - Misra, Anmol

line: { 00771, AID _ SYSTEM, AID_ SYSTEM, “data/app” }. The rststring de nes permission (771), thesecond and third strings are userand group IDs of the owner, andthe last string is the directory itself.

Page 119: Android Security - Misra, Anmol

Figure 2.4 Application Accessing InternetPermission Belongs to Group ID 3003(AID_INET)

Figure 2.5 User System Owns /data directory asDefined in android_filesystem_config.h

Page 120: Android Security - Misra, Anmol

Code Snippet 3 – Directory and

Page 121: Android Security - Misra, Anmol

File Permissions

The Android kernel also makescertain enhancements to the Linuxkernel, including Binder IPCmechanisms, Power Management,Alarm, Low Memory Killer, andLogger. The logger provides asystemwide logging facility thatcan be read using the logcatcommand. We cover logcat indetail in our Android Tools sectionlater in this chapter.

2.1.2 Libraries

Android includes a set of C andC++ libraries used by di erent

Page 122: Android Security - Misra, Anmol

components of the Android system( s e e Table 2.2). Developers usethese libraries through the Androidapplication framework. At times,this layer is referred to as the“native layer” as the code here iswritten in C and C++ andoptimized for the hardware, asopposed to the Androidapplications and framework, whereit is written in Java. Androidapplications can access nativecapabilities through Java NativeInterface (JNI) calls. Most of thelibraries are used without muchmodi cation (SSL, SQLite, etc.).One exception is the bionic or

Page 123: Android Security - Misra, Anmol

System C library. This library is nota typical libc but a trimmed downversion of it based on the BSDlicense and optimized for anembedded platform.

Table 2.2 – Android Native LayerLibraries

Library Description

MediaLibraries

Enables playback andrecording of audio andvideo formats. Based onOpenCore fromPacketVideo

Page 124: Android Security - Misra, Anmol

SQLite

Provides relationaldatabases that can beused by applications andsystems

SSLProvides support fortypical cryptographicfunctions

Bionic System C library

WebKitBrowser-renderingengine used by Androidbrowsers

Surface Provides support for the

Page 125: Android Security - Misra, Anmol

Manager display system

SGLGraphics engine used byAndroid for 2D

Figure 2.6 Compilation Process for Java VirtualMachine (JVM) and Dalvik Virtual Machine(DVM)

2.1.3 Android Runtime

Android Runtime can be thought of

Page 126: Android Security - Misra, Anmol

as comprising two di erentcomponents: the Dalvik VM andCore Libraries.

Android applications are writtenin Java. These applications arethen compiled into Java class les.However, Android does not runthese class les as they are. Javaclass les are recompiled into dexformat, which adds one more stepto the process before theapplications can be executed on theAndroid platform. The Dex formatis then executed in a custom JavaVirtual Machine (JVM)-likeimplementation—the Dalvik VM.Figure 2.6 shows the distinction

Page 127: Android Security - Misra, Anmol

between the compilation steps fora typical JVM versus the DalvikVM. The Dalvik VM relies on theLinux kernel for providing lowerlevel functionality (e.g., memorymanagement).

Android includes a set of CoreLibraries that provides most of thefunctionality available in Javaapplication programminginterfaces (APIs). However,available APIs_are a trimmed-downversion of what one would expectto see in a J2SE. For example,although there is no support forSwing or AWT, Core Libraries

Page 128: Android Security - Misra, Anmol

include Android-speci c libraries(e.g., SQLlite, OpenGL). Whereasusing J2SE would result inoverhead in an embeddedenvironment, using J2ME wouldhave licensing and securityimplications. Using J2ME wouldrequire paying licensing fees toOracle for each device. For securityreasons, each Android applicationruns in its own VM. For J2MEimplementation, all applicationswould be running inside on a VM,thus creating a weaker securitysandbox.

2.1.4 Application Framework

Page 129: Android Security - Misra, Anmol

The Android applicationframework provides a rich set ofclasses provided (for developers)through Java APIs for applications.This is done through variousApplication Manager services. Themost important components withinthis layer are Activity Manager,Resource Manager, LocationManager, and Noti cationManager. Table 2.3 summarizes themain services provided through thislayer.

Table 2.3 – Android ApplicationFramework Layer Services

Service Description

Page 130: Android Security - Misra, Anmol

ActivityManager

Manages the activitylifecycle ofapplications andvarious applicationcomponents. Whenan applicationrequests to start anactivity, e.g., throughstartActivity(),Activity Managerprovides this service.

Provides access to

Page 131: Android Security - Misra, Anmol

ResourceManager

resources such asstrings, graphics, andlayout files.

LocationManager

Provides support forlocation updates(e.g., GPS)

Notification

Applicationsinterested in gettingnotified about certainevents are providedthis service throughnotification manager,e.g., if an application

Page 132: Android Security - Misra, Anmol

Manager is interested inknowing when a newe-mail has beenreceived, it will usethe NotificationManager service.

The PackageManager service,along with installd(packagemanagementdaemon), is

Page 133: Android Security - Misra, Anmol

PackageManager

responsible forinstallingapplications on thesystem andmaintaininginformation aboutinstalled applicationsand theircomponents.

ContentProviders

Enables applicationsto access data fromother applications orshare its own data

Page 134: Android Security - Misra, Anmol

with them

Views

Provides a rich set ofviews that anapplication can use todisplay information

2.1.5 Applications

By default, Android comes with richset of applications, including thebrowser, the SMS program, thecalendar, the e-mail client, maps,Contact Manager, an audio player,and so forth. These applicationsare written in the Javaprogramming language. Google

Page 135: Android Security - Misra, Anmol

Play (the marketplace for Android)provides alternatives to theseapplications, if the user so desires.Android does not di erentiatebetween applications written byusers or provided by the OS—forexample, the browser application.A user can download Firefox,Opera, or other browsers, andAndroid will treat them the same asthe built-in browser. Users canreplace default applications withtheir own chosen applications. Wecover Android applicationarchitecture in detail in Chapter 3.

2.2 Android Start Up and Zygote

Page 136: Android Security - Misra, Anmol

As we have discussed, Android isnot Linux but is based on the Linuxkernel, and there are somesimilarities but also signi cantdi erences between them. AllAndroid applications at the coreare low-level Linux processes. Eachapplication runs as a separateprocess (with some exceptions),and, by default, there is one threadper process. Like most Linux-basedsystems, boot loader at the startuptime loads the kernel (a modi edLinux kernel tailored for Android)and starts the init process. All otherprocesses are spawned from theinit process. The init process

Page 137: Android Security - Misra, Anmol

spawns daemons (e.g., adbdaemon, USB, and other hardwaredaemons). Once it has nishedlaunching these daemons, init thenlaunches a process called “zygote.”This zygote process, in turn,launches the rst DVM andpreloads all core classes used bythe applications. It then listens ona socket interface for futurerequests to spawn off new DVMs.

When a new application islaunched, the zygote receives arequest to launch a new DalvikVM. The zygote then forks itselfand launches a new process thatinherits the previously initialized

Page 138: Android Security - Misra, Anmol

VM. The launching of a separateVM does not result in a slowdown,as shared libraries are not copiedunless the application makes anychanges and modi es them. Afterthe zygote is started by init, it forksitself and starts a process calledsystem server. The system serverthen starts all core Androidservices, such as Activity Manager.Once all of the core services arelaunched, the platform is ready tolaunch applications as desired bythe user. Each application launchresults in the forking of the zygoteand the creation of a new DalvikVM.

Page 139: Android Security - Misra, Anmol

2.3 Android SDK and Tools

In this section, we set up anenvironment for developing andrunning Android applications.Although developers are theprimary target for many of thesetools, it is important for us (theusers) to be familiar with them andto use them when performing asecurity review of an Androidapplication. By the end of thissection, you should be able to setup an Android environment onyour system and develop, compile,run, and debug an application.

The major components of the

Page 140: Android Security - Misra, Anmol

Android environment are asfollows:

1. Android SDK2. Eclipse IDE and ADT3. Tools (including DDMS,

logcat)

2.3.1 Downloading and Installingthe Android SDK

The Android SDK is what we needto develop and run applications.The SDK includes the Androidlibraries, tools, and sampleapplications to get us started. TheSDK is available for free from the

Page 141: Android Security - Misra, Anmol

Android website. To use the SDK,you will need to install the JavaSDK. Below are steps for setting upthe Android SDK on your system:

1. Download the SDKappropriate for your platform(Windows, Mac, Linux). If youare using the 64-bit version ofWindows, you might need totweak a few things, but set upis pretty straightforward. Onthe Mac and Linux, just unzipthe le to the desired locationand you will have access tothe Android tools. Figure 2.7shows utilities in the tools

Page 142: Android Security - Misra, Anmol

directory after unzipping thedownloaded SDK package.

2. Update your PATH variable sothat you can access tools fromthe command line evenoutside the SDK directory.PATH should be set to <pathto SDK>/tools and <path toSDK>platform-tools.

Page 143: Android Security - Misra, Anmol

Figure 2.7 Utilities Available under /tools

Page 144: Android Security - Misra, Anmol
Page 145: Android Security - Misra, Anmol

Figure 2.8 Android SDK Manager

3. Start the SDK manager bytyping “android.” Select theAndroid version of interest toyou and download thecorresponding packages.Figure 2.8 shows the AndroidSDK Manager.

To get started with Android,create an Android Virtual Device(AVD) through the SDK Manager(Figure 2.9). Once you create anAVD, you can launch it from theAVD Manager (accessible from theSDK Manager) or from thecommand line through the

Page 146: Android Security - Misra, Anmol

“emulator” command. The Androidemulator is a full implementationof the Android stack provided to usthrough the SDK to test and debugapplications. This comes in handywhen we do not have access to theactual device.

2.3.2 Developing with Eclipse andADT

Eclipse is an open-sourceIntegrated DevelopmentEnvironment (IDE) with manytools to aid in applicationdevelopment. It is quite popularamong Java developers. Eclipseplugins are also available for other

Page 147: Android Security - Misra, Anmol

languages (C, C++, PHP, and soforth). For Android, we recommendEclipse Classic IDE. You candownload Eclipse fromhttp://www.eclipse.org/downloads/

To use Eclipse to develop/reviewAndroid applications, you will needto download the AndroidDevelopment Tools (ADT) plugin.Steps to set up ADT on Eclipse areas follows:

1. Open Eclipse and then select“Help-> Install NewSoftware.”

2. Add the following URL:https://dl-

Page 148: Android Security - Misra, Anmol

ssl.google.com/android/eclipse/(see Figure 2.10).

3. Select “Developer Tools” andclick next. Accept terms andclick “Finish.”

4. Select “Eclipse” ->Preferences -> Android, pointto the SDK folder, and clickOK.

2.3.3 Android Tools

The Android SDK provides us withuseful tools for the development,testing, and analysis ofapplications. Table 2.4 presents themain tools and their descriptions. A

Page 149: Android Security - Misra, Anmol

detailed discussion of all of thesetools is outside scope of this book.However, we will examine three ofthe tools—Dalvik DebugMonitoring Service (DDMS),Android Debug Bridge (ADB), andProGuard—in some detail here.Table 2.4 summarizes the toolsavailable through the SDK andtheir purpose. The Eclipse ADTplugin provides access to thesetools through Eclipse IDE.Especially of interest to us is DDMSperspective, which provides us withinformation on Dalvik VMsrunning our applications. For moreinformation regarding these tools,

Page 150: Android Security - Misra, Anmol

please refer to the following URL:http://developer.android.com/guide/developing/tools/index.html

Page 151: Android Security - Misra, Anmol
Page 152: Android Security - Misra, Anmol

Figure 2.9 Creating a New Android VirtualDevice (AVD)

Page 153: Android Security - Misra, Anmol

Figure 2.10 Developer Tools Available Through

Page 154: Android Security - Misra, Anmol

ADT for Eclipse

Table 2.4 – Android ToolsAvailable through SDK

Tool Usage

android

To run SDKmanager fromthe commandline. This lets theuser manageAVDs andinstalledcomponents of

Page 155: Android Security - Misra, Anmol

SDK.

emulator

Enables us to runthe mobile deviceemulator on acomputer. This isespecially usefulif you don’t haveaccess to amobile device.

Enablesdebugging ofapplications. It

Page 156: Android Security - Misra, Anmol

ddms

provides thefollowinginformation:port-forwardingservices, screencapture on thedevice, threadand heapinformation onthe device,logcat, process,and radio stateinformation,

Page 157: Android Security - Misra, Anmol

incoming calland SMSspoofing,location dataspoofing, and soforth.

hierarchyviewerAllows us todebug the userinterface.

Allows us toconvert theHPROF file

Page 158: Android Security - Misra, Anmol

hprof-conv output fromAndroid to astandard formatthat can beviewed withprofiling tools.

sqlite

Allows us toreview sqlite3databasescreated/used byAndroidapplications

Allows us to

Page 159: Android Security - Misra, Anmol

adb

communicate toemulatorinstances ormobile devicesthrough thecommand line. Itis a client-serverapplication thatenables us tointeract with therunning emulator(or deviceinstances). One

Page 160: Android Security - Misra, Anmol

can, for example,install an apkthrough the adbshell, viewrunningprocesses, and soforth.

proguard

Built-in codeobfuscation toolprovided byAndroid

A graphical

Page 161: Android Security - Misra, Anmol

traceview analysis tool forviewing logsfrom applications

dx

Converts .classbyte code to .dexbyte code used byDalvik

mksdcard

Used for creatingSD card diskimages used bythe emulator

2.3.4 DDMS

Page 162: Android Security - Misra, Anmol

The emulator (or cell phone screen)enables us to view an application’sbehavior at a UI level. However, tounderstand what is going on underthe surface, we need the DDMS.The DDMS is a powerful tool thatallows us to obtain detailedinformation on running processes,review stack and heap information,explore the le system of theemulator/connected device, andmore. The Eclipse ADT plugin alsoprovides us with access to logsgenerated by logcat.

Figure 2.11 shows the DDMS toollaunched by typing ddms into yourdevelopment system. It can also be

Page 163: Android Security - Misra, Anmol

launched from Eclipse ADT byaccessing DDMS perspective(Figure 2.12). As can be seen fromFigure 2.11, DDMS provides uswith quite a bit of informationabout processes running on thedevice or emulator. Toward the topleft corner, there is a list ofrunning processes. Clicking on anyof these processes provides us withadditional information that we canexamine. For example, it lists theprocess ID—the application name(com.Adam.CutePuppiesWallpaper),in our case. We can also examinestack and heap information,threads associated with the process,

Page 164: Android Security - Misra, Anmol

and so forth, by choosing varioustabs toward the upper right handcorner. The bottom half of theDDMS provides us with detailedevent information for the emulator.In our example, by launching thewallpaper application, you can seethat the MCS_BOT_Service islaunched. After this, theapplication throws “Unknown HostException” for “k2homeunix.com”and exits.

2.3.5 ADB

ADB is a client-server applicationthat provides us with a way tocommunicate with an

Page 165: Android Security - Misra, Anmol

emulator/device. It is composed ofthree components: ADB daemon(/sbin/adbd), which runs on thedevice/emulator; service, whichruns on the development system,and client applications (e.g., adbor ddms), which are used tocommunicate to the daemonthrough the service. ADB allows usto execute interactive commandson the emulator or the device, suchas installing apk les orpulling/pushing les and shellcommands (through the adb shell).The ADB shell on an emulatorprovides us with a root shell withaccess to almost everything.

Page 166: Android Security - Misra, Anmol

However, on a device, we will login as a shell user and thus will belimited in our ability to performsensitive operations.

Table 2.5 presents importantcommands that we can executethrough ADB. For a full list ofcommands, please refer to thedocumentation provided throughthe following URL:http://developer.android.com/guide/developing/tools/adb.html

2.3.6 ProGuard

ProGuard is a code-obfuscation toolthat is part of the Android SDK.Since Java classes can be easilydecompiled, it is a good idea to

Page 167: Android Security - Misra, Anmol

perform code-obfuscation as part ofthe development and building ofan application. The ProGuard toolshrinks, optimizes, and obfuscatescode by removing unused codes aswell as renaming classes, elds,and methods. This can increase thetime required to reverse engineeran application by someone else.The steps to enable ProGuard areoutlined below:

Page 168: Android Security - Misra, Anmol
Page 169: Android Security - Misra, Anmol

Figure 2.11 DDMS Tool Provided through theAndroid SDK

Page 170: Android Security - Misra, Anmol
Page 171: Android Security - Misra, Anmol

Figure 2.12 DDMS Perspective through EclipseADT

Table 2.5 – ADB Commands

Purpose ADB Command

adb [-d] [-e] [-s<SerialNumber>]command Thiscommand willinvoke the adbclient. If there aremultiple

Page 172: Android Security - Misra, Anmol

Issuing ADBCommands

targets/instancesofdevices/emulatorrunning, -d optionwill specify whichinstance commandshould be directedto. –e option willdirect thecommand to therunning emulatorinstance.adb devicesThe

Page 173: Android Security - Misra, Anmol

List of devicesconnected tothe adb server

output will printthe serial numberof each deviceattached as well asits state (offline,device).

Installing anapplication(apk)

adb –s emulator-5556 installhelloworld.apkThiscommand willinstall thehelloworld.apkapplication on the

Page 174: Android Security - Misra, Anmol

emulator instancewith serial number5556

Copying filesto/fromdevice/emulator

adb pull<remote><local>adb push<local><remote>adbpull will copy filereference by<remote>path toone referenced by<local>adb push

Page 175: Android Security - Misra, Anmol

will copy filereferenced by<local>path toone referenced by<remote>

View loginformation

adb logcatThis willprint log data toscreen

Interactive shell

adb shell<command>Thiswill execute shellcommands—e.g.,

Page 176: Android Security - Misra, Anmol

commands adb shell ps willprovide processlisting running onthe emulator orthe device

ExaminingSQLitedatabases

adb shellsqlite3This willdrop us to sqlite3command lineutility throughwhich we cananalyze SQLitedatabases on the

Page 177: Android Security - Misra, Anmol

system1. Download and install the

latest SDK. Setting up yourproject using older versions ofSDK may cause errors. If youhave set up your project usingthe latest version of SDK, skipto Step 4.

2. If you created your projectusing an older version of SDK,you will need to update theproject. Execute the commandbelow to display a list ofAndroid API versions andchoose the versionappropriate for your SDK:D:\eclipse\workspace>android.bat

Page 178: Android Security - Misra, Anmol

list targets\

3. Update your project, ifnecessary, with the target APIversion:D:\eclipse\workspace>android

update project –name Hello

World –target 3 –path

D:\eclipse\workspace\HelloWorld\

4. Run the ant command fromyour project directory:D:\eclipse\workspace\HelloWorld\ant

5. Edit the local.properties leand add the following line:proguard.config=proguard.cfg

6. Build the project in releasemode:ant release

Page 179: Android Security - Misra, Anmol

2.4 Anatomy of the “HelloWorld” Application

It is important to analyze theanatomy of the simple “HelloWorld” application to becomefamiliar with various les andcomponents within the project andapplication. Create a Hello Worldapplication by opening Eclipse,setting build target (i.e., Androidrelease version on which code willbe executed) to your desired API,and selecting the application andpackage name. Once you nish,your project directory shouldcontain a listing similar to the oneshown in Table 2.6. Two les are

Page 180: Android Security - Misra, Anmol

of special signi cance to security:AndroidManifest. xml andstrings.xml under the /resdirectory.

2.4.1 Understanding Hello World

Next, we will analyze the sourcecode of the Hello World applicationto get an overview of how it works.At the heart of every Androidapplication is activity.

Table 2.6 – Anatomy of anAndroid Application Folder

Folder Comments

The code for the

Page 181: Android Security - Misra, Anmol

src

applicationresides in thisfolder. In ourcase, theHelloActivity.javafile will belocated here

gen

The codegenerated forresources definedin the /res folderis located here

Page 182: Android Security - Misra, Anmol

Android 2.3.3

This contains theandroid.jar filefor the targetedversion ofAndroid

assets

Files that youwould like to bebundled withyour applicationreside in thisfolder

For compilingand running the

Page 183: Android Security - Misra, Anmol

bin

application, thisfolder willcontain theAndroidapplication (apk)as well asclasses.dex filesThis is whereresources for yourapplication willbe stored. Theseresources includelayout, values

Page 184: Android Security - Misra, Anmol

(includingstrings), anddrawables.Layouts, strings,and otherresources aredefined in XMLfiles. R classenables us toaccess theseresources andtheir values inJava code. Once

Page 185: Android Security - Misra, Anmol

res

resources aredefined in XMLfiles (e.g.,layout.xml,string.xml and soforth), one canreference them inthe applicationcode by referringtheir resource ID.The strings.xmlfile is of specialinterest to

Page 186: Android Security - Misra, Anmol

securityprofessionals.String values usedby theapplication canbe defined here.Manyapplicationschoose to storesensitiveinformation here,but it is not agood place

Page 187: Android Security - Misra, Anmol

because simplereverse-engineeringtechniques candivulge themDefines Androidapplicationcomponents(activities,services,BroadcastReceivers),package

Page 188: Android Security - Misra, Anmol

AndroidManifest.xml

information,permissionsrequired byapplications tointeract withotherapplications aswell as to accessprotected APIcalls, andpermissions forotherapplications to

Page 189: Android Security - Misra, Anmol

interact withapplicationcomponents

proguard-project.txtConfiguration filefor ProGuard

An activity is a single screen that auser interacts with on screen—forexample, the screen where the userenters his user ID and password tolog onto the Twitter application.

A useful application comprisesmultiple activities (one activity perscreen that the user willencounter). However, for oursimple application, we only have

Page 190: Android Security - Misra, Anmol

one activity (a single screen),which displays “Hello World,HellloWorldActivity.” Thisscreen/activity is displayed whenthe application is launched andwrites “Hello Logcat” to log.

Figure 2.13 shows the screenlaunched by HelloWorldActivity.Code Snippet 3 shows the sourcecode for our application. Afterde ning the package name(com.androidsecurity.helloworld),we import a few classes that weneed to write a fully functionalapplication. Some of these aremandatory (e.g., android.app.Activity), whereas others are

Page 191: Android Security - Misra, Anmol

application dependent (e.g.,android.util.Log). If we do notneed logging functionality in theapplication, we can skip importingthis class. Activity is a base classthat is needed if an applicationrequires visualcomponents/UI/screens. Theapplication activity class(HelloWorldActivity) will need toextend the base activity class andoverride the OnCreate() method toadd custom functionality. In theapplication, we overrideOnCreate() to set how thescreen/UI will look, as well as towrite a line to logcat. We set the

Page 192: Android Security - Misra, Anmol

layout of the screen throughsetContentView(R.layout.main). Ifwe have multiple screens, we couldchoose a di erent layout for eachscreen by setContentView(R.layout.secondlayout). secondlayoutwill correspond to thesecondlayout.xml le. R classprovides us with a way to referencethe layout and variables de ned inXML les in Java code. This is aglue between views/xml les andJava. Finally, we log “HelloLogCat!” to the log le byLog.v(“Hello World”, “HelloLogCat!”). Log.v indicates that wewant verbose log (as opposed to

Page 193: Android Security - Misra, Anmol

other logging levels, such as debug,warning, and so forth). “HelloWorld” in the above line tags theevent to be logged, and “HelloLogCat!” sets the value of the lineitself.

Page 194: Android Security - Misra, Anmol
Page 195: Android Security - Misra, Anmol

Figure 2.13 HelloWorldActivity

Code Snippet 3 –HelloWorldActivity Source Code

The layout or structure of ascreen/visual component is de nedin XML les. Since our applicationhas only one activity, we de ne

Page 196: Android Security - Misra, Anmol

only one layout(/res/layouts/main.xml). CodeSnippet 4 describes the main.xmllayout code. We basically create alinear layout and write text ontothe screen through TextView. Thetext to be written is determined by@string/hello. This line basicallytells the application to display astring value stored in the variablenamed “hello.” The value of “hello”is de ned in/res/values/strings.xml (CodeSnippet 5). There are two stringvalues in this le “hello” set to“Hello World, HelloWorldActivity”and “app_name” set to “Hello

Page 197: Android Security - Misra, Anmol

World.” The string “app_name” isreferenced by the Manifest.xml file.

Code Snippet 4 – main.xml file

Page 198: Android Security - Misra, Anmol

Code Snippet 5 – strings.xml file

As seen from the Consolewindow within Eclipse’s Javaperspective (Figure 2.14), afterlaunching the Android emulator,the application apk (HellloWorld.apk) is installed. Activity(com.androidsecrity.helloworld.HellloWorldActivity)is then begun. Note that activity isreferenced through the packagename (com.androidsecurity.helloworld).

Figure 2.15 shows the logcatentry written by our application.

2.5 Summary

Page 199: Android Security - Misra, Anmol

In this chapter, we reviewed theAndroid Software Stack as well asthe various layers within it. Weexamined in detail the Linux kerneland its security-relatedmechanisms, which Android relieson. We discussed Zygote andAndroid start up and then movedonto setting up the Androidenvironment for development andtesting purposes. We reviewedvarious tools available to usthrough the Android SDK. Weconcluded the chapter byexamining the structure of a typicalAndroid project and application.The reader should now be familiar

Page 200: Android Security - Misra, Anmol

with di erent terms used across thestack.

Page 201: Android Security - Misra, Anmol
Page 202: Android Security - Misra, Anmol

Figure 2.14 Console Messages while Running theHelloWorld Application

Page 203: Android Security - Misra, Anmol
Page 204: Android Security - Misra, Anmol

Figure 2.15 Logcat Entry Written by theHelloWorld Application

Page 205: Android Security - Misra, Anmol

Chapter 3Android Architecture

In this chapter, we introduce thereader to Android ApplicationArchitecture. We present variouscomponents that make up anAndroid application, and wedemonstrate how these componentswork when an application isrunning, through the use of logcat.We then cover the applicationlifecycle phases of an Androidapplication. By end of the chapter,the reader will be able to describethe typical components of an

Page 206: Android Security - Misra, Anmol

Android application, determinewhen to use these components, andunderstand application lifecyclephases.

3.1 Application Components

A typical Android application isusually rich in functionality—forexample, the built-in clockapplication. This application hasthe following basic functions:displaying time (in time zones),setting alarms, and setting astopwatch. Basically, these arethree di erent screens of the sameapplication. Besides its obviousfunctionality, this application

Page 207: Android Security - Misra, Anmol

needs to communicate with back-end servers for time updates,execute a component in thebackground (service) for alarms,synchronize with a built-inprocessor clock, and so forth. Thus,even a simple Android applicationhas multiple building blocks. Thereare four main components of anAndroid application: activities,BroadcastReceivers,ContentProviders, and services.These components interact witheach other

Page 208: Android Security - Misra, Anmol

Figure 3.1 Components of an AndroidApplication

(or with components of otherapplications) through messagescalled Intents. Figure 3.1 depictsthe main components of anAndroid application.

3.1.1 Activities

Activities are basically screens that

Page 209: Android Security - Misra, Anmol

the user sees or interacts withvisually. They can be thought of asvisual user interface (UI)components of an application.Most applications will havemultiple activities (one for eachscreen that the user sees/interactswith). The user will switch backand forth among activities (in noparticular order, at times). Forseamless end-user experience, theuser is able to launch di erentactivities for the same applicationin any order (with someexceptions). The user can alsolaunch the activity of anotherapplication (through Intents,

Page 210: Android Security - Misra, Anmol

covered later in the chapter), asshown in Figure 3.2. Every Androidapplication has an activity that islaunched when an applicationstarts. From this activity, the usercan then navigate to di erentactivities or components within theapplication. There is usually a wayfor the user to revert to a previousactivity. In a nutshell, through theactivity UI screen, the userinteracts with the application andaccesses its functionality. Examplesof activities are:

Page 211: Android Security - Misra, Anmol

Figure 3.2 Activity Interaction between AndroidApplications

- Log-in screen of an application- Composing an e-mail- Sending a photo through an e-

mail

An application consists ofmultiple activities tied together forend-user experience. Usually, whenan application starts, there is a“main” activity that is launchedand a UI screen is presented to theuser.

The activity class creates screens,and developers can create UI

Page 212: Android Security - Misra, Anmol

components usingsetContentView(View). One has tocreate a subclass of the “activity”class to create an activity. In thisclass, one has to implement(override) relevant callbackmethods that will be called whenan activity is created, transitioned(paused, stopped, sent into thebackground), or destroyed. Thereare quite a few callback methods.However, the most important ones(frequently used) are OnCreate()and OnPause().

- OnCreate(Bundle): This iswhere activity is initialized,

Page 213: Android Security - Misra, Anmol

and every activity classimplements this method.Usually, setContentView(Int)is called within OnCreate()and de nes the UI of thescreen/activity.

ndViewById(Int) is used tond resources and interact

with them programmatically.- onPause(): If a user decides to

leave an activity, the savingof the state or importantoperations are performed bythis method.

Other important methods for anactivity class are as follows:

Page 214: Android Security - Misra, Anmol

onStart(), onRestart(), onResume(),onStop(), and onDestroy(). Wecover these in our discussion onActivity Lifecycles later in thechapter.

Code Snippet 1 shows thede nition of a typical activity class(Activity A, in this case). TheActivity A class extends the baseclass (activity), de nes thevariables, and then overrides andimplements callbacks—speci callyOnCreate(). Inside OnCreate(),activity de nes the UI by callingsetConventView() andfindViewById().

Page 215: Android Security - Misra, Anmol

Code Snippet 1 – Activity AOnCreate() Method

Every activity in an applicationneeds to be declared inside the

Page 216: Android Security - Misra, Anmol

Manifest le. Any activity that isnot declared in Manifest won’t beregistered in the system and thuswon’t be allowed to execute.

Code Snippet 2 shows theManifest le with declarations foractivities. Activity declaration isdone through <activity> tag andis a child of the <application>element in the le. Inside the<activity> tag, we de neattributes for that activity.android:name provides the classname for the activity. <activity>tag contains the Intent lters aswell as the metadata for anactivity.

Page 217: Android Security - Misra, Anmol

The Manifest le needs to havean entry for each activity in anapplication. In the snippet here,the application is composed ofthree di erent activities—A, B, andC. As is evident from the Manifest

le, Activity A is the main activityand is launched when theapplication starts. Also note thatActivity A has Intent de ned. Forthis Intent, the action is MAIN andthe category is set to LAUNCHER,thus enabling the activity to beavailable in the applicationlauncher and enabling the user tostart the application.

For detailed information on

Page 218: Android Security - Misra, Anmol

other attributes, please refer to thefollowing URL:http://developer.android.com/guide/topics/manifest/activity-element.html

Code Snippet 2 – Activities inManifest File

Since an application can startactivities within other applications,

Page 219: Android Security - Misra, Anmol

we need to limit the ability of otherapplications to start a particularactivity. This is enforced usingpermissions in the AndroidManifest le. Other applicationswill need to request access to thesepermissions through uses-permission. Activity permissions(applied under <activity> tagthrough android:permission)enable us to restrict who can startthat activity. The permission ischecked whenContext.startActivity() orActivity.startActivityForResult() arecalled. If the caller does not havepermission, the request to start an

Page 220: Android Security - Misra, Anmol

activity is denied.

3.1.2 Intents

Intents are messages through whichother application components(activities, services, and BroadcastReceivers) are activated. They canbe thought of as messages statingwhich operations/actions need tobe performed. Through Intents, theAndroid provides a mechanism forlate run-time binding betweenapplication components (withinthe same application or amongdi erent applications). Intentsthemselves are objects containinginformation on operations to be

Page 221: Android Security - Misra, Anmol

performed or, in the case ofBroadcast Receivers, on details ofan event that occurred.

Consider an application like theN.Y. Times. Within thisapplication, there are di erentactivities—an activity that presentsa list of articles available, anactivity that displays an article, adialog activity that allows us tomark it as favorite, and so forth.This application also allows us toshare articles with others bysending links in e-mails. As shownin Figure 3.3, these interactions areachieved by switching betweendifferent activities through Intents.

Page 222: Android Security - Misra, Anmol

Intents are delivered by variousmethods to application componentsdepending on whether thecomponent is a service, activity, ora Broadcast Receiver, as presentedin Table 3.1.

Intent is a data structuredesigned to hold information onevents or operations to beperformed. Intents contain twoprimary pieces of information:

- Action to be performed- Data on which action will be

performed, expressed asUniform Resource Identi er(URI)

Page 223: Android Security - Misra, Anmol

Shown below are a few examplesof action/data pairs:

- ACTION_DIALcontent://contacts/people/1This will display the numberof the person in the phonedialer.

- ACTION_DIAL tel:123This will display the number123 in the phone dialer.

Page 224: Android Security - Misra, Anmol
Page 225: Android Security - Misra, Anmol

Figure 3.3 Use of Intents

Table 3.1 – Methods DeliveringIntents to Components

ApplicationComponents

Activity Context.startActivity()Activity.startActivtyForResult()Activity.setResult()

Service Context.startService()Context.bindService()

BroadcastReceivers

Context.sendBroadcast()Context.sendOrderedBroadcast()Context.sendStickyBroadcast()

There are other pieces ofinformation that can be providedin an Intent:

Page 226: Android Security - Misra, Anmol

- Category – providesinformation on the category ofaction. If it is set toCATEGORY_LAUNCHER, thisactivity will appear in theapplication launcher.

- Type – provides explicit type ofIntent data (thus bypassingbuilt-in evaluation).

- Component – provides name ofthe component that willhandle the Intent. This is not arequired eld. If it is empty,other information provided inthe bundle will be used toidentify the appropriatetarget.

Page 227: Android Security - Misra, Anmol

- Extras – any additionalinformation that needs to beprovided. These extra piecesof information are providedthrough android.os.Bundle.

Through attributes, Intents allowthe expression of operations andevents. For example, an activitycan pass on an Intent to the e-mailapplication to compose anapplication with an e-mail ID.Intents can be classi ed into twodi erent types: explicit andimplicit.

Explicit Intents provide thecomponent name (class name) that

Page 228: Android Security - Misra, Anmol

must be invoked through theIntent. This is usually for inter-application components, sinceother applications would nottypically know component names.Here is a typical invocation ofexplicit Intent:

Intent i = new Intent(this,<activity_name>.class);

Implicit Intents, on the otherhand, are used to invokecomponents of di erentapplications (e.g., photoapplication sending an e-mailIntent to e-mail application to send

Page 229: Android Security - Misra, Anmol

a photo through an e-mail). Theydo not provide the speci ccomponent name to be invoked butrely on the system to nd the bestavailable component to beinvoked. For this to be possible,each component can provideIntent- lters—structures thatprovide information on whichIntents can be handled byparticular components. The systemthen compares lters to the Intentobject and selects the best availablecomponent for it. Intent- ltersprovide a way to specify whichIntents a component is willing tohandle and can help de-limit the

Page 230: Android Security - Misra, Anmol

invoking of a component throughimplicit Intent. If a componentdoes not have Intent- lters, it canonly receive explicit Intents. Notethat Intent- lters cannot be reliedon for security because one canalways send an explicit Intent to it,thus bypassing the lters.Component speci c permissionsshould always be de ned to restrictwho can access a particularcomponent through Intents. Inaddition, limited data can bepassed through Intents. However,any sensitive information, such aspasswords, should never be sentthrough Intents, as these can be

Page 231: Android Security - Misra, Anmol

received by malicious components.A typical invocation of implicit

Intent is as follows:

Intent I = newIntent(Intent.ACTION_VIEW,

Uri.parse(http://www.google.com));

When an Intent object is comparedto a lter by the system, the three

elds (elucidated in Table 3.2) aretested/compared, and thus acomponent servicing the Intentneeds to provide this informationin its filter.

The Manifest.XML files for Phone

Page 232: Android Security - Misra, Anmol

and Browser applications arepresented in Figures 3.4 and 3.5.Both of these applications areinstalled by default on Androiddevices, and, thus, otherapplications can leverage them formaking calls and browsing theweb. The Phone applicationprovides many Intent lters,includingandroid.intent.action_CALL withdata type of “tel.” If an applicationtries to make a phone call, anIntent will be sent to the Phoneapplication with data type(number to call). The Browserapplication provides Intent lters

Page 233: Android Security - Misra, Anmol

for android.intent.action_VIEW,among others. This enables otherapplications to pass the URL to theBrowser application.

Table 3.2 – Intent Fields andTheir Descriptions

IntentField

Purpose

Action

A string with the name of theaction being performed orevent that has taken place (inthe case of BroadcastReceivers). Examples:

Page 234: Android Security - Misra, Anmol

ACTION_CALL,ACTIION_TIMEZONE_CHANGED

Data

URI and MIME type of data tobe acted upon. Example:ACTION_VIEW will have URLassociated with it whileACTION_CALL will have tel:data type

Category

Provides additional informationon the kind of component thatshould handle/service theIntent. Categories can be set toCATEGORY_HOME,

Page 235: Android Security - Misra, Anmol

CATEGORY_LAUNCHER,CATEGORY_BROWSABLE, andso forth

Page 236: Android Security - Misra, Anmol
Page 237: Android Security - Misra, Anmol

Figure 3.4 Manifest.XML File for PhoneApplication

Page 238: Android Security - Misra, Anmol
Page 239: Android Security - Misra, Anmol

Figure 3.5 Manifest.XML File for BrowserApplication

3.1.3 Broadcast Receivers

Broadcast Receivers deal withIntents. They are a means wherebyAndroid applications and systemcomponents can communicate witheach other by subscribing to certainIntents. The receiver is dormantuntil it receives an activatingIntent; it is then activated andperforms a certain action. Thesystem (and applications) canbroadcast Intents to anyone who isinterested in receiving them(although this can be restricted

Page 240: Android Security - Misra, Anmol

through security permissions). Afteran Intent is broadcasted, interestedreceivers having requiredpermissions can be activated by thesystem.

The Android system itselfbroadcasts Intents for interestedreceivers. The following is a list ofAndroid System Broadcast Intents:

• ACTION_TIME_TICK• ACTION_TIME_CHANGED•

ACTION_TIMEZONE_CHANGED• ACTION_BOOT_COMPLETED• ACTION_PACKAGE_ADDED

Page 241: Android Security - Misra, Anmol

• ACTION_PACKAGE_CHANGED• ACTION_PACKAGE_REMOVED•

ACTION_PACKAGE_RESTARTED•

ACTION_PACKAGE_DATA_CLEARED• ACTION_UID_REMOVED• ACTION_BATTERY_CHANGED• ACTION_POWER_CONNECTED•

ACTION_POWER_DISCONNECTED• ACTION_SHUTDOWN

An alarm application might beinterested in receiving the

Page 242: Android Security - Misra, Anmol

following two broadcasts from thesystem: ACTION_TIME_CHANGEDandACTION_TIMEZONE_CHANGED.Broadcast Receivers themselves donot have a UI component. Rather,the application (through theactivity) will de ne theonReceive() method to receive andact on a broadcast. The activitywill need to extend theandroid.content.BroadcastReceiverclass and implement onReceive().

An application can sendbroadcasts to itself or to otherapplications as well. BroadcastReceivers need to be registered in

Page 243: Android Security - Misra, Anmol

the Manifest.xml le. This enablesthe system to register yourapplication to receive particularbroadcast. Let’s take the exampleof our time application. To receiveACTION_TIME_CHANGED andACTION_TIMEZONE_CHANGEDbroadcasts, the application needsto declare the register method inthe Manifest.xml le with eventswe are interested in receiving. Bydoing this, we register ourBroadcastReceivers with the systemwhich activates our receiver whenthe event happens. Code Snippet 3shows the Manifest.xml le with adeclaration for TimeReceiver. The

Page 244: Android Security - Misra, Anmol

TimeReceiver will override thecallback onReceive().

We need to request permissionsrequired to receive Intents toreceive certain broadcasts.

Code Snippet 3 – RegisteringBroadcast Receivers

To receive certain broadcasts,one will need to have requisitepermissions (e.g., to receiveBOOT_COMPLETED broadcast, one

Page 245: Android Security - Misra, Anmol

needs to holdRECEIVE_BOOT_COMPLETEDpermission). In addition,BroadcastReceiver permissionsrestrict who can send broadcasts tothe associated receiver. When thesystem tries to deliver broadcasts toreceivers, it checks the permissionsof the receiver. If the receiver doesnot have the required permissions,it will not deliver the Intent.

3.1.4 Services

A service is an applicationcomponent that can perform long-running operations in thebackground for an application. It

Page 246: Android Security - Misra, Anmol

does not have a UI component toit, but it executes tasks in thebackground—for example, analarm or music player. Otherapplications can be running in thefront while services will be activebehind the curtain even after theuser switches to a di erentapplication component orapplication. In addition, anapplication component may“bound” itself to a service and thusinteract with it in background; forexample, an applicationcomponent can bind itself to amusic player service and interactwith it as needed. Thus, service can

Page 247: Android Security - Misra, Anmol

be in two states:

- Started- Bound

When an application componentlaunches a service, it is “started.”This is done through thestartService() callback method.Once the service is started, it cancontinue to run in the backgroundafter the starting component (or itsapplication) is no longer executing.

An application component canbind itself to a service by callingbindService(). A bound service canbe used as a client-server

Page 248: Android Security - Misra, Anmol

mechanism, and a component caninteract with the service. Theservice will run only as long as thecomponent is bound to it. Once itunbinds, the service is destroyed.Any application component (orother applications) can start orbind to a service once it receivesthe requisite permissions. This isachieved through Intents.

To create a service, one mustcreate a subclass of service andimplement callback methods. Mostimportant callback methods forservice are onStartcommand(),onBind(), onCreate(), andonDestroy().

Page 249: Android Security - Misra, Anmol

onStartCommand()

This callback method is called bythe system when anotherapplication component requests aparticular service to be started bycalling startService(). This servicethen will run until it encountersstopSelf() or stopService().

onBind()

This callback method is calledwhen another component wouldlike to be bound to the service bycalling bindService().

onCreate()

Page 250: Android Security - Misra, Anmol

When the service is rst created,this method will perform initialsetup before callingonStartCommand() or onBind().

onDestroy()

This callback method is calledwhen the service is no longerneeded or being used.

Note that an Android will stop aservice in case it needs to recoversystem resources (e.g., it is low onmemory). As with othercomponents, one needs to declareservices in the Manifest.xml le.

Page 251: Android Security - Misra, Anmol

Services are declared under the<service> tag as a child of the<application> tag. Code Snippet4 depicts a typical declaration ofservice in the Manifest le. Theandroid:name attribute speci es aclass name for the service. Aservice can be invoked by otherapplications if it has de nedIntent-filters.

Code Snippet 4 – Services in the

Page 252: Android Security - Misra, Anmol

Manifest File

As with other applicationcomponents, one can restrict whichapplications can start or bind to aservice. These permissions arede ned within the <services> tagand are checked by the systemwhen Context.startService(),Context.stopService(), orContent.bindService() are called. Ifthe caller does not have requiredpermissions, the request to start orbound to a service is denied.

3.1.5 Content Providers

Content providers provide

Page 253: Android Security - Misra, Anmol

applications with a means to sharepersistent data. A content providercan be thought of as a repository ofdata, and di erent applicationscan de ne content providers toaccess it. Applications can sharedata through Intents. However, thisis not suited for sharing sensitive orpersistent data. Content providersaim to solve this problem.Providers and provider clientsenable a standard interface toshare data in a secure and e cientmanner—for example, theAndroid’s Contacts Provider. TheAndroid has a default applicationthat accesses this provider.

Page 254: Android Security - Misra, Anmol

However, one can write anapplication that has a di erent UIaccessing and presenting the sameunderlying data provided by theContacts Provider. Thus, if anyapplication makes changes to thecontacts, that data will beavailable for other applicationsaccessing the Contacts Provider.When an application wants toaccess data in a content provider,it does so throughContentResolver().

The content provider needs to bedeclared like other applicationcomponents in the Manifest.xml

le. One can control who can

Page 255: Android Security - Misra, Anmol

access the content provider byde ning permissions inside the<provider> tag. One can setandroid:readPermission andandroid.writePermission to controlthe type of operations otherapplication components canperform on content providers. Thesystem will perform a check forrequisite permissions whenContent.Resolver. query(),Content.Resolver.insert(),Content.Resolver.update(), andContent. Resolver.delete() methodsare called. If the caller does nothave requisite permissions, therequest to access the content

Page 256: Android Security - Misra, Anmol

provider is denied.

3.2 Activity Lifecycles

In this chapter, we have introducedactivities and discussed callbackmethods that activities implement,such as onCreate(), onPause(),onStart(), onRestart(), onResume(),onStop(), and onDestroy(). We willnow cover activity lifecycles in abit more detail.

As we have seen, activities areUI screens for users to interactwith. A typical application consistsof multiple activities, and the userseamlessly switches back and forthbetween them. The user can also

Page 257: Android Security - Misra, Anmol

launch the activity of anotherapplication (done through Intents).It is important to understandactivity lifecycles, especially fordevelopers, because when activitiesare switched or terminated, certaincallback methods need to beimplemented. If an activity doesnot implement required callbacks,this can lead to performanceand/or reliability issues.

Activities are managed as anactivity stack. When the usernavigates an application, activitiesgo through di erent states in theirlifecycle. For example, when a newactivity is started, it is put on top

Page 258: Android Security - Misra, Anmol

of the stack (and have user focus)and becomes the running activity,with previously running activitypushed below it on the stack. Thesystem will call di erent lifecyclemethods for di erent states ofactivities. It will call eitheronCreate(), onRestart(), onStart(),or onResume() when an activitygains focus or comes to theforeground. The system will call adi erent set of callbacks (e.g.,onPause()) when an activity losesfocus.

- Active/Running: Activity is inthis state if it is in the

Page 259: Android Security - Misra, Anmol

foreground and has user focus.- Paused: Activity is in this state

if it has lost focus but is stillvisible, as non–full-sizeactivity has taken focus.Activity still retains stateinformation and can be killedin case the system is low inresources.

- Stopped: If an activity losesfocus to a full-screen activity,then its state changes toStopped. The activity stillretains state information andcan be killed in case thesystem is low in resources.

Page 260: Android Security - Misra, Anmol

- Inactive/Killed: A system cankill activity if it is in paused orstopped state. When re-launched, activity will have toinitialize its state and memberinformation again.

Figure 3.6 shows important pathsin lifecycle activity. Rectanglesrepresent di erent callbackmethods that can be implementedwhen an activity moves betweenstates. Ovals represent di erentstates an activity can be in.

By the time an activity isdestroyed, it might have gonethrough multiple iterations of

Page 261: Android Security - Misra, Anmol

becoming active orinactive(paused). During eachtransition, callback methods areexecuted to transition betweenstates. It is useful to look at anactivity timeline from threedifferent views:

Page 262: Android Security - Misra, Anmol

Figure 3.6 Activity Lifecycle and CallbackMethods

Page 263: Android Security - Misra, Anmol

- Entire lifetime: The timeline ofan activity between the rstcall to onCreate() and the callto onDestroy() is its entirelifetime. This includes alliterations that an activity willgo through until it isdestroyed. onCreate() sets upthe state for an activity(including resources), whileonDestroy() frees up resourcesconsumed by the activity.

- Visible lifetime: This lifetimecorresponds to the time a usersees activity on screen. Thishappens between one cycle ofonStart() and onStop().

Page 264: Android Security - Misra, Anmol

Although activity might bevisible, the user might notnecessarily be able to interactwith it.

- Foreground lifetime: Thislifetime corresponds to thetime that a user can actuallyinteract with the activity. Thishappens between the call toonResume() and the call toonPause().

Table 3.3 – Activity LifecycleCallback Description

Method Description

Called when an

Page 265: Android Security - Misra, Anmol

onCreate()activity is firstlaunched. Performsinitial setup for anactivity

onRestart()

Called when anactivity was stoppedearly and needs tobe restarted

onStart()

Called when anactivity comes toforeground andbecomes available to

Page 266: Android Security - Misra, Anmol

the user forinteraction

onResume()

Called when anactivity comes to theforeground andstarts interactingwith the user

onPause()

Called when thesystem would like toresume previouslypaused activity.Changes that need to

Page 267: Android Security - Misra, Anmol

be saved are usuallymade in this methodbefore an activitypauses itself

onStop()Called when anactivity is no longervisible to the user

onDestroy()Called when thesystem wants to freeup resources

Callback methods and theirdescriptions relevant to activitylifecycles are described in Table

Page 268: Android Security - Misra, Anmol

3.3.We will review an activity

lifecycle by walking through anapplication (available fromdeveloper.android.com). We havemodi ed the code to outputinformation to logcat. Theapplication is composed of threedi erent activities (UI screens)—Activity A, B, and C (see Figure3.7). The user can switch betweenthese activities by clicking a buttonprovided on the activity. Switchingbetween activities launches variouscallback methods, and previouslyrunning activity is put on the stack.The user can also return to

Page 269: Android Security - Misra, Anmol

previously running activity usingthe application. Let’s walk throughthe following sequence of activityswitching: launching Activity A,Activity B, and Activity C and thencoming back to Activity B andActivity A. We will review theoutput from logcat to see thelifecycle methods being called.

Activity Lifecycle Demonstration

1. Launch Activity A by startingthe application (as this is ourmain activity). Reviewingoutput from logcat (see Figure3.8) shows that the following

Page 270: Android Security - Misra, Anmol

methods are called in order:onCreate(), onStart() andonResume() after the ActivityManager starts the mainactivity (Activity A, in ourcase).

2. Launch Activity B by clickingthe “Start B” button. Uponreviewing the output in logcat(see Figure 3.9), we see thatonPause() was called inActivity A, thus putting it onthe stack. Activity B then wasstarted by the ActivityManager, and methodsonCreate(), onStart(), andonResume() were called. Once

Page 271: Android Security - Misra, Anmol

Activity B came to theforeground, onStop() wascalled from Activity A. Weobserve the same sequence ofcallback methods when weswitch to Activity C fromActivity B (see Figure 3.10). 3.Now click the “Finish C”button in Activity C andobserve the sequence ofcallback methods (see Figure3.11). We see that onPause()is called from Activity C; then,the next activity on the stack(Activity B) is started. OnceActivity B is in the foreground,onStop() and onDestroy() are

Page 272: Android Security - Misra, Anmol

called for Activity C, thusfreeing up resources for thesystem. We observe a similarsequence of callback methodswhen we “Start A” fromActivity B (Figure 3.12).

Page 273: Android Security - Misra, Anmol
Page 274: Android Security - Misra, Anmol

Figure 3.7 Screenshot of Activity LifecycleApplication

Page 275: Android Security - Misra, Anmol
Page 276: Android Security - Misra, Anmol

Figure 3.8 Activity Lifecycle: Activity ALaunched

Page 277: Android Security - Misra, Anmol
Page 278: Android Security - Misra, Anmol

Figure 3.9 Activity Lifecycle: Activity BLaunched

Page 279: Android Security - Misra, Anmol
Page 280: Android Security - Misra, Anmol

Figure 3.10 Activity Lifecycle: Activity CLaunched

Page 281: Android Security - Misra, Anmol
Page 282: Android Security - Misra, Anmol

Figure 3.11 Activity Lifecycle: Activity CCompleted

Page 283: Android Security - Misra, Anmol
Page 284: Android Security - Misra, Anmol

Figure 3.12 Activity Lifecycle: Activity A IsLaunched

3.3 Summary

In this chapter, we discussedAndroid application components(activities, Broadcast Receivers,Content Providers, and services) indetail. We also discussed Intents—messages sent between applicationcomponents or within applications.We then discussed activitylifecycles and di erent callbackmethods that are implemented bythe activities. The reader shouldnow be able to describe the majorcomponents of Android

Page 285: Android Security - Misra, Anmol

applications, the interactionsbetween them, and the activitylifecycle methods.

Page 286: Android Security - Misra, Anmol

Chapter 4Android (in)Security

In this chapter, we turn our focusto Android’s built-in securitymechanisms at the platform levelas well as its application layers.The reader should be familiar withAndroid architecture (covered inChapter 2) and Androidapplication basics (building blocks,frameworks) (covered in Chapter3). This chapter builds on anunderstanding of the platform andapplication layers to demonstratethe security features provided by

Page 287: Android Security - Misra, Anmol

Android. This chapter alsointroduces the reader to di erentInterprocess Communication (IPC)mechanisms used by Androidapplication components.

DETOUR

Di erent applications and processes need tocommunicate with each other and sharedata/information. This communicationoccurs through the IPC mechanism—forexample, in Linux, signals can be used as aform of IPC.

4.1 Android Security Model

Android developers have includedsecurity in the design of the

Page 288: Android Security - Misra, Anmol

platform itself. This is visible in thetwo-tiered security model used byAndroid applications and enforcedby Android. Android, at its core,relies on one of the securityfeatures provided by Linux kernel—running each application as aseparate process with its own set ofdata structures and preventingother processes from interferingwith its execution.

At the application layer, Androiduses ner-grained permissions toallow (or disallow) applications orcomponents to interact with otherapplications/components or criticalresources. User approval is

Page 289: Android Security - Misra, Anmol

required before an application canget access to critical operations(e.g., making calls, sending SMSmessages). Applications explicitlyrequest the permissions they needin order to execute successfully. Bydefault, no application haspermission to perform anyoperations that might adverselyimpact other applications, theuser’s data, or the system.Examples of such operationsinclude sending SMS messages,reading contact information, andaccessing the Web. Playing music

les or viewing pictures do not fallunder such operations, and, thus,

Page 290: Android Security - Misra, Anmol

an application does not need toexplicitly request permissions forthese. Application-levelpermissions provide a means to getaccess to restricted content andAPIs.

Each Android application (orcomponent) runs in a separateDalvik Virtual Machine (VM)—asandbox. However, the readershould not assume that thissandbox enforces security. TheDalvik VM is optimized for runningon embedded devices e ciently,with a small footprint. It is possibleto break out of this sandbox VM,and, thus, it cannot be relied on to

Page 291: Android Security - Misra, Anmol

enforce security. Androidpermission checks are notimplemented inside the Dalvik VMbut, rather, inside the Linux kernelcode and enforced at runtime.

Access to low-level Linuxfacilities is provided through userand group ID enforcement,whereas additional ne-grainedsecurity features are providedthrough Manifest permissions.

4.2 Permission Enforcement—Linux

When a new application isinstalled on the Android platform,Android assigns it a unique user id

Page 292: Android Security - Misra, Anmol

(UID) and a group id (GID). Eachinstalled application has a set ofdata structures and les that areassociated with its UID and GID.Permissions to access thesestructures and les are allowedonly to the application itself(through its ID) or to the superuser(root). However, other applicationsdo not have elevated superuserprivileges (nor can they get them)and, thus, cannot access otherapplications’ files. If an applicationneeds to share information withother application(s) orcomponent(s), the MAC securitymodel is enforced at the

Page 293: Android Security - Misra, Anmol

application layer (discussed in thenext section).

It is possible for two applicationsto share the same UID or run in thesame process. This can be the caseif two applications have beensigned by the same key (seeapplication signing in Chapter 3).This should underscore theimportance of signing keys safelyfor developers. Androidapplications run in separateprocesses that are owned by theirrespective UID and thus sandboxedfrom each other. This enablesapplications to use native code(and native libraries) without

Page 294: Android Security - Misra, Anmol

worrying about securityimplications. Android takes care ofit.

Figure 4.1 id Command on the Emulator

Note that Linux is a multi-usermultitasking OS. In contrast,Android is meant to deliver single-user experience. It leverages asecurity model meant for multipleusers in Linux and applies toapplications through Linuxpermissions.

Page 295: Android Security - Misra, Anmol

Figure 4.1 is a screenshotshowing the UID of the user whenconnected to the Android emulator.In this case, UID (and GID) = 0.This has special signi cance in the*NIX environment, as this denotessuperuser (equivalent toAdministrator in a traditionalWindows environment). Asuperuser can perform pretty muchall operations and access all files.

Note: Obtaining the shell throughthe emulator will give you rootuser access. However, if youperform this test on the phone, youwill be assigned a “system” or“shell” UID, unless, of course, you

Page 296: Android Security - Misra, Anmol

have rooted your phone.Each application installed on

Android has an entry in /data/datadirectory. Figure 4.2 is a screenshotshowing the ls –l command on thisdirectory. The output listspermissions for each directoryalong with owner (UID), group(GID), and other details. As thereader can see, any two-application directories are ownedby respective UIDs.

In the screenshot presented inFigure 4.2, app_1 (htmlviewer)owns the com.android.htmlviewerdirectory, and, thus, it cannotaccess les in the

Page 297: Android Security - Misra, Anmol

com.android.music directory, whichis owned by app_5.

If Android applications createnew les usinggetSharedPreferences(),openFileOutput(), oropenOrCreateDatabase() functioncalls, the application can useMODE_WORLD_READABLE and/orMODE_WORLD_WRITEABLE ags.If these ags are not set carefully,other applications can read/writeto les created by your application(even if the files are owned by yourapplication).

The UID of an application is theowner of the process when the

Page 298: Android Security - Misra, Anmol

application runs. This enables it toaccess les (owned by the UID),but any other process cannotdirectly access these les. They willhave to communicate throughallowed IPC mechanisms. Eachprocess has its own address spaceduring execution, including stack,heap, and so forth.

Figure 4.3 is a screenshotdemonstrating the output of the“ps” command. The ps commandprovides a list of processes runningand corresponding stateinformation. As can be seen in thisscreenshot, each process(application) belongs to the

Page 299: Android Security - Misra, Anmol

corresponding UID.

Figure 4.2 ls Command Executed on /data/dataShows Directory Ownership

Page 300: Android Security - Misra, Anmol

The com.mj.iCalender process isowned by app_36 (UID 36), whichthe iCalender application wasassigned during the install process.Many processes are owned by theroot or system user. The root userowns daemons (e.g., init) and thesystem user owns servicemanagers. These are specialprocesses that manage and provideAndroid functionality and thus arenot controlled by the user.

Page 301: Android Security - Misra, Anmol

Figure 4.3 ps Command Shows ProcessOwnership

An application can request toshare a UID by using“android:shareUserId” in theManifest le (discussed later).Android will grant the request ifthe application has been signed bythe same certi cate. An entry inthe Manifest le to request thesame UID looks like this:

4.3 Android’s Manifest

Page 302: Android Security - Misra, Anmol

Permissions

The Linux kernel sandboxesdi erent applications and preventsthem from accessing otherapplications’ data or userinformation, or from performingoperations such as accessing theInternet, making phone calls, orreceiving SMS messages. If anapplication needs to perform theaforementioned operations (e.g.,Internet access), read the user’sinformation (e.g., contacts), or talkto other applications (e.g.,communicate with the e-mailapplication), the application needsto speci cally request these

Page 303: Android Security - Misra, Anmol

permissions (MAC model).Applications declare thesepermissions in their con guration

le (Manifest.xml). When anapplication is installed, Androidprompts the user to either allow orreject requested permissions (seeFigure 4.4). A user cannot selectcertain permissions—that is, allowaccess to the Internet and rejectSMS access. The applicationrequests a set of permissions, andthe users either approve or deny allof them. Once the user hasapproved these permissions,Android (through the Linux kernel)will grant access to the requested

Page 304: Android Security - Misra, Anmol

operations or allow interactionwith di erentapplications/components. Pleasenote that once the user hasapproved permissions, he cannotrevoke them. The only way toremove the permissions is touninstall the application. This isbecause Android does not have themeans to grant permissions atruntime, as it will lead to less user-friendly applications.

Android permissions are alsodisplayed to the end-user whendownloading applications from the“o cial” Android market (seeFigure 4.5). However, this might

Page 305: Android Security - Misra, Anmol

not always be the case, as there arequite a few sources for Androidapplications. If the user justdownloads .apk les, a warningabout security implications willonly be displaced during runtime.

Page 306: Android Security - Misra, Anmol

Figure 4.4 Android Requesting User Consentduring Install Process

Page 307: Android Security - Misra, Anmol

4.3.1 Requesting Permissions

Since an Android applicationcannot perform any operationsthat would adversely impact theuser’s experience or access anydata on the device by default, itneeds to request these “protected”features explicitly. These arerequested in theAndroidManifest.xml le and areusually called Manifest permissions(compared to the Linux permissionsdiscussed earlier). Requestedpermissions are contained within<uses-permission> tags within the

le. Below is an example of anapplication that is requesting

Page 308: Android Security - Misra, Anmol

Internet access and reads MMS andSMS messages:

Page 309: Android Security - Misra, Anmol
Page 310: Android Security - Misra, Anmol

Figure 4.5 YouTube Application PermissionsListing (Android Marketplace) (Google and theGoogle logo are registered trademarks of GoogleInc., used with permission.)

If an application tries to performan operation for which it has nopermission (e.g., read SMS),Android will typically throw aSecurityException back to theapplication. The Android systemprovides default permissionde nitions (Manifest Permissions).These cover lot of applicationfunctionality (reading SMS,sending MMS, accessing theInternet, mounting le systems).However, an application can

Page 311: Android Security - Misra, Anmol

de ne its own permissions. Thiswould be needed if the applicationwould like to expose itsfunctionality (through activities orother components) for use withother applications or if theapplication wants to enforce itsown permissions (not known toother applications).

If an application wants tocontrol which applications (or theircomponents) can start/access itsactivities, it can enforce using thistype of permission in the Manifestpermission file:

Page 312: Android Security - Misra, Anmol

In the above snippet,android:name describes the nameof a newly created permission,which can be used by applications(including this one) through the<uses-permission> tag in theManifest le. The android:labelprovides a short name for thepermission (which is displayed tothe user) while android:descriptionprovides the user with information

Page 313: Android Security - Misra, Anmol

on the meaning of the permission.For example, the label can beEXPENSIVE FEATURE, while thedescription can be something like,“This feature will allow theapplication to send premium SMSmessages and receive MMS. Thiscan add to your costs as it will becharged to your airtime.” Theandroid:protectionLevel de nes therisk the user will be taking byallowing the application to use thispermission. There are four differentlevels of protection categories (seeTable 4.1):

You can obtain a list of all

Page 314: Android Security - Misra, Anmol

permissions by group through thefollowing command (Figure 4.6)

Table 4.1 – Android UserProtection Levels

ProtectionLevel

Description

This is the defaultvalue. It allows anapplication to getaccess to isolatedfeatures that pose

Page 315: Android Security - Misra, Anmol

Normalminimal risk to otherapplications, the user,or the system. It isgranted automaticallyby the system, but theuser can still review itduring the installtime.

Allows the applicationto perform certainoperations that cancost the user money or

Page 316: Android Security - Misra, Anmol

Dangerous use data in a way thatcan impact the user ina negative manner.The user needs toexplicitly approvethese permissions.

Signature

Granted only if theapplication signedwith the samecertificate as theapplication thatdeclared thepermission.

Page 317: Android Security - Misra, Anmol

Signatureor system

Granted only toapplications that arein the Android systemimage or that aresigned with the samecertificates as those inthe system image

A detailed description ofpermissions de ned in the systemcan be obtained through (Figure4.7)

To obtain descriptions of allpermissions de ned on the device

Page 318: Android Security - Misra, Anmol

you can use (Figure 4.8)

4.3.2 Putting It All Together

To sum up, the Linux kernelsandboxes applications andprovides security by enforcingUID/GID permissions. Anapplication can request additionalpermissions that, if approved bythe end-user, will be allowedthrough Android runtime. Allapplications (Java, native, andhybrid) are sandboxed in the samemanner.

Page 319: Android Security - Misra, Anmol
Page 320: Android Security - Misra, Anmol

Figure 4.6 Android Permissions on System (bygroup)

To allow certain low-levelpermissions, Android needs to mapthe permission string to the groupthat can access the functionality.For example, if an applicationrequests access to the Internet(android.permission.INTERNET),Android (after approval from theuser) will add the application tothe inet group. An applicationneeds to be a member of this groupto access the Internet. Thismapping is de ned through theplatform.xml le (found under/system/etc/platform-xml)/). High-

Page 321: Android Security - Misra, Anmol

level permissions are restricted byAndroid runtime. This is essential,as an application can be requestingmore permissions than wereauthorized by the end-user.

/system/etc/platform-xmlde nes mapping between lowerlevel system user IDs and group IDs(uid/gid) and certain permissions(see Figure 4.9).

For example, an applicationFoobar needs to access the Internetand read SMS and MMS messages.Its permission request entrieswould look like Figure 4.10.

Page 322: Android Security - Misra, Anmol
Page 323: Android Security - Misra, Anmol

Figure 4.7 adb shell pm list permissions –foutput

Page 324: Android Security - Misra, Anmol
Page 325: Android Security - Misra, Anmol

Figure 4.8 adb shell pm list permissions –soutput

Figure 4.9 Mapping ofandroid:permission.INTERNET to inet GID in/system/etc/platform.xml

Page 326: Android Security - Misra, Anmol

When this application isinstalled, Android will ask the userif he or she consents to theapplication using the abovepermissions. If the user consents,Android will look up the“android:permission.INTERNET”entry in the platform.xml les. Toaccess the Internet, an applicationneeds to be added to the inetgroup. Whenandroid.permission.INTERNETpermission is approved, Androidlooks up the corresponding GID inthe le. The application then runswith the inet GID attached to itsprocess and is, thus, able to access

Page 327: Android Security - Misra, Anmol

the Internet. Forandroid.permission.READ_SMS andandroid.permission.READ_MMS,the Android runtime permissionmanager will determine if anapplication has access to performthese operations.

On the device itself, there is noManifest XML le for anapplication. A Manifest XML le isused by developers to create anapk le. To determine thepermissions that a particularinstalled package has on thesystem, we need to review/data/system/packages.xml asshow in Figure 4.11.

Page 328: Android Security - Misra, Anmol

There are multiple instances inwhich permissions can be enforced:

Page 329: Android Security - Misra, Anmol
Page 330: Android Security - Misra, Anmol

Figure 4.10 Permissions for the ApplicationFoobar

Page 331: Android Security - Misra, Anmol
Page 332: Android Security - Misra, Anmol

Figure 4.11 Permissions for an InstalledApplication (/data/system/packages.xml)

– When an application isexecuting

– When an application executescertain functions that it is notauthorized to

– When an application starts anactivity which it is notauthorized to

– When an application sends orreceives broadcasts

– When accessing/updatingContent Providers

– When an application starts a

Page 333: Android Security - Misra, Anmol

service

4.4 Mobile Security Issues

The Android platform su ers from“traditional” security concerns, justlike any other mobile OS. Theissues discussed below are commonto all mobile platforms, not just theAndroid. Some of these issues arealso found on traditional devices(laptops), whereas some arespecific to mobile devices.

4.4.1 Device

Many of us have, at some point,lost a cellular device. Before theadvent of smartphones, it meant

Page 334: Android Security - Misra, Anmol

losing one’s contact information.On a typical (Android) smartphonetoday, however, the following istrue for most of us:

– E-mails saved on the mobiledevice

– Auto sign-in to Facebook,Twitter, YouTube, Flickr, andmore

– Bank account information– Location and GPS data– Health data

Unless the device is encrypted,the loss of a cell phone implies a

Page 335: Android Security - Misra, Anmol

potential data disclosure risk, aswell. Plug in a cellphone to acomputer, and various tools(including forensic tools) will dothe rest.

4.4.2 Patching

Android’s latest version is 3.2.However, most devices in use todayare running anything from Android1.5 to Android 2.3, with 2.2 and2.3 being the most popularreleases. Furthermore, thesedevices are updated/modi ed bythe respective manufacturers. Thus,it is di cult to apply patches in atimely manner given the lack of

Page 336: Android Security - Misra, Anmol

uniformity of the OS used.Compare this to the iPhone, whereIOS 3 and IOS 4 are the onlyversions available today.

4.4.3 External Storage

Removable external storagecompounds the data security issue.It is much easier to lose SD cardsthan to lose a cell phone. In mostcases, data is not encrypted, thusgiving very easy access to theuser’s data. SD cards also travelthrough multiple devices, thusincreasing the risk of malicioussoftware ending up on the device.Finally, removable storage is often

Page 337: Android Security - Misra, Anmol

more fragile, which can lead todata loss/corruption.

4.4.4 Keyboards

Although a very popular feature,touch screen keyboards can givegoose bumps to a securityprofessional. They provide aperfect opportunity for shouldersur ng, if you are accessingsensitive data in a train or in aco ee shop. Tablets are even worseculprits, with full-size softkeyboards and letters beingre ected back to the user inplaintext for few seconds. Smudgeson the screen may also aid an

Page 338: Android Security - Misra, Anmol

attacker.

4.4.5 Data Privacy

One of the most popularapplications on Android is GoogleMaps. Many other applications arealso interactive and can use theuser’s location information. Theycan store this information in itscache, display ads based on thisdata, or show us the nearest co eeshot. Bottom line: This data isavailable for any application thathas the right permissions. Over aperiod of time, this data can revealsensitive information about a user’shabits, essentially acting as a GPS

Page 339: Android Security - Misra, Anmol

tracking in the background.

4.4.6 Application Security

Mobile applications are stillvulnerable to the same attacks astraditional, full- edgedinformation technology (IT)applications. SQL Inject (SQLi),Cross-Site Request Forgery (XSRF),and Cross-Site Scripting (XSS) arenot only possible on mobileplatforms and applications but canlead to more serious attacks, giventhe nature of data available on amobile device. Weak Secure SocketsLayer (SSL) or lack of encryption,phishing, authentication bypass,

Page 340: Android Security - Misra, Anmol

and session xation are all issueslikely to be present in mobileapplications.

4.4.7 Legacy Code

Much of the underlying code usedby cell phones for GSM or CDMAcommunication has not changedmuch over the years. These devicedrivers were written withoutsecurity practices in mind and thusare vulnerable to old-school attacks(e.g., bu er over ows). Newdevices continue to rely on thiscode. In fact, new code is beingadded on the top of existing code.

Page 341: Android Security - Misra, Anmol

4.5 Recent Android Attacks—AWalkthrough

In the rst week of March 2011, amalware—DroidDream—hit theAndroid platform. Android is amuch more open platformcompared to iOS and, thus, has alenient marketplace policy. Googledoes not tightly controlapplications that show up in themarket. In fact, Google does noteven control all channels ofdistribution, unlike Apple. Variousways to get applications onAndroid are as follows:

– O cial Android market

Page 342: Android Security - Misra, Anmol

(Google)– Secondary Android markets

(e.g., Amazon)– Regional Android markets and

app stores (e.g., China, Korea)– Sites providing apk les to

users

Similar to other Androidmalware, such as Geinimi andHongTouTou, DroidDream was“hidden” or “obfuscated” inside alegitimate-looking application.Regular users having no reasons todistrust the Android marketdownloaded the application and

Page 343: Android Security - Misra, Anmol

ended up having an infecteddevice.

After the outbreak of thismalware, Google took anextraordinary step—the remotewiping of devices that wereinfected (approximately 50applications were considered to bemalicious). DroidDream and itsvariants gained access to sensitiveuser and device information andeven obtained root access. For acomplete list of maliciousapplications on the list, perform asearch on Google for“MYOURNET.”

Page 344: Android Security - Misra, Anmol

4.5.1 Analysis of DroidDreamVariant

The authors analyzed this malwareto determine the permissions usedby it and potential implications.After installing the malware on anemulator, we reviewed thepermissions requested by theapplication (see Figure 4.12).

Page 345: Android Security - Misra, Anmol
Page 346: Android Security - Misra, Anmol

Figure 4.12 Permissions for the MalwareDroidDream (/data/system/packages.xml)

There are three permissionsrequested by the application—READ_PHONE_STATE,SET_WALLPAPER, and INTERNET.

From the permissions requested, itappears to be a wallpaperapplication. However, it wants toaccess the phone state, as well. Anapplication having access to thispermission can access the followinginformation

Page 347: Android Security - Misra, Anmol

– IMEI number (a.k.a. Device ID)– Phone Number– Sim Serial Number– Subscriber ID (IMSI)

Below is the snippet of code thatwould enable an application toobtain sensitive phoneinformation:

After the malware has obtainedthe above device information, it

Page 348: Android Security - Misra, Anmol

can potentially send it to a remoteserver. This will be permitted, asthe malware has requested anotherimportant permission:android.permission.INTERNET

DETOUR

The International Mobile Equipment Identity(IMEI) number is a 15–17 digit number that isused to uniquely identify a mobile device on anetwork. Mobile operators use this number todisable devices that are stolen or lost.

4.5.2 Analysis of Zsone

We will now analyze a Trojannamed zsone, which wasdistributed under di erent names

Page 349: Android Security - Misra, Anmol

(iCalendar, iMatch, and others). Ithit the Android platform during thesummer of 2011 and tried to sendSMS messages without the user’spermissions. Just like DroidDream,it was pulled o of the Androidmarket.

Upon analysis of the permissionsrequested by this calendarapplication, we found that it hadaccess to the following:

Page 350: Android Security - Misra, Anmol

None of the permissions (seeFigure 4.13) requested by theapplication relate to itsfunctionality—that is, a calendarapplication. Essentially, the abilityto send and receive SMS, providelocation based on CELL-ID or Wi-FI, and read the phone state allpoint to a malicious application.Below is a snippet of code thatdemonstrates the applicationsending an SMS message withoutuser intervention:

4.5.3 Analysis of Zitmo Trojan

Page 351: Android Security - Misra, Anmol

Most of the leading banks todayo er mobile banking applications.Initially, banks used simple one-factor authentication (usernameand password) to allow users to logon to the bank’s mobile site andview nancial information. Since itis easier to defeat this form ofauthentication (crackingpasswords, MITM, socialengineering), banks have started torely on two-factor authentication.In addition to the passwords, theywill usually send an SMS message(a ve-to-six digit one-time PIN) tothe user’s cell phone device andrequire this as part of the overall

Page 352: Android Security - Misra, Anmol

authentication process.The Zitmo Trojan on Android

aims to defeat this mechanism byintercepting SMS messages that aresent by banks to its customers. Thisworm was rst discovered forSymbian (Nokia) devices inSeptember 2010. Now, it isavailable for Android, as well.Trojan essentially aids the Zeuscrime kit. The Zeus kit is installedwhen an unsuspecting user visits amalicious site. Installation of theZeus kit enables attackers to stealcredentials—one part of the two-factor authentication. InstallingZitmo provides them with the

Page 353: Android Security - Misra, Anmol

second—TAN messages from thebank.

Page 354: Android Security - Misra, Anmol
Page 355: Android Security - Misra, Anmol

Figure 4.13 Permissions for the Malware zsone(/data/system/packages.xml)

Figure 4.14 Zitmo Malware Application onAndroid

The malware application itselfdisguises itself as “Trusteer

Page 356: Android Security - Misra, Anmol

Rapport” (see Figure 4.14. It getsinstalled as a“com.systemsecurity6.gms”application—a name that makes itdi cult to identify it as malwarefor a normal user.

Figure 4.15 shows the outputfrom the ps command. The Zitmomalware runs as“com.systemsecurity6.gms.”

Zitmo requests the followingpermissions (see Figure 4.16):

READ_PHONE_STATE gives it

Page 357: Android Security - Misra, Anmol

access to the IMEI number, SIMcard number. and other uniquephone data. RECEIVE_SMS allowsit to intercept TAN numbers sent bybank websites. Once it hasintercepted TAN numbers, it sendsthis to the Command and Control(C&C) Center because it also hasINTERNET permission.

4.6 Summary

In this chapter, we covered thekernel and application layers ofthe Android Security Model. Thereader should now have anunderstanding of how Android usesthe Linux kernel to enforce the

Page 358: Android Security - Misra, Anmol

permission-based security model.We walked through Manifestpermissions and demonstrated whythese are important for anapplication from a securityperspective. We reviewed thesecurity landscape for mobiledevices, including those runningthe Android OS. Finally, weanalyzed malicious applicationsand demonstrated how one canstart analyzing them based onpermissions requested.

Page 359: Android Security - Misra, Anmol

Figure 4.15 ps Command Output (with Zitmorunning)

Page 360: Android Security - Misra, Anmol
Page 361: Android Security - Misra, Anmol

Figure 4.16 Zitmo Permissions

Page 362: Android Security - Misra, Anmol

Chapter 5Pen Testing Android

In this chapter, we focus on pentesting the Android platform andapplications. We start by coveringpenetration methodology,discussing how to obtain details onthe Android operating system. Wethen turn to pen testing Androidapplications and discuss securityfor Android applications. Towardsthe end, we talk about relativelynewer issues (including storage onclouds) and patching. Finally, weshowcase recent security issues for

Page 363: Android Security - Misra, Anmol

Android applications.The reader should now be

familiar with Android architecture(covered in Chapter 2), Androidapplication basics (building blocks,frameworks; covered in Chapter 3),and Android permissions andsecurity models (covered inChapter 4).

5.1 Penetration TestingMethodology

A penetration test (also pen test) isa method of evaluating the securityof systems by simulating an attackfrom malicious insiders oroutsiders. The goal is to discover

Page 364: Android Security - Misra, Anmol

issues before they are discovered byattackers with malicious intentsand to x them. Testing oftenhappens just before a product isreleased, to ensure security, orafter it has been out, and to ensurethat no vulnerabilities have beenintroduced. Source code review orstatic analysis compliments a pentest. A static analysis ideally shouldbe performed before a pen test andshould be a component of theSoftware Development Life Cycle(SDLC) cycle. If a static analysis isperformed before the pen test and

ndings from it are remediedbeforeproduct development is complete, a

Page 365: Android Security - Misra, Anmol

pen test will result in relativelyfewer ndings. This allows for arelatively cleaner pen test reportthat can be shared with customers,if needed, thereby providing themwith an assurance of security forthe product.

Pen tests can be classi ed intotwo categories—internal andexternal—depending on thevantage point of the simulatedtests. Below are overviews ofinternal and external pen tests,guidelines for conducting pen tests,a static analysis, and steps tofollow in pen testing an AndroidOS and devices.

Page 366: Android Security - Misra, Anmol

5.1.1 External Penetration Test

External pen tests are performedby security professionals outsidethe network who are only providedwith limited information.Enterprise networks are protectedby a multitude of rewalls withAccess Control Lists (ACL) thatblock o most of the ports that canbe accessed from the outside. In anexternal pen test, the onlyinformation security professionalsare given are URLs or IP addresses.Many of the tools/techniques usedby security professionals forexternal pen tests will encounter

rewalls, and these rewalls will

Page 367: Android Security - Misra, Anmol

usually prevent them from probingthe internal networks. Thisprevents them from identifyingvulnerabilities that exist but areprotected by rewalls or otherdefenses.

For example, a rooted Androiddevice is running a service on port850. Firewalls are usuallycon gured so as not to allowprobes to this port (and thusprotects services running on thisport). Thus, a pen test from theoutside will not detect a servicerunning on this port. However, if arooted Android device is anrunning httpd server on port 80, it

Page 368: Android Security - Misra, Anmol

is more likely to be discovered byan external pen test, since port 80is usually accessible through afirewall.

5.1.2 Internal Penetration Test

Internal pen test are not hinderedby rewalls (although they mightbe, if there is tiered architecture),and it is, therefore, easier to obtaininformation on internal systems(systems that have private IPs,etc.).

Continuing our example of arooted Android device runningservice on port 850, in an internalpen test, security professionals are

Page 369: Android Security - Misra, Anmol

more likely to discover this port(and service), as it probably won’tbe blocked by a rewall. If aservice is communicating withother devices, it can be probed.

The rule of thumb is that aninternal penetration test willhighlight more issues compared toan external penetration test.External penetration tests rely onthe fact that attackers can’t accessdevices in the network. However, itdoes not mean that issues ininternal pen tests are of lessseverity. Insiders can still exploitthese issues. In addition, attackersfrom the outside might be able to

Page 370: Android Security - Misra, Anmol

exploit these issues as part oflarger attacks, where they can, infact, get inside the network.

5.1.3 Penetration TestMethodologies

Peer-reviewed methodologies forperforming pen tests step by stepexist. NIST 800-115 and OSSTMMare two such guidelines. The idea isnot to follow them every step ofthe way, but to use them asguidelines and modify them asneeded in conducting a pen test.

A typical pen test can be broadlydivided into the following fourstages:

Page 371: Android Security - Misra, Anmol

1. Planning: Identify goals for theexercise and obtain approvalsand logistics.

2 . Discovery: Obtain informationon target(s). Informationincludes IP addresses, contactinformation, systeminformation (OS versions),applications, and databases,etc.

3. Attacks: Based on informationdiscovered in Stage 2, identifyany systems, applications, anddatabases that are vulnerableand validate thesevulnerabilities. If necessary,loop back into the discovery

Page 372: Android Security - Misra, Anmol

phase.4 . Reporting: Based on this

assessment, categorize issuesby severity—critical, high,medium, and low—andprovide this analysis tomanagement, along withrecommendations.

5.1.4 Static Analysis

Although not part of penetrationtesting, static analysis is animportant tool for securityprofessionals. It helps to identifysoftware code–related issues earlyin the development cycle (or if theproduct has been released, later

Page 373: Android Security - Misra, Anmol

during security assessments). Astatic analysis tool is executedagainst a code base. Tools usealgorithms to analyze various codepaths and ow and provide a listof potential security issues. There isoften some percentage of falsepositives. The beauty of the staticanalysis is that developers can useit without any outside help andunderstand/improve their codingpractices to prevent such issues inthe future.

As far as Android is concerned,we can analyze security at twodi erent layers (skipping thehardware layers, which is the focus

Page 374: Android Security - Misra, Anmol

of another book): operatingsystems (OS) and applications.

5.1.5 Steps to Pen Test AndroidOS and Devices

For most Android devices runningin an environment, one of themajor issues can arise if it isrooted. Rooted devices are more atrisk, since a user would be runningwith elevated privileges, andattackers can leverage this tocompromise the device. Inaddition, it is useful to analyzeissues in the OS stack itself(although this requires access to thesource code of the kernel, libraries,

Page 375: Android Security - Misra, Anmol

etc.). A mix of black box and whitebox testing is usually the bestapproach, wherein securityprofessionals have access to deviceson the network and they can probefurther if they sense suspiciousactivities on the device.

1. Obtain the IP address of theAndroid device(s).

2. Run an NMAP scan to see theservices that are running onthose devices.

3. For suspicious devices (e.g.,rooted devices), capture andanalyze packets throughWireshark.

Page 376: Android Security - Misra, Anmol

4. If device is deemedcompromised, use utilities likebusybox to explore deviceinternals (which processes arerunning, etc.) and forforensics.

5. Perform a static analysis ofthe source code of the librariesand OS. Speci cally look forcodes contributed by vendorssuch as HTC. Code should bereviewed for the followingtype of issues: resource leaks,null pointer references, illegalaccess operations, and control

ow issues, which canpotentially bypass security

Page 377: Android Security - Misra, Anmol

checks.6. Review con guration les and

code for plain text passwordsand other sensitive data that isbeing stored withoutappropriate securityconsiderations.

5.2 Tools for Penetration TestingAndroid

Android comes with limited shell,and there might be times whensecurity professionals need accessto more information than providedby the Android OS (by design).There are di erent tools that canbe leveraged for this purpose.

Page 378: Android Security - Misra, Anmol

Nmap—network scanner;Wireshark—network sni er; andBusyBox—a collection of commandline tools (e.g., ifcon g) are amongsome of the most useful tools.

5.2.1 Nmap

Assuming you don’t have access tothe device itself, but are looking onthe network for Android devices,Nmap scans can help. The Nmapscan launches a SYN (synchronize)scan against the IP and looks forOS ngerprinting and versiondetection (see Figure 5.1). Our scanresults showed no open ports

Page 379: Android Security - Misra, Anmol

Figure 5.1 Nmap SYN Scan against an AndroidDevice

(services) and, therefore, did notprovide very useful informationregarding the Android device. Ifany of the ports were open, wemight have wanted to explore it a

Page 380: Android Security - Misra, Anmol

bit further.

5.2.2 BusyBox

Android comes with limited shellutilities. The BusyBox packageprovides many commonly foundUNIX utilities for Android. Thesecan become handy during learning,exploring, pen testing, andforensics on an Android device.Since it runs on Android, utilitiesmight not support all options, suchas the ones on desktop versions.

Below are instructions forinstalling and running BusyBox onan emulator (see Figure 5.2). Foran Android device, you will need to

Page 381: Android Security - Misra, Anmol

root it to be able to install thispackage and make it runsuccessfully.

From the terminal inside theLinux system, launch adb shell andperform the following (assumingyou have binary handy):

Page 382: Android Security - Misra, Anmol

Figure 5.2 ifconfig Command After InstallingBusyBox

At this point, utilities should befound in the /data/busyboxdirectory. Change that directory (orupdate the PATH variable), andyou can start using common UNIXcommands.

Page 383: Android Security - Misra, Anmol

Figure 5.3 netstat Command After InstallingBusyBox

Page 384: Android Security - Misra, Anmol

Figure 5.4 Open Ports through pscan

As is visible from the output ofthe ifcon g command (Figure 5.2),the emulator’s IP address is10.0.2.15—a special IP addressreserved for the emulator. If yourdevice was on a network, youmight see something like192.168.0.104 IP. 10.0.2.2 IP is thealias for the 127.0.0.1 loop backaddress on the development system(i.e., the system running theemulator). 10.0.2.1 is therouter/gateway, and 10.0.2.3 is thefirst DNS server.

As can be seen from the

Page 385: Android Security - Misra, Anmol

screenshots (Figures 5.3 and 5.4),port 80 is open (httpd was runningon the device). On a typicalAndroid device, this would requirefurther exploration.

5.2.3 Wireshark

If you would like to analyze tra cfrom an Android device, you willprobably need to root the device(to use something like Wiresharkon the device) or you will needaccess to a router. In our case, weare running tcpdump (installed ona Linux system) and capturingtra c in an emulator. We can thenopen the le in Wireshark, as

Page 386: Android Security - Misra, Anmol

shown in Figure 5.5.To launch tcpdump and capture

tra c from the emulator on adevelopment machine, you can use:emulator –tcpdump <output le>-avd <avd device name>

The tra c shown in Figure 5.5was captured during a web browserrequest to open www.google.com.As can be seen from the Wiresharklisting, the DNS server is 10.0.2.3and the router/gateway is 10.0.2.2.The source 10.0.2.15 (emulator)sends a HTTP GET request towww.google.com (see Figure 5.6).

5.2.4 Vulnerabilities in the

Page 387: Android Security - Misra, Anmol

Android OS

The Android OS is based on theLinux OS, which is at its core. It isopen source, and, thus, people arefree to develop and contribute/re-use code. Google has an o cialAndroid team that is responsiblefor the Vanilla Android OS.However, since it is open sourceand free, everyone is free to checkout code, modify, and ship thesoftware. Di erent vendors—HTC,Samsung, etc.—seem to modify theOS per their needs, although thedevice is still said to run “Android.”

Page 388: Android Security - Misra, Anmol
Page 389: Android Security - Misra, Anmol

Figure 5.5 tcpdump Output in Wireshark

Page 390: Android Security - Misra, Anmol
Page 391: Android Security - Misra, Anmol

Figure 5.6 HTTP GET Request in Wireshark

Before we explore the types ofissues that can be found in theAndroid OS, it might be worthwhileto wonder who is ultimatelyresponsible for these issues? Is itGoogle (since they are ones whohave ownership of Android o cialreleases) or is it the vendors, suchas HTC, who take the Vanilla OSand make modifications?

We can even go beyond this.Android OS leverages driverscontributed to Linux. These driversmight be used without anyconsideration for their security

Page 392: Android Security - Misra, Anmol

implications. In addition, manydrivers might have old code, withnew code being added on top of it.Security issues at any of the lowerlayers lacks clear accountability.

Typical issues found in C/C++code and potentially found in theAndroid OS would be in resourceleaks, memory corruption, control

ow issues, dataaccess violations,and pointer references. Often, deadcode (code written but not used byany code ow path) will beencountered, and it should bepointed out to the users.

5.3 Penetration Testing—

Page 393: Android Security - Misra, Anmol

Android Applications

Most of the pen testing e ortsdescribed on Android will befocused on applications—both builtin (e.g., browser, maps) and third-party applications (found on theAndroid Market).

5.3.1 Android Applications

Penetration testing for an Androidapplication is like testing any othersoftware on a platform. Things toconsider while pen testing anAndroid application include attacksurface, interactions with othercomponents (internally and

Page 394: Android Security - Misra, Anmol

externally), communications, andstorage.

Attack Surface: Every pen testfocuses at the core on thefunctionality of an application.Depending on the functions andfeatures provided by anapplication, the e orts of the pentester are on items that arerelevant and critical (e.g.,authentication, data, etc.), andtests are performed on relevantunderlying components. Localcomponents not handling criticaldata should be tested di erently(and less time should be spent onthem, compared to components

Page 395: Android Security - Misra, Anmol

interacting with outsideapplications/systems).

Interactions with OtherComponents: An applicationinteracts with other Androidapplications and outside serversthrough various InterprocessCommunication (IPC) mechanisms.These include socket-basedcommunications, Remote ProcedureCalls (RPC), passing/receivingbroadcasts, Intents, and otherAndroid-speci c IPC interactions.Many of these communications arepossible through permissions, and,thus, it is paramount to look at thefollowing:

Page 396: Android Security - Misra, Anmol

– Permissions and applicationrequests

– Functionality that anapplication exposes to otherAndroid applications

The reader should be familiarwith Android permissions (coveredi n Chapter 4). Permissions arede ned in the Manifest.xml le. Atester will need to decompile theAPK le to access this le andreview it. Steps for decompiling theAPK le and obtaining theManifest.XML le are shownFigures 5.7 and 5.8.

APK les are bundles of various

Page 397: Android Security - Misra, Anmol

les. These include META-INF, res,AndroidManifes.XML, classes.dex,and resources.arsc les/directories.Apktool can be used to extract theAndroidManifest.XML from an apk

le. Usage: apktool decode<apkname> <directory>

For Android-speci c components(Intents, Broadcast Receivers), thetester needs to at least ensure thefollowing:

1. Sensitive data is not beingpassed for IPCcommunications (e.g., inIntents, broadcasts, etc.).

2. Intent lters are not being

Page 398: Android Security - Misra, Anmol

used for security purposes.Although Intent lters cancontrol which Intents areprocessed by an application,this only applies to implicitIntents. An application canalways force the processing ofan Intent by creating anexplicit Intent.

3. Sticky broadcasts are notbeing used when sensitivedata is transmitted, since theapplication cannot controlwho receives these broadcasts.

Page 399: Android Security - Misra, Anmol

Figure 5.7 Extracting Manifest Permissions Filesthrough apktool

Page 400: Android Security - Misra, Anmol
Page 401: Android Security - Misra, Anmol

Figure 5.8 Example of a Manifest PermissionFile Extracted from apk

4. Permissions requested by theapplications are not morethan ones needed forapplication functionality—that is, the principle of leastprivilege is being applied.

Communications: It is important todetermine if communications of theapplication with outsidesystems/servers is over a securechannel. Connections should beencrypted. It is also important toreview how servers/systems arechosen for communication.

Page 402: Android Security - Misra, Anmol

Data: At the core of everyapplication assessment is the datahandled by that application.Typical applications canread/write data in the form of lesor databases. Both of these can bemade readable by the applicationonly or by the outside world. Whensensitive data is being handled byan application, it is prudent toreview its le and databaseoperations for permissions. A testershould also review the applicationlogs and shared preferences to seeif there is data being inadvertentlyexposed. Most of the applicationscommunicate with the external

Page 403: Android Security - Misra, Anmol

environment (or the Web), and alot of data is stored on remoteservers/databases. The testershould review data beingtransmitted and stored on o siteservers/applications. Another thingto review is how sensitiveparameters are beingpassed/stored (e.g., credentials).

Proper Use of Cryptography: Thetester should look at the standardcryptographic practices of anapplication. For example, is theapplication checking preapprovedpublic keys during the certi catecheck process? How does the

Page 404: Android Security - Misra, Anmol

application validate certi cates?Does the application do strictcertificate checks?

Passing Information (includingparameters) to Browsers: The testershould see if the application isopening a browser application,and, if so, how it is passing thenecessary parameters (i.e., throughGET or POST requests).

Miscellaneous: Applications can bereviewed for services running inthe background to see their impacton resources. There are a fewadditional steps that are needed as

Page 405: Android Security - Misra, Anmol

part of pen testing an Androidapplication. Since Androidapplications are coded in Java, it isessential to review Java code fortypical vulnerabilities. If anapplication is relying onunderlying native code or libraries,it would be prudent to validatevulnerabilities in the native code,as well. Finally, it is important toreview how an application ishandling storage (covered later).

To review an application’scommunication with the outsideworld, you will need to set up aproxy to intercept tra c between

Page 406: Android Security - Misra, Anmol

the application and the Web. Thiscan be done as follows:

Figure 5.9 Setting up a Proxy on an AndroidDevice

Page 407: Android Security - Misra, Anmol

Intercepting traffic for browser(HTTP) applications:

1. Download and install proxy(e.g., Burp Suite) on thehost/development system.Turn on the “intercept”option.

2. Set up a proxy from theAndroid phone/emulator (seeFigure 5.9). In our example,we are using an emulator.Thus, we will need to use a“10.0.2.2” IP address as theproxy.

3. Open the browser on Androidand type a URL.

Page 408: Android Security - Misra, Anmol

4. Review captured tra cthrough the Burp Suite (seeFigures 5.10 and 5.11).

Intercepting traffic for otherapplications:

1. Start the application (in ourcase, we chose the InternetRelay Chat (IRC) applicationYaaic) (see Figure 5.12).

Page 409: Android Security - Misra, Anmol
Page 410: Android Security - Misra, Anmol

Figure 5.10 Intercept of Android BrowserCommunication through Burp

Page 411: Android Security - Misra, Anmol
Page 412: Android Security - Misra, Anmol

Figure 5.11 Credentials in Plain Text (URL)Captured through Burp

Figure 5.12 Yaaic Application on Android

2. Capture tra c throughWireshark and lter by the

Page 413: Android Security - Misra, Anmol

phone’s IP address (in ourcase, 192.168.0.107).

3. Review captured tra cthrough various options inWireshark (see Figures 5.13(a)M and (b).

5.3.2 Application Security

We covered pen-testing steps forAndroid-speci c issues. In additionto these, any Android applicationneeds to be analyzed (and codereviewed) for usual security awsin the code and the design. Theseissues can be broadly classi ed, asshown in Table 5.1:

Page 414: Android Security - Misra, Anmol

Issues need to be mapped byseverity (critical, high, medium,and low) and level of di culty inexploiting them (high, medium,and low). The following is asummary of some of theclassi cation categories outlined inTable 5.1:

1. Authentication Issues: Validatesthat user credentials are notbeing transmitted overunencrypted channel and ifauthentication mechanismsare in alignment withstandard practices.

Page 415: Android Security - Misra, Anmol

Figure 5.13 (a) Packet Capture of YaaicCommunication through Wireshark; (b) Analysisof Packets Captured through Wireshark

2. Access Controls: Validates thatauthenticated users can only

Page 416: Android Security - Misra, Anmol

access resources andfunctionality in line with theircredentials and that they arenot able to bypass accesscontrols.

3. Logs: Validates that logs do notcontain sensitive information,and that logs are notaccessible by unnecessaryapplications and that theyhave appropriate permissions.

4 . Cryptography: Validates thatsensitive communicationsoccur only over securechannels and that strongciphers are used for thiscommunication. Validate that

Page 417: Android Security - Misra, Anmol

there are no proprietycryptographic protocols beingused in the application.

5 . Data Leakage: Validates thatthe application is notaccidently exposing data thatotherwise should not beavailable to other applicationsthrough logs, IPC calls, URLcalls, files, and so forth.

6 . Data Validation: Validates thatthe application does not useinput from untrusted sourcesdirectly into SQL queries andother sensitive operations.

Page 418: Android Security - Misra, Anmol
Page 419: Android Security - Misra, Anmol

Figure 5.13(b)

Table 5.1 – Application SecurityIssues

Security Issue Description

AuthenticationIssues related touser identification

Access ControlIssues related touser rights afterauthentication

Auditing andLogging

Issues related tologs and auditing

Issues related to

Page 420: Android Security - Misra, Anmol

Cryptographyencryption andsecuringcommunications

CredentialHandling

Issues related tothe handling ofuser passwordsand othercredentials

Data Handling

Issues related tothe handling ofdata vis-à-vis itssensitivity

Page 421: Android Security - Misra, Anmol

Data Leakage

Issues related toaccidental orunintendedleakage ofinformation

ErrorChecking

Issues related toreporting errorswithout providingtoo much data

InputValidation

Issues related tovalidatinguntrusted user

Page 422: Android Security - Misra, Anmol

input

SessionManagement

Issues related tobest practices foruser sessionmanagement

ResourceHandling

Issues related tothe handling ofresources,including memory

Patching

Issues related totimelypatching/upgrade

Page 423: Android Security - Misra, Anmol

of software

7 . Error Reporting: Validates thatwhen an application throwsan error, it does not log andreport the entire stack trackand does not contain sensitiveinformation.

8. Session Management: Validatesthat the application followsbest practices for sessionmanagement, including timeout, session identi ers, tokenuse, and so forth.

9 . URL Parameters: Ensures thatthe application does not passsensitive parameters to URLs

Page 424: Android Security - Misra, Anmol

in plain text.1 0 . Predictable Resources:

Validates that an applicationis not generatingtokens/identi ers that can beeasily guessed.

Pen Testing should provide anapplication benchmark againstthe following best practices:

1. Timely patching libraries andapplications as vulnerabilitiesare identified.

2. Sensitive information (e.g.,SSN) is not passed as aparameter through a URL.

Page 425: Android Security - Misra, Anmol

Information in a URL isaccessed through the GETrequest, and this can belogged at multiple places. APOST request solves thisproblem. However, althoughinformation through a POSTrequest is not visible in a URL,a POST request can still revealthis information in therequest-header. For trulysensitive information, oneshould always use an HTTPSconnection.

3. Brute force attacks are notpossible due to a limitednumber of attempts to

Page 426: Android Security - Misra, Anmol

authenticate.4. A Secure Sockets Layer (SSL) is

used pervasively to requestresources.

5. Session identi ers are not sentin URLs.

6. Tokens are not easilyguessable.

7. Password complexity isenforced.

8. Log les do not containsensitive information and areprotected appropriately.

9. Files are encrypted on localand external storage.

Page 427: Android Security - Misra, Anmol

10. Proper data validation isperformed to prevent XSS,SQLi, command injection, etc.

Code review of an Androidapplication can identify thefollowing issues:

1 . Command Injection: Attackercan in uence which commandis executed or the environmentin which it is executed, thusbypassing security controls.Typical examples include userinput being used in SQL queryconstructed to query SQLiteDBs.

Page 428: Android Security - Misra, Anmol

2 . Resource Leaks: Applicationdoes not relinquish resourcesafter being used (e.g., lehandling, etc.). This can resultin performance issues but canalso be available for malicioususers/applications.

3. Error Handling: An applicationdoes not take in to accountstructure/ ow on a particularerror and thus does notperform allhousekeeping/access controlchecks needed if a particularcode path is executed.

4 . Unsafe Java Native Interface(JNI) Calls: Since Android

Page 429: Android Security - Misra, Anmol

applications can call nativecode written in C through JNI,this exposes applications tounderlying issues in the nativecode.

5.4 Miscellaneous Issues

5.4.1 Data Storage on Internal,External, and Cloud

There are various locationsavailable for Android applicationdata storage, including les,databases, preferences, and cache.Data can be stored in the internalmemory or on an external card. Ifdata is stored in plain text and the

Page 430: Android Security - Misra, Anmol

device is compromised or stolen,data will be exposed. It is usually abest practice to encrypt data that isbeing stored. The application needsto ensure that a strong encryptionalgorithm is being used to do this.In-house encryption is usually isthe weakest compared to publiclyavailable encryption tools.

A pen tester needs to review thefollowing locations for data storage—local: les, SQLite DBs, cache,and preferences; and external:files, cloud.

Code review can help identifyplaces where le/data storageoccurs. Typical operations that

Page 431: Android Security - Misra, Anmol

need to be reviewed include theopening/creating of les, accessingthe directory and its contents,accessing cache/preferences,opening/creating a database, andso forth.

5.5 Summary

This chapter introduced the readerto penetration testing on Android.We covered how to pen test theAndroid OS. We also discussedapplication security, pen testingAndroid applications, and staticanalysis. We analyzed recentsecurity issues with Androidapplications.

Page 432: Android Security - Misra, Anmol

We suggest that the readerdownload a few open-sourceapplications for Android or writeone and then try out the techniquesdescribed in this chapter. Theauthors also have an applicationon their website that the user canexperiment with.

Page 433: Android Security - Misra, Anmol

Chapter 6Reverse EngineeringAndroid Applications

In this chapter, we will covermalware basics—how to identifymalware, malware behavior, andmalware features. We will thendiscuss a custom Android BOTapplication created by the authorsand demonstrate to the reader howpotential malware can bypassAndroid built-in checks.

The Android BOT walkthroughwill include stealing a user’s

Page 434: Android Security - Misra, Anmol

browser history and Short MessageService (SMS) as well as call logs,and it attempts to drain thephone’s battery. We will alsopresent a sample application toshow the readers how to reverseengineer or analyze maliciousapplications. After completing thischapter, the reader will be able towrite Android BOT in Java. Thereader will also become familiarwith reverse engineering tools andwill be able to decompile anyAndroid application.

6.1 Introduction

Reverse engineering is the process

Page 435: Android Security - Misra, Anmol

of discovering the technologicalprinciples of a device, object, orsystem through analysis of itsstructure, function, and operation(http://en.wikipedia.org/wiki/Reverse_engineeringIt often involves taking something(e.g., a mechanical device,electronic component, softwareprogram, or biological, chemical,or organic matter) apart andanalyzing its workings in detail tobe used in maintenance, or to tryto make a new device or programthat does the same thing withoutusing or simply duplicating(without understanding) theoriginal.

Page 436: Android Security - Misra, Anmol

The typical user todaydownloads or buys software andinstalls it without thinking muchabout its functionality. A few linesof description and some reviewsmight be enough to persuade theuser to try it. Except for well-known software (written bysoftware companies such asMicrosoft or Apple) or through theopen-source community, it can bedi cult to verify the authenticityof available software or vouch forits functionality. Shareware/trial-ware/free software is available forpersonal computers (PCs) and isnow available for mobile devices,

Page 437: Android Security - Misra, Anmol

as well, and only requires one clickto install it. Hundreds of softwareapplications pop up everyday inthe marketplace from seasoned tonewbie developers.

The problem is compounded formobile devices, especially Android.With no rigorous security review(or gate) on multiple Androidmarketplaces, there are manyopportunities for malicioussoftware to be installed on adevice. The only gate seems to beduring the install process, when theuser is asked to approve requestedpermissions. After that, the user’strust in an application is complete.

Page 438: Android Security - Misra, Anmol

Users, therefore, don’t understandthe full implications of the utilitiesand software that they install ontheir devices. Given the complexityand interdependencies of softwareinstalled, it can become confusingeven for seasoned professionals to

gure out if a software package istrustworthy. At these times, theneed for reverse engineeringbecomes crucial.

Reverse engineering comprises aset of techniques that can identifyhow software is going to behave.Often this process can becompleted without access to thesource code.

Page 439: Android Security - Misra, Anmol

Reverse engineering is useful forthe security analysis of software forthe following purposes:

1 . Identifying malicioussoftware/code: Securitycompanies use reverseengineering techniques toidentify how a particular pieceof malware (virus, worm, etc.)behaves and develop asolution to counter it. Reverseengineering can also aid inthe development of heuristicsthat can identify futuremalicious software behaviorbefore it can impact users.

Page 440: Android Security - Misra, Anmol

2 . Discovering aws/securityissues: Reverse engineering isone of the last techniques usedby security professionals tovalidate that software doesnot have aws/issues that canbe exploited. For example,reverse engineering can helpidentify if an application isproviding a lot of usefulinformation to an attacker orhas predictable data in thestack/heap.

3 . Identifying unintendedfunctionality in software:Reverse engineering might beused by developers of

Page 441: Android Security - Misra, Anmol

particular software to identifyif there are potentiallyunintended consequences ofits functionality, and if so,they can take appropriatemeasures to mitigate them.

Reverse engineering has beenaround for a long time—competitors trying to reverseengineer popular products, thegovernment trying to reverseengineer defense technologies oftheir opponents, mathematicianstrying to reverse engineer ciphers.However, we would like to notethat this chapter is not about

Page 442: Android Security - Misra, Anmol

reverse engineering Androidapplications for any purpose.

It is illegal to reverse engineersoftware applications. It infringeson the copyrights of developersand companies. It is punishable bylaw, including copyright laws anddigital rights acts. Our sole purposein demonstrating techniques in thischapter is to decipher and analyzemalicious software. We provideguidelines on how potentiallymalicious software can be reviewedand di erentiated from legitimatesoftware/downloads.

Android has some useful toolsthat are available for aiding the

Page 443: Android Security - Misra, Anmol

reverse engineering process. Wehave covered some of them inprevious chapters, and we willcover some of them here. We willnow walk the reader through theprocess of analyzing an application(using reverse engineeringtechniques) for malicious behavior.The application used here has beendeveloped for demonstrationpurposes only by the authors of thisbook.

6.2 What is Malware?

Malware (or malicious software) issoftware code designed to disruptregular operations and collect

Page 444: Android Security - Misra, Anmol

sensitive and/or unauthorizedinformation from a system/user.Malware can include viruses,worms, Trojans, spyware, keyloggers, adware, rootkits, andother malicious code.

The following behavior cantypically be classified as malware:

1 . Disrupting regular operations:This type of software istypically designed to preventsystems from being used asdesired. Behavior can includegobbling up all systemresources (e.g., disk space,memory, CPU cycles), placing

Page 445: Android Security - Misra, Anmol

large amounts of tra c on thenetwork to consume thebandwidth, and so forth.

2 . Collecting sensitive informationwithout consent: This type ofmalicious code tries to stealvaluable (sensitive)information—for example,key loggers. A key loggertracks the user’s keys andprovides them to the attacker.When the user inputs sensitiveinformation (e.g., SSN, creditcard numbers, andpasswords), these can allpotentially be logged and sentto an attacker.

Page 446: Android Security - Misra, Anmol

3 . Performing operations on thesystem without the user’sconsent: This type of softwareperforms operations onsystems/other applications,which it is not intended to do—for example, a wallpaperapplication trying to readsensitive les from a bankingapplication or modifying lesso that other applications areimpacted.

6.3 Identifying Android Malware

Our focus here is to identifybehavior that can be classi ed asmalware on Android devices. As we

Page 447: Android Security - Misra, Anmol

have seen, this can be at the OSlevel (Android/Linux kernel) or atthe application level. The questionhere is, how do we detectsuspicious applications on Androidand analyze them? Themethodology we propose will helpsecurity professionals identifysuspicious behavior and evaluateapplications. Below is ourmethodology, followed by a casestudy using a malicious applicationwritten by the authors:

1. Source/FunctionalityThis is the rst step inidentifying a potentially

Page 448: Android Security - Misra, Anmol

suspicious application. If it isavailable on a non-standardsource (e.g., a website insteadof the Android Market), it isprudent to analyze thefunctionality of theapplication. In many cases, itmight be too late if the useralready installed it on amobile device. In any case, itis important to note thesupposed functionality of anapplication, which can beanalyzed through Steps 2 to 4.

2. PermissionsNow that you have analyzedand you understand the

Page 449: Android Security - Misra, Anmol

expected behavior of theapplication, it is time toreview the permissionsrequested by the application.They should align with thepermissions needed to performexpected operations. If anapplication is asking for morepermissions than it should forproviding functionality, it is acandidate for furtherevaluation.

3. DataBased on the permissionsrequested, it is possible todraw a matrix of dataelements that it can have

Page 450: Android Security - Misra, Anmol

access to. Does it align withthe expected behavior? Wouldthe application have access todata not needed for itsoperations?

4. ConnectivityThe nal step in ourmethodology is to analyze theapplication code itself(covered later). The reviewerneeds to determine if theapplication is opening sockets(and to which servers),ascertain what type of data isbeing transmitted (and ifsecurely), and see if it is usingany advertising libraries, and

Page 451: Android Security - Misra, Anmol

so forth.

6.4 Reverse EngineeringMethodology for AndroidApplications

In the previous section, wedescribed the methodology forassessing suspicious Androidapplications. In this section, weapply this methodology to analyzea wallpaper application developedby the authors.

Step 1: Review source andfunctionality of the application

The application is available for

Page 452: Android Security - Misra, Anmol

download from the authors’website(www.androidinsecurity.com) orfrom the Android Market. If thisapplication was available onlyfrom a non-standard source (e.g.,webpage), then it would de nitelymerit further review. Uponinstalling the application on anemulator, it seems like an o -the-shelf wallpaper application (seeFigures 6.1 and 6.2).

Step 2: Review permissions usedby the application

We covered Android permissions in

Page 453: Android Security - Misra, Anmol

Chapter 4 and how to access theManifest.xml le (which has thepermissions listing) in Chapter 5.Using the apktool on the CutePuppies Wallpaper applicationdeveloped by the authors, we canaccess the list of permissionsrequested by this application (seeFigures 6.3 and 6.4).

As is evident from Figure 6.4, theapplication seems to be requestingtoo many permissions. Table 6.1summarizes the permissionsrequested, their uses on theAndroid device, and if they arerequired for a wallpaperapplication. The application is

Page 454: Android Security - Misra, Anmol

requesting far too manypermissions than are needed.

Figure 6.1 Installing the Wallpaper Applicationthrough the Command Line

Page 455: Android Security - Misra, Anmol

Figure 6.2 Application Screenshots

Step 3: Review InterprocessCommunication (IPC)mechanisms used by theapplicationNext we analyze the IPC

Page 456: Android Security - Misra, Anmol

mechanisms used by theapplication (see Figure 6.5). Welook for Intents and Intent filters inthe AndroidManifest le. We alsoanalyze components associatedwith these Intents (e.g., service,receiver, activity, etc.). Table 6.2shows the IPC mechanisms de nedby the application and our analysisof them.

Figure 6.3 Extracting AndroidManifest.XML

Page 457: Android Security - Misra, Anmol

through apktool

Figure 6.4 Permissions Listed inAndroidManifest for Wallpaper Application

Step 4: Analyze code to reviewopen ports, datashared/transmitted, socketconnections, and so forth

Decompiling APK to obtain Javacode

Page 458: Android Security - Misra, Anmol

Finally, we decompile theapplication code into readableJava code. We then review thecode to gain insight into theapplication’s behavior. TheAndroid Package les (APK) is acompressed le that contains theclasses.dex le, among otherthings. APK les can be easilydecompressed, and classes.dex lecan be extracted. DEX is Java ByteCode for Dalvik Virtual Machine. Itis optimized for running on smalldevices. The dex2jar utility(available fromhttp://code.google.com/p/dex2jar/downloads/listallows us to convert classes.dex

Page 459: Android Security - Misra, Anmol

les into jar les (see Figure 6.6).The resulting jar les can beviewed in a Java decompiler (e.g.,JD) (see Figure 6.7).

Analyze code for open ports, datashared/transmitted, and opensockets

We now analyze jar les in a Javade-compiler. As shown in Figure6.7, opening the classes.jar le inJD-GUI, we see the following class

les that comprise the Java archive(jar file):

1. BotBroadcastHander

Page 460: Android Security - Misra, Anmol

2. BotClient3. BotLocationHandler4. BotSMSHandler5. BotService6. BotWorker7. CutePuppiesWallpaper8. R

Table 6.1 – Permissions Listed inthe AndroidManifest for theWallpaper Application

Permission

Page 461: Android Security - Misra, Anmol

RECEIVE_BOOT_COMPLETED

Allows an application toreceive theACTION_BOOT_COMPLETEDthat is broadcast after thesystem finishes booting

INTERNETAllows an application toopen network sockets

Page 462: Android Security - Misra, Anmol

ACCESS_COARSE_LOCATIONAllows an application toaccess coarse (e.g., Cell-ID,WiFi) location

ACCESS_FINE_LOCATIONAllows an application toaccess fine (e.g., GPS)

Page 463: Android Security - Misra, Anmol

location

READ_PHONE_STATEAllows read-only access tophone state

SET_WALLPAPERAllows an application to setthe wallpaper

Page 464: Android Security - Misra, Anmol

WRITE_CONTACTSAllows an application towrite (but not read) theuser’s contacts data

READ_CONTACTSAllows an application toread the user’s contacts data

Page 465: Android Security - Misra, Anmol

RECEIVE_SMS Allows an application toread SMS messages

READ_OWNER_DATA Custom permission

Page 466: Android Security - Misra, Anmol

READ_HISTORY_BOOKMARKSAllows an application toread (but not write) theuser’s browsing history andbookmarks

WRITE_HISTORY_BOOKMARKS

Allows an application towrite (but not read) theuser’s browsing history andbookmarks

Page 467: Android Security - Misra, Anmol
Page 468: Android Security - Misra, Anmol

Figure 6.5 IPC Mechanisms Used by the CutePuppies Wallpaper Application

Table 6.2 – IPC Mechanisms Usedby the Cute Puppies WallpaperApplication

IPC Component

RECEIVERcom.adam.CutePuppiesWallpaper.BotBroadcastHandler

Page 469: Android Security - Misra, Anmol

RECEIVERcom.adam.CutePuppiesWallpaper.BotSMSHandler

SERVICEcom.adam.CutePuppiesWallpaper.BotService

Page 470: Android Security - Misra, Anmol

ACTIVITYCutePuppiesWallpaper

It seems thatCutePuppiesWallpaper is the le inwhich the main activity might bede ned. We look next at thecontents of this le through JD-GUI.

Analysis ofCutePuppiesWallpaper.class file:As seen from the screenshotdepicted in Figure 6.8, this class

le de nes the integer array thatpoints to wallpaper (de ned in theresources R le). It then starts

Page 471: Android Security - Misra, Anmol

BotService in the background. Wenow look at the BotService.classfile.

Analysis of BotService.class file

As seen from the screenshotdepicted in Figure 6.9, when botservice is started it initializesBotClient. The constructor to theBotClient includes an external URL(“k2.homeunix.com”) and socketport 1500. It then calls theBotClient. Run() method. We nowanalyze the BotClient.class le toanalyze the functionality de nedthere.

Page 472: Android Security - Misra, Anmol

Figure 6.6 Using dex2jar to Convert classes.dexFile to Jar Format

Page 473: Android Security - Misra, Anmol
Page 474: Android Security - Misra, Anmol

Figure 6.7 Using Java Decompiler to View JavaCode from Decompiled Jar File

Page 475: Android Security - Misra, Anmol
Page 476: Android Security - Misra, Anmol

Figure 6.8 CutePuppiesWallpaper Class

Page 477: Android Security - Misra, Anmol
Page 478: Android Security - Misra, Anmol

Figure 6.9 BotService.class

Analysis of BotClient.class file

When the BotClient.Run() methodis called, it, in turn, callsConnectToServer() and thenMasterCommandProcessor().ConnectToServer establishes thesocket connection to thethis.hostUri on port this.port. Italso creates input and outputstreams that read/write from thischannel (see Figure 6.10). It thenstarts theMasterCommandProcessor()thread. Inside Run(), the command

Page 479: Android Security - Misra, Anmol

from the server is read intolocalObject1, as shown in Figure6.11. The value is then checkedagainst integer values 101 through106. Depending on the value, thecorresponding BotWorker classmethod is called to return therequested information to theremote server. For example, if thevalue of localObject1 is 101, bwr.

Page 480: Android Security - Misra, Anmol

Figure 6.10 BotClient.class – ConnectToServer()

Page 481: Android Security - Misra, Anmol
Page 482: Android Security - Misra, Anmol

Figure 6.11 BotCIient.cIass –MasterCommandProcessor()

Page 483: Android Security - Misra, Anmol

Figure 6.12 BotClient.class –MasterCommandProcessor()

GetContactInfo is called andcontact information is sent to theremote server (see Figure 6.12).SendDataToMaster() writes to theoutput socket stream, thus sendingdata to the remote server.

Analysis of BotWorker.class file

As shown in Figures 6.12 and 6.13,depending on the value oflocalObject1, BotClient callsvarious methods in BotWorkerclass. For example, if the value oflocalObject1 is 101,

Page 484: Android Security - Misra, Anmol

BotWorker.GetContactInfo() iscalled by BotClient. The actualfunction of getting contactinformation from the device isde ned in the BotWorker class.This class also de nes similarmethods to obtain browser history,device information, packageinformation, and SMS data (seeFigure 6.14). Table 6.3 lists variousmethods de ned in BotWorkerclass.

Page 485: Android Security - Misra, Anmol
Page 486: Android Security - Misra, Anmol

Figure 6.13 GetContactInfo() called by BotClientwhen localObject1 = 101

Figure 6.14 Methods Defined in BotWorker Class

Page 487: Android Security - Misra, Anmol

Table 6.3 – Various MethodsDefined in BotWorker Class

Method Name Description

BotWorker(ContentResolverparamContentResolver,Context paramContext)

Constructormethod forBotWorkerclass(Figure6.15)

GetBrowserHistory()

Providesbrowserhistory

Page 488: Android Security - Misra, Anmol

(Figure6.16)

GetContactInfo()

Providescontactsinformation(Figure6.17)

GetCurrentLocation()

Provideslocationdata (Figure6.18)

Providesdevice

Page 489: Android Security - Misra, Anmol

GetDeviceID() information(Figure6.19)

GetPackagesInstalled()

Provideslisting ofpackagesinstalled ondevice(Figure6.20)

ObtainsSMS

Page 490: Android Security - Misra, Anmol

GetReceivedSMS() messagesreceived onthe device(Figure6.21)

ReadContacts()

Readscontact data(Figure6.22)

Figure 6.15 BotWorker Constructor

Page 491: Android Security - Misra, Anmol

Figure 6.16 GetBrowserHistory() in BotWorker

Analysis ofBotLocationHandler.class file

BotClient callsbwr.GetCurrentLocation() to obtainlocation data. This, in turn, callsBotLocationHandler().GetLastLocation()de ned in theBotLocationHanlder.class. Itobtains the current location of the

Page 492: Android Security - Misra, Anmol

BOT client (Figure 6.23).

Analysis of BotSMSHandler.classfile

BotClient callsbwr.GetReceivedSMS() to obtainSMS data. GetReceivedSMS() inBotWorker calls GetMessages()de ned in BotSMSHandler class.onReceive() in the class listens forincoming SMS messages andbu ers them to send them to theremote server (Figure 6.24).

Putting it all together—CutePuppiesWallpaperApplication Analysis

Page 493: Android Security - Misra, Anmol

Based on our analysis so far, wecan conclude that theCutePuppiesWallpaper applicationis malicious. As soon as theapplication is launched, it starts abackground service. Theapplication contains a proof-of-concept BOT, which connects to themaster Command and ControlCenter (CnC) using socketconnections. It then waits forcommands from the CnC. Thecenter can send di erentcommands to BOT on the device.

Page 494: Android Security - Misra, Anmol
Page 495: Android Security - Misra, Anmol

Figure 6.17 GetContactInfo() in BotWorker

Figure 6.18 GetCurrentLocation() in BotWorker

Although it is supposed to be awallpaper application, it requestspermission, such as RECEIVE_SMS,and de nes Intent lters for SMS

Page 496: Android Security - Misra, Anmol

receivers. By performing a codeanalysis, we conclude that itcreates a backdoor to a remoteserver. Based on commands sent bythe remote server, it can transferany of the following information tothe BOT server: contactinformation, browser history, SMSmessages, location (including GPSco-ordinates), packages installedon the device, IMEI number of thedevice, and so forth.

F r o m Figure 6.12, we canconstruct Table 6.4, illustratingdi erent commands sent by theBOT Master.

From our analysis, we can

Page 497: Android Security - Misra, Anmol

conclude the work ow of theCutePuppies Wallpaper application(see Figure 6.25).

A user downloads the applicationfrom either the Android Market orthrough another source and installsit on the device. When the userlaunches the application on thedevice, the BOT service gets startedin the background and the BOTclient contacts the CnC. The BOTserver establishes a connectionwith the client and sends acommand to the BOT client. TheBOT client processes the commandfrom the CnC and sends data backto the server.

Page 498: Android Security - Misra, Anmol
Page 499: Android Security - Misra, Anmol

Figure 6.19 GetDeviceID() in BotWorker

Page 500: Android Security - Misra, Anmol
Page 501: Android Security - Misra, Anmol

Figure 6.20 GetPackagesInstaIIed() inBotWorker

Page 502: Android Security - Misra, Anmol
Page 503: Android Security - Misra, Anmol

Figure 6.21 GetReceivedSMS() in BotWorker

Page 504: Android Security - Misra, Anmol
Page 505: Android Security - Misra, Anmol

Figure 6.22 ReadContacts() in BotWorker

Page 506: Android Security - Misra, Anmol
Page 507: Android Security - Misra, Anmol

Figure 6.23 GetLastLocation() Defined inBotLocationHandIer.cIass

Page 508: Android Security - Misra, Anmol
Page 509: Android Security - Misra, Anmol

Figure 6.24 GetMessages() Defined inBotSMSHanIder.cIass

Table 6.4 – Commands Sent byCnC to BOT Client

Command Purpose

MCS_CONTACTS_INFOGet contactinformation

MCS_BROWSER_HISTORYGet browserhistory

MCS_SMSGetincomingmessages

Page 510: Android Security - Misra, Anmol

MCS_LOCATIONGet GPSinformationfrom device

MCS_PACKAGESGet list ofapplicationsinstalled

MCS_DEVICE_INFOGet deviceinformation

6.5 Summary

In this chapter, we discussedmalware and behavior thatconstitutes malware. We thendiscussed malicious behavior in the

Page 511: Android Security - Misra, Anmol

context of Android applicationsand walked the reader through themethodology available to analyzeAndroid applications for maliciousbehavior. We then covered a casestudy where we demonstrated astep-by-step analysis of a malwareapplication to determine itsbehavior and functionality.

Page 512: Android Security - Misra, Anmol
Page 513: Android Security - Misra, Anmol

Figure 6.25 Workflow

Page 514: Android Security - Misra, Anmol

Chapter 7Modifying the Behaviorof Android Applicationswithout Source Code

This chapter builds on Chapter 6.We begin by discussing potentialuse cases forrecompiling/modifying thebehavior of applications. We showhow to analyze and debug Androidapplication binaries. We cover the.dex le format and show how todecompile and recompile Androidapplications without having access

Page 515: Android Security - Misra, Anmol

to source code, thus changing theapplication’s behavior. Wedemonstrate how an attacker canchange an application’s behaviorby decompiling the application,changing the smali code, andrecompiling it.

7.1 Introduction

The techniques covered in thischapter are not generally used by atypical user or developer. A personusing the techniques covered hereis probably attempting one of thefollowing (which is unethical if notillegal):

Page 516: Android Security - Misra, Anmol

1. To add malicious behavior2. To eliminate malicious

behavior3. To bypass intended

functionality

7.1.1 To Add Malicious Behavior

It should be noted that doing this isillegal. Malicious users canpotentially download an Androidapplication (apk), decompile it,add malicious behavior to it,repackage the application, and putit back on the Web on secondaryAndroid markets. Since Androidapplications are available from

Page 517: Android Security - Misra, Anmol

multiple markets, some users mightbe lured to install these modi edmalicious applications and thus bevictimized.

7.1.2 To Eliminate MaliciousBehavior

The techniques listed here can beused to analyze suspiciousapplications, and, ifillegal/malicious behavior isdetected, to modify them andremove the illegal/maliciousbehavior. Analyzing an applicationfor malicious behavior is ne andnecessary for security and forensicspurposes. However, if there is

Page 518: Android Security - Misra, Anmol

indeed such behavior detected,users should just remove theapplication and do a clean installfrom a reliable source.

7.1.3 To Bypass IntendedFunctionality

A third potential use of thetechniques listed here could be tobypass the intended functionalityof an application. Manyapplications require a registrationcode or serial key before beingused or they can only be used for aspeci ed trial period or show adswhen being used. A user of thesetechniques could edit smali code

Page 519: Android Security - Misra, Anmol

and bypass these mechanisms.

7.2 DEX File Format

We covered the Dalvik VirtualMachine (VM) in Chapter 2. TheDalvik VM is a register-basedvirtual machine designed to runAndroid applications. The DalvikVM enables applications to rune ciently on devices in whichbattery life and processing powerare of paramount important.Android applications written inJava are compiled into Java bytecode using a Java compiler. For aJava application to run onAndroid, there is one extra step

Page 520: Android Security - Misra, Anmol

that is added, that is, converting.class les (Java byte code) to .dex

les (Dex le or Dalvik byte code).Dex code is executed by the Dalvikvirtual machine. Whereas there aremultiple .class les, there is onlyone .dex le, in which all relevantclass les are compiled by theDalvik dx compiler. Figure 7.1shows the le structure of .dexfiles.

Page 521: Android Security - Misra, Anmol

Figure 7.1 Anatomy of a .DEX File

The Android SDK comes with adexdump tool that can be used to

Page 522: Android Security - Misra, Anmol

get a dump of dex le content.However, it is not very informativefor a novice reading it.

Figure 7.3 shows dex le headerinformation (through dexdump –f)for a classes.dex le obtained bycompiling HelloActivity.java (seeFigure 7.2). As seen in Figure 7.3,the Classes.dex le containsinformation on the dex le itself,including checksum, le size,header size, and size and o sets tovarious sections of the .dex le..dex le contains the followingsections: header, string, type, eld,method, class, and data. There isan entry for each class in the

Page 523: Android Security - Misra, Anmol

program. Figure 7.4 shows anentry for the HelloActivity class.This entry also displays methods(init, OnCreate). Figure 7.5displays an entry for the R class.

Figure 7.2 Simple “Hello World” Program forAndroid

Page 524: Android Security - Misra, Anmol

Figure 7.3 Header Information in classes.dex forHelloActivity

As can be seen in Figures 7.4 and7.5, the output from dexdump doesnot provide intuitive information.Although it is helpful forunderstanding bits and pieces of

Page 525: Android Security - Misra, Anmol

the application’s behavior, it is notquite readable. Therefore, we willuse smali/baksmaliassembler/disassembler to analyzeand modify the .dex format leinstead, as the smali le is easy tounderstand. Smali takes .dex lesand produces smali les, which aremore readable and havedebugging, annotations, lineinformation, and so forth. Baksmalienables the assembling of smali

les back to the .dex format. TheApkTool enables us to repackagethe modi ed .dex le into an apkfile.

Page 526: Android Security - Misra, Anmol

7.3 Case Study: Modifying theBehavior of an Application

We will now demonstrate howapplication behavior can bemodi ed by decompiling it intosmali code, recompiling it, andthen packaging it into an apk le.The authors have created a simpleapplication that requires the userto enter the correct passcode beforeusing the application. We willdemonstrate how a malicious usercan potentially bypass thisintended functionality. See AppScreenshots in Figures 7.6 and 7.7.

Page 527: Android Security - Misra, Anmol

Figure 7.4 HelloActivity Class Information in

Page 528: Android Security - Misra, Anmol

classes.dex

Page 529: Android Security - Misra, Anmol
Page 530: Android Security - Misra, Anmol

Figure 7.5 R Class Information in classes.dex

Figure 7.6 Secure App on Android Emulator

Page 531: Android Security - Misra, Anmol

The rst step in analyzing or toreverse engineering an applicationis to understand its behavior.Typically, this entails installingand using the application andreviewing its various functions. Inour case, we can install theapplication on an emulator and tryto use it. As depicted in Figure 7.8,launching the application presentsthe user with a password screen. Atthis point, we don’t know thelength of the password required orif passwords are numeric (PIN) oractual passwords. We learn (bytrial and error) that the applicationonly accepts digits as a password.

Page 532: Android Security - Misra, Anmol

We also note that the maximumnumber of digits the applicationallows us to enter is 4. Thus, wecan conclude that the password isall numeric and is 4 digits inlength.

Step 1: Decompile theapplication

We can decompile the applicationle (apk) by using apktool. Figure

7.9 shows SecureApp.apkdecompiled into a secure_appfolder. Browsing through the folder(Figure 7.10), we note that there isa smali folder. Smali les are found

Page 533: Android Security - Misra, Anmol

in the test directory. Note thatthere are smali les (Figure 7.11)beginning with both KeyPad and Rpre xes. We can conclude from thisthat the application had two Javafiles—KeyPad.java and R.java.

Page 534: Android Security - Misra, Anmol

Figure 7.7 Successful Login on Secure App

Step 2: Make changes to theapplication

Page 535: Android Security - Misra, Anmol

Reading through the smali code forthe KeyPad$1.smali le (Figure7.12), we conclude that SHA-256 isbeing used for hashing passworduser inputs from the login screen ofthe application. This password isthen compared against the storedpassword and if they match, theuser is logged into the application.

The hash is loaded into v8 andcompared with v10 (line 51 inFigure 7.13). If these values are thesame, the user is logged in. We cancreate a SHA-256 hash value andcreate an entry to input into v8,thus modifying the password to ourchoice and bypassing

Page 536: Android Security - Misra, Anmol

authentication. Figure 7.13 showsthe original smali le created byapktool, and Figure 7.14 shows themodi ed smali le with thefollowing entry (SHA-256 hash of“1234” with a salt): const-string v8,

“2DD225ED6888BA62465CF4C54DB21FC17700925D0BD0774EE60B600B0172E916”

Note that there is usually a “salt”passed onto the hash algorithm.Finding out the value of the salt(and that of the hash of theoriginal password) is left to thereader as an exercise. Once thereader is able to obtain the hashand the salt, he or she can brute

Page 537: Android Security - Misra, Anmol

force it by computing the hashes ofgenerated passwords andcomparing it with the stored hashin the le. The answers areprovided toward the end of thebook.

Step 3: Recompile theapplication

Modi ed smali code can bereassembled and packaged into anapk le through the followingcommand: apktool b (Figure 7.15).New Apk le will be placed in distdirectory (Figure 7.16).

Page 538: Android Security - Misra, Anmol
Page 539: Android Security - Misra, Anmol

Figure 7.8 Analyzing an Application’s Behavior

Page 540: Android Security - Misra, Anmol
Page 541: Android Security - Misra, Anmol

Figure 7.9 Decompiling SecureApp.apk Usingapktool

Page 542: Android Security - Misra, Anmol
Page 543: Android Security - Misra, Anmol

Figure 7.10 Smali files Created by apktool

Page 544: Android Security - Misra, Anmol

Figure 7.11 KeyPad.smali File

Page 545: Android Security - Misra, Anmol
Page 546: Android Security - Misra, Anmol

Figure 7.12 SHA-256 String in KeyPad$1.smali

Page 547: Android Security - Misra, Anmol
Page 548: Android Security - Misra, Anmol

Figure 7.13 if-eqz v10 Compares ComputedHash Value with the Hash Value in v8.

Page 549: Android Security - Misra, Anmol
Page 550: Android Security - Misra, Anmol

Figure 7.14 Entering Hash Value of Our Choicein v8

A new apk needs to be signedbefore it can be installed on thedevice or emulator. The Signapktool (Figure 7.17) is freelyavailable on the Web fordownload. After installing themodi ed apk, the reader can use“1234” as the password string touse the application.

Page 551: Android Security - Misra, Anmol

Figure 7.15 Additional Directories Created byapktool b Command

The methodology listed abovecan be used to analyze, decompile,and recompile an existingapplication. We provided anexample of an application createdby the authors and vulnerabilitythat could have been exploited to

Page 552: Android Security - Misra, Anmol

bypass authentication and getaccess to application data orfunctionality. The vulnerabilitydescribed here was not theoretical.There have been cases where asimilar issue could have resulted incompromised user data.

7.4 Real World Example 1—Google Wallet Vulnerability

Google Wallet is mobile paymentsoftware developed by Google. Itallows users to store (securely)credit card numbers, gift cards, andso forth, on their cell phones. Ituses Near Field Communication(NFC) to make secure payments on

Page 553: Android Security - Misra, Anmol

PayPass-enabled terminals atcheckout counters (e.g.,MasterCard’s PayPass). The idea isto use cell phones to makepurchases instead of using physicalcredit/debit/gift cards.

Figure 7.16 New apk Will Be Placed in distDirectory

Page 554: Android Security - Misra, Anmol

Figure 7.17 Signing New APK File

Note: NFC is a set of standards thatallows mobile devices tocommunicate through radiofrequencies with devices nearby.This can be leveraged fortransactions and data exchange.

NFC uses RFID to communicatewirelessly. Security was providedthrough a device—Secure Element(SE), which was used to encryptsensitive data (e.g., a credit cardnumber). To access thisinformation, the user needed toprovide a 4-digit PIN. After ve

Page 555: Android Security - Misra, Anmol

invalid attempts, data would bewiped out.

It turned out that the PIN wasstored in the sqlite database inbinary format. Data was compiledusing Google’s “protocol bu ers”—a library for serializing data formessage passing between systems.Contents of the PIN could beobtained from this binary string. Itincluded a salt and a SHA 256 hashstring. One can easily brute forcethis PIN knowing that the PINcould only be four digits. Onewould need to root the device toobtain this data, and this issomething that can be

Page 556: Android Security - Misra, Anmol

accomplished without much e ort,as there are many tools availableto root Android devices. For furtherdetails refer to the following URL:https://zvelo.com/blog/entry/google-wallet-security-pin-exposure-vulnerability

7.5 Real World Example 2—Skype Vulnerability (CVE-2011-1717)

In 2011, it was discovered thatSkype for Android was storingsensitive user information (e.g.,user IDs, contact information,phone numbers, date of birth,instant messaging logs, and other

Page 557: Android Security - Misra, Anmol

data) in a sqlite3 database.However, the application did notsecure this database with properpermissions (world readable), andthus any application or user couldaccess it. Also, data was beingstored unencrypted (in plain text)in the sqlite3 database AndroidPolice discovered the vulnerability,and they also had a proof-of-concept application that exploitedthe issue, thus obtaining data fromthe Skype application.

7.6 Defensive Strategies

In this section, we cover ve mainstrategies to prevent reverse

Page 558: Android Security - Misra, Anmol

engineering of an application or tominimize information leakageduring the reverse engineeringprocess.

7.6.1 Perform Code Obfuscation

Code Obfuscation is the deliberateact of making source code ormachine code di cult toread/understand by humans andthus making it a bit more di cultto debug and/or reverse engineeronly from executable les.Companies use this technique tomake it harder for someone to stealtheir IP or to prevent tampering.

Most Android applications are

Page 559: Android Security - Misra, Anmol

written in Java. Since Java codegets compiled into byte code(running on a VM) in a class le, itis comparatively easier to reverseengineer it or to decompile it thanbinary executable les fromC/C++. Consequently, we cannotrely only on code obfuscation forprotecting intellectual property orusers’ privacy. We need to assumethat it is possible for someone todecompile the apk and more or lessget access to the source code.Instead of relying completely oncode obfuscation, we suggestrelying on “Server SideProcessing,” where possible

Page 560: Android Security - Misra, Anmol

(covered in the following section).One of the freely available Java

obfuscators that can be used withAndroid is ProGuard. ProGuardshrinks and obfuscates Java class

les. It is capable of detecting andremoving unused classes, elds,methods, and so forth. It can alsorename these variables to shorter(and perhaps meaningless) names.Thus, the resulting apk les willrequire more time to decipher.ProGuard has been integrated intothe Android-built system. It runsonly when an application is builtin the release mode (and not in thedebug mode).

Page 561: Android Security - Misra, Anmol

To use ProGuard and enable it torun as part of the Ant or Eclipsebuild process, set theproguard.con g property in theproperties.cfg le. This le can befound in the root directory of theproject (see Figure 7.18).

The screenshots in Figures 7.19and 7.20 show decompiled code inJD-GUI. Figure 7.19 shows codewhen code obfuscation (throughProGuard) was not used. Figure7.20 shows it after using ProGuard.As you can see, ProGuard shortensclass names and renames them. Italso performs such operations onmethods and elds. Since this is a

Page 562: Android Security - Misra, Anmol

simple application, codeobfuscation does not result in muchdi erence between the screenshots.With a complex application, theresulting output would be muchbetter.

ProGuard might not be one ofthe best obfuscators out there forJava. However, it is something thatone should de nitely use in theabsence of other options.

Page 563: Android Security - Misra, Anmol
Page 564: Android Security - Misra, Anmol

Figure 7.18 proguard.cfg File in Eclipse

Page 565: Android Security - Misra, Anmol
Page 566: Android Security - Misra, Anmol

Figure 7.19 Code without Obfuscation (in JD-GUI)

Page 567: Android Security - Misra, Anmol
Page 568: Android Security - Misra, Anmol

Figure 7.20 Code with Obfuscation (in JD-GUI)

7.6.2 Perform Server SideProcessing

Depending on the type ofapplication, it might be possible toperform sensitive operations anddata processing on the server side.For example, for an applicationthat pulls data from the server toload locally (e.g., twitter), much ofthe application logic is performedon the server end. Once theapplication authenticatessuccessfully and the validity of theuser is veri ed, the application canrely on the server side for much of

Page 569: Android Security - Misra, Anmol

the processing. Thus, even ifcompiled binary is reverseengineered, much of the logicwould be out of reach, as it will beon server side.

7.6.3 Perform Iterative Hashingand Use Salt

Hash functions can be susceptibleto collision. In addition, it might bepossible to brute force hash forweaker hash functions. Hashfunctions make it very di cult tobrute force (unless you are agovernment agency with enormouscomputing power) while providingreasonably high collision

Page 570: Android Security - Misra, Anmol

resistance. The SHA-2 family tsthis category.

A stronger hash can be obtainedby using salt. In cryptography, asalt consists of random bits and isusually one of the inputs to thehash function (which is one wayand thus collision resistant). Theother input is the secret (PIN,passcode, or password). This makesbrute force attacks more di cult,as more time/space is needed. Thesame is true for rainbow tables.Rainbow tables are a set of tablesthat provide precomputedpassword hashes, thus making iteasier to obtain plaintext

Page 571: Android Security - Misra, Anmol

passwords. They are an example ofspace-time or timememory tradeo (i.e., increasing memoryreduces computation time).

In addition, we recommend usingiterative hashing for sensitive data.This means simply taking the hashof data and hashing it again and soon. If this is done a su cientnumber of times, the resultant hashcan be fairly strong against bruteforce attacks in case an attackercan guess or capture the hashvalue.

7.6.4 Choose the Right Locationfor Sensitive Information

Page 572: Android Security - Misra, Anmol

The location of sensitiveinformation (and access to it)matters as much as the techniquesdescribed above. If we store stronghashes at a publicly accessiblelocation (e.g., values.xml or on ansd card or local le system withpublic read attributes to it), thenwe make it a bit easier for anattacker. Android provides a greatway to restrict access—data canonly be explicitly made availablethrough permissions wherein, bydefault, only the UID of the appitself can access it.

An ideal place for storingsensitive information would be in

Page 573: Android Security - Misra, Anmol

the database or in preferences,where other applications don’thave access to it.

7.6.5 Cryptography

In the iterative hashing section, wediscussed how to make a user’spasswords or sensitive informationstronger through the use ofcryptography (hashing and salt).Cryptography can also be used toprotect a user’s data. There are twomain ways of doing this forAndroid: (1) Every application canstore data in an encrypted manner(e.g., the user’s contact informationcan be encrypted and then stored

Page 574: Android Security - Misra, Anmol

in a sqlite3 database). (2) Use diskencryption, wherein everythingwritten to the disk isencrypted/decrypted on the y.System administrators prefer full-disk encryption, so as not to relyon developers to implementencryption capabilities in theirApps.

7.6.6 Conclusion

Access Control (relying on the OSto prevent access to critical les),cryptography (relying onencryption as well as hashing toprotect con dential data [e.g.,tokens] and to verify the integrity

Page 575: Android Security - Misra, Anmol

of an application), and codeobfuscation (making it di cult todecipher class les) are the mainstrategies that one should leverageto prevent the reverse engineeringof applications. Both the GoogleWallet vulnerability and the Skypeissue would have been prevented ifdevelopers and systemadministrators had madeappropriate use of access controlsand cryptography.

7.7 Summary

In this chapter, we discussedpotential scenarios ofdisassembling and reassembling an

Page 576: Android Security - Misra, Anmol

Android application withouthaving access to source code. Wethen demonstrated this through theuse of a SecureApp written by theauthors. We presented security bestpractices to prevent reverseengineering as well as thepotential leaking of sensitiveinformation through it. The readershould try to develop an Androidapplication (or downloadSecureApp from the book’s website—www.androidinsecurity.com) andtry the techniques listed in thischapter.

Page 577: Android Security - Misra, Anmol

Chapter 8Hacking Android

In this chapter, we introduceforensics and techniques used toperform it. We walk the readerthrough the Android le system,directories, and mount points. Wecover SD card analysis andAndroid-speci c techniques toperform forensics. Finally, we walkthe reader through an example thatdemonstrates topics covered in thischapter.

8.1 Introduction

Page 578: Android Security - Misra, Anmol

Mobile device forensics is a branchof digital forensics that relates tothe recovery of digital evidence ordata from a mobile device underforensically sound conditions(http://en.wikipedia.org/wiki/Mobile_device_forensics

As discussed in Chapter 1, mobiledevices today are a di erent beast.They are used for all kind ofcommunications, transactions, andtasks. The following kinds ofpersonal information are typicallyfound on a smartphone: contacts,photos, calendars, notes, SMS,MMS, e-mail, browser history, GPSlocations, social mediainformation, nancial data,

Page 579: Android Security - Misra, Anmol

passwords, and so forth. You getthe idea! If we have a device that isevidence in a legal investigation orneeds to be analyzed for a securityinvestigation, it can provide agoldmine of information, providedone knows how to extract thisinformation carefully. Our focus inthis chapter is on extracting asmuch information as we can,rather than “extracting underforensically correct” conditions.The latter is a topic for a di erentbook.

To perform forensics on Androiddevices, it is important tounderstand the Android system. We

Page 580: Android Security - Misra, Anmol

have already covered Androidarchitecture and the securitymodel. In this chapter, we willwalk through le system speci cs(directories, les, mount points,and le systems). We need tounderstand how, where, and whattype of data is stored on the device,to perform the actual extraction ofuseful information. Data can bestored on a le system as les, inapplication/system-specificformats, or in SQLite DBs.

8.2 Android File System

In this section, we will review theAndroid File System by looking at

Page 581: Android Security - Misra, Anmol

various mount points (Figure 8.1)on a typical Android device, aswell as its directory structure,which might be of interest to us forgathering useful information.

8.2.1 Mount Points

Let’s look at various partitions onan Android device and analyzerelevant ones for their directorystructures. Typing “adb shellmount” (Figure 8.2) showsmounted le systems on the device,whereas typing “adb shell cat/proc/filesystems” gives us a listingof supported le systems (seeFigure 8.3) . Table 8.1 shows

Page 582: Android Security - Misra, Anmol

various partitions and theirdescriptions.

8.2.2 File Systems

Android supports quite a few lesystems (based on the Linuxkernel). One can obtain a list ofsupported le systems by typing“cat /proc/ lesystems” at thecommand line. As can be seen fromFigure 8.3, the nodev entry next to

le system indicates that there isno physical device associated withthat particular le system, thusmaking a nodev virtual le system.Note that Android supports ext2,ext3, and ext4 le systems (used by

Page 583: Android Security - Misra, Anmol

Linux systems) and the vfat lesystem used by Windows-basedsystems. Since it is targeted formobile devices, Android supportsYAFFS and YAFFS2 le systems(needed to support NAND chipsused in these devices). Table 8.2provides more information onthese file systems.

8.2.3 Directory Structure

Let’s look at the directory structureof a typical Android device. Onecan access the le system throughthe command line (adb) or throughEclipse/DDMS (Figure 8.4). Thereare three main directories that are

Page 584: Android Security - Misra, Anmol

of interest to us: /system, /sdcard,and /data. As mentioned earlier,/system holds most of theOperating System (OS) les,including system applications,libraries, fonts, executables, and soforth. /sdcard is a soft link to the/mnt/sdcard and refers to the SDcard on the device. /data directorycontains user data. Morespeci cally, each application hasan entry in/data/app/<application name>,and user data resides in/data/data/<application_name>.On the device itself, one would notbe able to access the /data folder,

Page 585: Android Security - Misra, Anmol

as it is accessible only to the systemuser (as opposed to the shell user).We use an emulator to demonstratethe contents of the /data directory.Since user data for an applicationresides in/data/data/<application_name>,it is important that only thatapplication has access to thatparticular folder. This isaccomplished through userpermissions (each application hasits own UID, and only thatUID/user has permissions to accessthe folder). Table 8.3 provides asummary of important

les/directories on Android that an

Page 586: Android Security - Misra, Anmol

application might interact with.We will cover the structure of the/data/data/folder later in thischapter.

Page 587: Android Security - Misra, Anmol
Page 588: Android Security - Misra, Anmol

Figure 8.1 Mount Points on an Android Device

Figure 8.2 Directory Structure of an AndroidDevice (ADB)

Page 589: Android Security - Misra, Anmol

Figure 8.3 File Systems of an Android Device

8.3 Android Application Data

Page 590: Android Security - Misra, Anmol

In this section, we cover howapplications can store persistentdata and also review the contentsof the /data/data folder and howthey can be used to retrieve usefulinformation.

8.3.1 Storage Options

Android provides multiple optionswhereby an application can savepersistent data (depending on theapplication’s needs). Table 8.4shows various options for storingdata.

Table 8.1 – Overview of MountedFile Systems on an Android

Page 591: Android Security - Misra, Anmol

Device

Mount Point Description

/

This is a read-only root filesystem and ismounted by thekernel beforeany other filesystem. Itcontainsimportantsystem

Page 592: Android Security - Misra, Anmol

information,including bootconfigurationand librariesthat the kernelneeds atstartup.

Contains systemlibraries,executable,fonts, systemapplications,

Page 593: Android Security - Misra, Anmol

/system

andconfigurationfiles.Subdirectoriesinclude ban, lib,etc, bin, app,media, fonts,and so forth.Permissions onthis file systemare ro.Containstemporary files

Page 594: Android Security - Misra, Anmol

/cache

such as browsercache anddownloads. Italso containsfiles that arerecovered whena repair to acorrupted filesystem isperformed.Permissions onthis file systemare rw.

Page 595: Android Security - Misra, Anmol

/data

Contains userand applicationdata, includinguserinstalledapplications,settings, andpreferences.

/mnt/sdcard

This partitionpoints to the SDcard. Note thatthis is a FAT32file system and

Page 596: Android Security - Misra, Anmol

has rwpermissions.

/mnt/secure/asec

This is anencryptedcontainer onthe SD card forapps that areinstalled on theSD card.

Table 8.2 – Different Kinds ofFile Systems on Android

Page 597: Android Security - Misra, Anmol

FileSystem

Description

YAFFSandYAFFS2

These are fast and robustfile systems used by manymobile devices to supportNAND or NOR flash chips.They are specificallydesigned to be used inembedded devices. Yaff2is a newer version of filesystem (Yaffs1 supported512-byte page flash,

Page 598: Android Security - Misra, Anmol

whereas Yaffs2 supports2k-byte page flash, aswell). For more detailsrefer tohttp://www.yaffs.net/These file systems(second, third, and fourthextended file systems) arecommonly used by theLinux kernel. Ext 2 wasintroduced in the early1990s to resolve issues inthe ext file system used by

Page 599: Android Security - Misra, Anmol

ext2,ext3,andext4

the Linux kernel. Ext 3added journalingcapability, among otherfeatures, to ext 2. Ext 4further added newcapabilities to ext3,including supportinglarge file systems and filesizes, extents (replacedblock mapping present inext2 and ext3), and soforth.

Page 600: Android Security - Misra, Anmol

vfat

This is a FAT32 filesystem from Microsoft.Linux kernelimplementation of it isreferred to as VFAT. Thisfile system is used byAndroid primarily for SDcards.

Page 601: Android Security - Misra, Anmol
Page 602: Android Security - Misra, Anmol

Figure 8.4 Directory Structure of an AndroidDevice (DDMS)

Table 8.3 – ImportantFiles/Directories on Android

Directory/File

cache

Page 603: Android Security - Misra, Anmol

/sdcard

/vendor

Page 604: Android Security - Misra, Anmol

/system

Page 605: Android Security - Misra, Anmol

/system/etc/permissions/platform.xml

/system/app

Page 606: Android Security - Misra, Anmol

/system/bin

/system/buid.prop

/data/data

Page 607: Android Security - Misra, Anmol

/data/app

/data/app-private

/mnt/asec

8.3.2 /data/data

Now that we have covered options

Page 608: Android Security - Misra, Anmol

available to an application forstoring data, let’s examine somereal-world applications andanalyze their /data/data/directory. We installed the Seesmicapplication, which allows you toconnect you to multiple socialmedia accounts. Figure 8.5 showssubdirectories of the/data/data/com.seesmicapplication. The Seesmicapplication has three folders:databases, libs, and shared_prefs.Accessing the /data/data directoryon the device would not bepossible, as permissions arerestricted to the system owner (as

Page 609: Android Security - Misra, Anmol

opposed to the shell user). One hasto either root the phone or image itto be able to obtain access to thecontents of this directory.

Table 8.4 – Overview of StorageOptions for AndroidApplications

StorageOption

Description

SharedPreferences

Stores private data in key-value format. Anyprimitive data (Booleans,float, int, strings, etc.) can

Page 610: Android Security - Misra, Anmol

be saved using SharedPreferences.

InternalStorage

Stores private data on theinternal memory. Anapplication can save filesdirectly onto the internalmemory (as opposed toexternal memory, such asan SD card). Files areprotected through filepermissions, with anapplication being theowner of the file. Note

Page 611: Android Security - Misra, Anmol

that one needs to use theMODE_PRIVATE option tocreate a file. UsingMODE_WORLD_READABLEorMODE_WORLD_WRITABLEwill make a file accessibleto other applications.

ExternalStorage

Stores data on sharedexternal storage. Filessaved to external storageare world readable, andthere is no file permission-

Page 612: Android Security - Misra, Anmol

based security.

SQLiteDatabases

Stores data in a privatedatabase accessible only toan application.

NetworkConnection

Stores data on a networkserver.

Looking at the folder structuresuggests that the application mightbe storing some data in SQLitedatabases, as well as in the form ofShared Preferences. It might beworthwhile to investigate these

les and see if we can gather moreinformation. Browsing to theshared_prefs directory and

Page 613: Android Security - Misra, Anmol

performing “cat” on one of theXML les, we get information usedby the application (key-valuepairs). Please note Figure 8.6. Oneof the key-value gures de ned inthe le is req_token_secret, andanother is req_token. If applicationdevelopers are not careful, theymight store all kinds of sensitiveinformation in here (includingpasswords in plaintext).

Figure 8.5 Directories Inside /data/data for the

Page 614: Android Security - Misra, Anmol

Seesmic Application

Figure 8.6 Contents of One of the XML Files in

Page 615: Android Security - Misra, Anmol

the shared_prefs Folder

We have noted that there is adatabase folder inside/data/data/com.seesmic. Browsingto the folder, we nd a databasenamed twitter.db, indicating thatthe user of the device had a twitteraccount. Let’s see if we can getdetails of the twitter account fromthe database. This can be donethrough the sqlite3 command lineutility. As seen from Figure 8.7, wecan understand the schema of thedatabase and then query di erenttables to retrieve information.

8.4 Rooting Android Devices

Page 616: Android Security - Misra, Anmol

Android, by default, comes with arestricted set of permissions for itsuser. These restrictions have beencarefully designed to preventmalicious applications (and users)to circumvent controls provided bythe Android security model. Theyare also sometimes used to preventa particular functionality frombeing accessed or changed (e.g.,tethering or installing proxy, andso forth). Rooting an Androiddevice can be useful when we needto analyze a device. When we logon to a shell (through adb shell),the UID of the user is “shell.” Wecan’t really access directories such

Page 617: Android Security - Misra, Anmol

as /data, as we don’t havesu cient permission. Thus, weneed to elevate our privileges tosuper user. The process of gettingthese is called rooting. Typically, avulnerability in the system whenexploited successfully allows us tobecome a super user. One candownload corresponding<version>Break. apk les fromthe web and root a device. In thefollowing, we walk a user throughrooting the Android Froyo 2.2.

Page 618: Android Security - Misra, Anmol
Page 619: Android Security - Misra, Anmol

Figure 8.7 Contents of SQLite DB

1. Determine the version of theAndroid OS running on yourdevice. This can be found bygoing to “Settings” -> “AboutPhone.” This should give youthe Android and kernelversion details (Figure 8.8).

2. Connecting through the adbshell and executing the “ID”command should show you asa “shell” user (UID = 2000[shell]).

3. Download Gingerbreak.apk(Figure 8.9) (given you arerunning Android Froyo 2.2.2,

Page 620: Android Security - Misra, Anmol

Honeycomb, Gingerbread).

Figure 8.8 Android Version

Page 621: Android Security - Misra, Anmol
Page 622: Android Security - Misra, Anmol

Figure 8.9 Gingerbreak Application

4. Enable USB Debugging.5. Install Gingerbreak on the

phone by executing thefollowing command “adbinstall gingerbreak.apk.”

6. Open the Gingerbreakapplication on the phone. Thiswill install the super userapplication.

7. Now, connect to the deviceusing the command line (adb)and execute the su command(see Figure 8.10). You shouldnow be rooted on the deviceand be able to browse to

Page 623: Android Security - Misra, Anmol

directories such as /data/data.

8.5 Imaging Android

It is sometimes useful to create animage of the Android device andanalyze it using various toolsavailable on your workstation. Thisis especially true in the case of aninvestigation where the original

le system needs to be preservedfor evidence/future reference. Wemay also not want to work directlyo the device but, rather, a copy ofit for investigation/analysis. Beloware instructions for imaging anAndroid device:

Page 624: Android Security - Misra, Anmol
Page 625: Android Security - Misra, Anmol

Figure 8.10 Root Shell on an Android Device

1. Download mkfs.ya s2 andcopy it onto the SD cardconnected to your device,through the followingcommand:

2. Open adb shell and change toroot user (su). Change thepermission of/mnt/sdcard/tmp/ya s2 leto 755

3. Create an image of theAndroid device by executingthe command that follows.This will create data.img,which will contain the image

Page 626: Android Security - Misra, Anmol

of the Android device4. Pull data onto your

workstation by using the“pull” command from adbshell

Now that you have the deviceimage on your workstation, youcan use tools such as ya ey toanalyze the image (Figure 8.11),browse through di erentdirectories, review les, and soforth. Ya ey is available at thefollowing URL:http//code.google.com/p/yaffey/.

8.6 Accessing Application

Page 627: Android Security - Misra, Anmol

Databases

As discussed earlier in the chapter,applications can store structureddata in SQLite databases. Eachapplication can create DB lesunder the/data/data/<appname>/databasesfolder. Although we can root adevice and analyze databasesthrough the sqlite3 command lineutility, it is convenient to imagethe device and analyze it usingworkstation tools such as ya eyand the SQLite browser. Below aresteps to retrieve the database lesand view them in SQLite:

Page 628: Android Security - Misra, Anmol

1. Root and image the /datapartition on your phone (asshown in the previoussection).

2. Download and install SQLitebrowser fromhttp://sqlitebrowser.sourceforge.net/index.html

3. Browse to the SQL database ofan application through ya eyand pull the applicationdatabase onto yourworkstation (see Figure 8.12)or execute the commandbelow:

4. Open twitter.db in the SQLlitedatabase browser (see Figure

Page 629: Android Security - Misra, Anmol

8.13).

Page 630: Android Security - Misra, Anmol
Page 631: Android Security - Misra, Anmol

Figure 8.11 Analyzing a Device Image throughYaffey

Page 632: Android Security - Misra, Anmol
Page 633: Android Security - Misra, Anmol

Figure 8.12 Database Location for a TwitterApplication

Page 634: Android Security - Misra, Anmol
Page 635: Android Security - Misra, Anmol

Figure 8.13 Analyzing a Twitter DB in theSQLite DB Browser

8.7 Extracting Data fromAndroid Devices

In the previous section, we showedhow to root an Android device andobtain useful information stored onit. While we can certainly do thispiece-by-piece, there are tools thatcan help us to do this moree ciently—for example, theMOBILedit application. On arooted device, MOBILedit allows usto extract all kinds of informationfrom the device (contactinformation, SMS messages,

Page 636: Android Security - Misra, Anmol

databases from di erentapplications, and so forth). Beloware steps to extract informationfrom a device using thisapplication:

1. Make sure your device isrooted (see previous sectionsin this chapter).

2. Download and install theMOBILedit application (Figure8.14).

3. Input your device’s IP addressinto the MOBLedit application(see Figure 8.15).

4. Once the application connects

Page 637: Android Security - Misra, Anmol

to your device, you candownload/view information,including call data, SMSmessages, photos, and so forth(see Figure 8.16).

5. You can also download datafrom the MobilEdit and usethe techniques described in theprevious sections to do afurther analysis analysis (seeFigure 8.17).

8.8 Summary

In this chapter, we describeddi erent le systems used byAndroid. We reviewed relevantpartitions and mount points that

Page 638: Android Security - Misra, Anmol

would of interest to securityprofessionals to to analyze a deviceor applications. We revieweddi erent mechanisms throughwhich an application can storepersistent data (databases,preferences, les, and so forth) andhow to obtain and analyze thesebits. We covered steps to root anAndroid device (though this will bedi erent from release to release)and how to use third-partyapplications to retrieve data fromAndroid devices.

Page 639: Android Security - Misra, Anmol
Page 640: Android Security - Misra, Anmol

Figure 8.14 MOBILedit Application afterLaunching

Page 641: Android Security - Misra, Anmol
Page 642: Android Security - Misra, Anmol

Figure 8.15 Connecting to an Android DeviceUsing MOBILedit

Page 643: Android Security - Misra, Anmol
Page 644: Android Security - Misra, Anmol

Figure 8.16 Obtaining Contact Data, SMS/MMS,E-mail, and Photos

Page 645: Android Security - Misra, Anmol
Page 646: Android Security - Misra, Anmol

Figure 8.17 Obtaining Data from the File Systemon the Device

Page 647: Android Security - Misra, Anmol

Chapter 9Securing Android for theEnterprise Environment

In this chapter, we look at securityconcerns for deploying Androidand Android applications in anenterprise environment. We rstreview security considerations formobile devices, in general, as wellas Android devices, in particular.We then move on to covermonitoring and compliance/auditconsiderations, as well as end-usertraining. We then look at

Page 648: Android Security - Misra, Anmol

hardening Android and developingsecure applications for the Androidplatform.

9.1 Android in Enterprise

From an enterprise perspective,there are di erent ways of lookingat Android in the environment,with the main being the followingthree: deploying Android devices,developing Android applications,and the implications of allowingAndroid applications in theenvironment.

The deployment of Androiddevices and applications isprimarily an IT function, whereas

Page 649: Android Security - Misra, Anmol

developing secure Androidapplications is part of eitherdevelopment/engineering teams orIT-development teams.

9.1.1 Security Concerns forAndroid in Enterprise

As we discussed in Chapter 1,today’s mobile devices, includingAndroid cell phones, are evolvingat a rapid rate in terms ofhardware and software features.

Our assessment of threats, aswell as security controls, has notkept up with the evolution of thesefeatures. These devices, we wouldargue, need more protection due to

Page 650: Android Security - Misra, Anmol

the features available on them, aswell as the proliferation of threatsto them. Before such devices can bedeployed in an enterprise (orapplications developed), it isessential that we carefully considerthreats to mobile devices, as wellas to enterprise resources arisingfrom mobile devices (and users).This can be done using a threatmodel. In threat modeling, weanalyze assets to protect, threats tothese assets, and resultingvulnerabilities. We proposeappropriate security controls tomitigate these threats andvulnerabilities.

Page 651: Android Security - Misra, Anmol

As covered brie y in Chapter 4,Android su ers from traditionalsecurity concerns, similar to anyother mobile OS. We expand onthem here and include ones weintentionally left out in thatdiscussion. The following aresecurity concerns that areapplicable to Android mobiledevices(http://csrc.nist.gov/publications/drafts/800-124r1/draft_sp800-124-rev1.pdf):

1. Lack of physical control ofdevices

2. Use of untrusted mobiledevices

Page 652: Android Security - Misra, Anmol

3. Use of untrusted connectionsand networks

4. Use of untrusted applications5. Connections and interactions

with other systems6. Use of untrusted content7. Use of location services8. Lack of control on the

patching of applications andthe OS

Lack of Physical Control ofDevices

Mobile devices are physically underthe control of end users (not system

Page 653: Android Security - Misra, Anmol

administrators or securityprofessionals). The fact that adevice is with the user pretty muchall the time increases the risk ofcompromise to an enterprise’sresources. From shoulder sur ng tothe actual loss of the physicaldevice, threats arise from the lackof physical control of these devices.Mobile devices are more likely tobe lost, stolen, or are temporarilynot within the user’s immediatereach or view. Enterprise securityshould assume that once stolen orlost, these devices could fall intomalicious hands, and thus securitycontrols to prevent disclosure of

Page 654: Android Security - Misra, Anmol

sensitive data must be designedwith this assumption.

Considering the worst-casescenario in which a lost or a stolendevice falls into malicious hands,the best way to prevent furtherdamage will be to encrypt themobile device (if the storing ofsensitive data is allowed) or notallowing devices to access sensitiveinformation (not really possiblewith Android smartphones). Toprevent shoulder sur ng, it mightbe prudent to use privacy screens(yes, there are ones for phones). Inaddition, a screen lock (requiring apassword/PIN) should be a

Page 655: Android Security - Misra, Anmol

requirement for using thesedevices, if access to enterpriseresources is desired. The bestpractice would be to authenticateto a di erent application each timeone uses it, although this is tedious,and, most likely, users will notadhere to this (imagine logginginto the Facebook application onan Android device every time oneuses it).

Use of “User-Owned” UntrustedDevices

Many enterprises are following aBYOD (bring your own device)

Page 656: Android Security - Misra, Anmol

model. This essentially means thatusers will bring their own mobiledevice (which they purchase) anduse it to access company resources.This poses a risk because thesedevices are untrusted (and notapproved) by enterprise security,and one has to rely on end usersfor due diligence. Thus, theassumption that all devices areessentially untrusted is not far-fetched.

Security policies need to beenforced even if these devices areowned by the users. In addition,these devices and applications onthem need to be monitored. Other

Page 657: Android Security - Misra, Anmol

solutions include providingenterprise devices (which have ahardened OS and preapprovedapplications and security policies)or allowing user-owned devices,with sensitive resources beingaccessed through well-protectedsandboxed applications.

Connecting to “Unapproved andUntrusted Networks”

Mobile devices have multiple waysto connect: cellular connectivity,wireless, Bluetooth connections,Near Field Communication (NFC),and so forth. An enterprise should

Page 658: Android Security - Misra, Anmol

assume that any or all of thesemeans of connectivity are going tobe employed by the end user. Theseconnectivity options enable manytypes of attacks: sni ng, man-in-the-middle, eavesdropping, and soforth. An example of such an attackwould be the end user connectingto any available (and open) Wi-Finetwork and thus allowing anattacker to eavesdrop oncommunications (if not protected).

Making sure communications areauthenticated before proceedingand then encrypted can e ectivelymitigate risk from this threat.

Page 659: Android Security - Misra, Anmol

Use of Untrusted Applications

This essentially replicates theproblem on desktop/laptopcomputers. End users are free toinstall any application they chooseto download. Even if the device isowned and approved by anenterprise, users are likely toinstall their own applications(unless prevented by the securitypolicy for the device). For Android,a user can download applicationsfrom dozens of application marketsor just download an application othe Internet.

There are several options for

Page 660: Android Security - Misra, Anmol

mitigating this threat. Anenterprise can either prohibit useof third-party applications throughsecurity policy enforcement orthrough acceptable use policyguidelines. It can create a whitelistof applications that users areallowed to install and use if theywould like to access companyresources through their Androiddevices. Although this mightprevent them from installing anapplication (e.g., Facebook), theymight still be able to use thisapplication through other means(e.g., browser interface). The moste ective mitigating step here is

Page 661: Android Security - Misra, Anmol

educating the end user, along withpolicy enforcement. Themonitoring of devices is anotherstep that can be taken.

Connections with “Untrusted”Systems

Mobile devices synchronize datato/from multiple devices andsources. They can be used to synce-mails, calendars, pictures, music,movies, and so forth.Sources/destinations can be theenterprise’s desktops/laptops,personal desktops/laptops,websites, and increasingly, these

Page 662: Android Security - Misra, Anmol

days, cloud-based services. Thus,one can assume any data on thedevice might be at risk.

If the device is owned by theenterprise, security policies on thedevice itself can be enforced toprevent it from backing up orsynchronizing to unauthorizedsources. If the user owns thedevice, awareness and monitoring(and maybe sandbox applications)are the way to go.

Unknown Content

There can be a lot of untrustedcontent on mobile devices (e.g.,

Page 663: Android Security - Misra, Anmol

attachments, downloads, QuickResponse (QR) codes, etc.). Manyof these will be from questionableor unknown sources and can poserisks to user and enterprise data.Take, for example, QR codes. Therecan be malicious URLs ordownloads hidden throughout thesecodes, but the user might not beaware of these, thus falling victimto an attack.

Installing security software (anti-virus) might mitigate some risk.Disabling the camera is anotheroption to prevent attacks such asthose on QR codes. Awareness,however, is the most e ective

Page 664: Android Security - Misra, Anmol

solution here.

Use of GPS (location-relatedservices)

Increasingly, mobile devices arebeing used as a navigation deviceas well as to nd “information”based on location. Manyapplications increasingly rely onlocation data provided through GPScapabilities in mobile devices.From Facebook to yelp, the user’slocation is being used to facilitateuser experience. This has adownside, aside from privacyimplications. Location information

Page 665: Android Security - Misra, Anmol

can be used to launch targetedattacks or associate users’ activitiesbased on their location data.

Disabling the GPS is one way tomitigate the risk. However, this isnot possible for BYOD devices.Another possibility is to educateusers on the implications of usinglocation data. Policies preventingsome applications (e.g., socialmedia applications) to use locationinformation can also beimplemented through policyenforcement.

Lack of Control of PatchingApplications and OS

Page 666: Android Security - Misra, Anmol

This is an especially acute problemin BYOD environments. Users canbring their own devices and maynot patch or update theirOS/applications for security xesthat become available, thusexposing enterprise resources tosecurity risks. Think of all thedi erent Android versions (from2.2.21 to 4.x) in your environmenttoday and the potential securityrisks for each of them. Usersprobably have not upgraded orkept up-to-date with security xesfor Android itself. In addition,many users don’t installapplication updates.

Page 667: Android Security - Misra, Anmol

Monitoring the devices andtrying to ascertain informationabout the respective versions oftheir OS/applications can provideinformation that can be use to agout insecure OS/applications. Userscan then be forced to eitherupgrade or risk losing access toenterprise resources.

9.1.2 End-User Awareness

Any strategy for securing mobiledevices or enterprise resourcesbeing accessed through mobiledevices must include end-usertraining. Users should be madeaware of the risks (listed above)

Page 668: Android Security - Misra, Anmol

and understand why securitycontrols are necessary. Adhering tothese controls should be part ofacceptable-use policy, and usersshould be required to review this atleast annually. In addition, annualsecurity-awareness training and afollow-up quiz might imbibe someof these best practices in theirminds. Secure awareness should becomplemented by warning userswhen they are about to perform anunwarranted action (e.g., accessunwanted site, download maliciouscode, etc.).

9.1.3 Compliance/Audit

Page 669: Android Security - Misra, Anmol

Considerations

Enterprise security needs to bedemonstrated to customers,auditors, and other stakeholders.Increasingly, mobile devices are anintegral part of the “computinginfrastructure” of an enterprise andare thus probed in depth byauditors. Although current securitycerti cations (standards) have notkept up with threats to mobiledevices, they do require that basicsecurity practices be applied tomobile devices (and applicationsdeveloped for mobile devices).Failing to secure your mobiledevices/infrastructure can risk

Page 670: Android Security - Misra, Anmol

audit ndings and nes, in manycases (depending onregulation/standards).

ISO 27002 is a widely usedsecurity standard published by theISO/IEC body. It lists 39 controlobjectives and 130+ securitycontrols for securing an enterpriseenvironment. Many of thesecontrols directly or indirectlyprovide guidance to securingmobile devices, data, andapplications on them. Control 9.2.5addresses physical securityconcerns, control 10.8.1 addressesinformation exchange, and control11.7.1 speci cally mandates

Page 671: Android Security - Misra, Anmol

security policy and measures thataddress threats from mobiledevices.

In addition to the controlsmentioned above, many othercontrols are applicable to mobiledevices. Examples of such controlswould be regular patching, securityscanning, hardening,cryptography, and so forth. Thecontrol objective, “Informationsystems acquisition, developmentand maintenance,” requires thatsecurity be taken into accountwhile developing informationsystems and applications. Codingbest practices (input validation,

Page 672: Android Security - Misra, Anmol

output encoding, error checking,etc.) is covered as part of thisobjective. Other standards (NIST800-53, PCI DSS) have similarrequirements for protecting mobiledevices. At the core, thesestandards mandate performingregular assessment of threats onmobile assets, identify securityissues, and implement controls, aswell as educate end users anddevelopers.

9.1.4 Recommended SecurityPractices for MobileDevices

Page 673: Android Security - Misra, Anmol

Security controls can be dividedinto four main categories:

1. Policies and restrictions onfunctionality: Restrict the userand applications fromaccessing various hardwarefeatures (e.g., camera, GPS),push con gurations forwireless, Virtual PrivateNetwork (VPN), sendlogs/violations to remoteserver, provide a whitelist ofapplications that can be used,and prevent rooted devicesfrom accessing enterpriseresources and networks.

Page 674: Android Security - Misra, Anmol

2. Protecting data: This includesencrypting local and externalstorage, enabling VPNcommunications to accessprotected resources, and usingstrong cryptography forcommunications. This alsoshould include a remote wipefunctionality in the case of alost or stolen device.

3. Access controls: This includesauthentication for using thedevice (e.g., PIN, SIMpassword) and per-applicationpasswords. A PIN/Passcodeshould be required after thedevice has been idle for few

Page 675: Android Security - Misra, Anmol

minutes (the recommendationis 2–5 minutes).

4. Applications: This includesapplication-speci c controls,including approvedsources/markets from whichapplications can be installed,updates to applications,allowing only trustedapplications (digitally signedfrom trusted sources) to beinstalled, and preventingservices to backup/restorefrom public cloud-basedapplications.

9.2 Hardening Android

Page 676: Android Security - Misra, Anmol

In the previous section, wereviewed common threats tomobile devices and some of themitigation steps one can take. Inthis section, we will cover in detailhow to con gure (harden) anAndroid device to mitigate therisks. We divide this section intotwo: hardening Android devices bycon guration changes (hardening)and developing Androidapplications that are secure.

9.2.1 Deploying Android Securely

Out of the box, Android does notcome with all desired con gurationsettings (from a security

Page 677: Android Security - Misra, Anmol

viewpoint). This is especially truefor an enterprise environment.Android security settings haveimproved with each major releaseand are fairly easy to con gure.Desired con guration changes canbe applied either locally or can bepushed to devices by ExchangeActiveSync mail policies.Depending on the devicemanufacturer, a device might haveadditional (manufacturer or third-party) tools to enhance security.

Unauthorized Device Access

As mentioned earlier in the

Page 678: Android Security - Misra, Anmol

chapter, lack of physical control ofmobile devices is one of the mainconcerns for a user and for anenterprise. The risk arising out ofthis can be mitigated to a certainextent through the followingconfiguration changes:

Setting Up a Screen Lock

After enabling this setting, a user isrequired to enter either a PIN or apassword to access a device. Thereis an option to use patterns,although we do not recommend it.To enable this setting, go to“Settings” -> “Security” -> “Screen

Page 679: Android Security - Misra, Anmol

Lock” and choose between the“PIN” and “Password” option. Werecommend a strong password oran 8-digit PIN (see Figure 9.1).Once “Screen Lock” is enabled, theautomatic timeout value should beupdated as well (Figure 9.2)

Setting up the SIM Lock

Turning on the “SIM card lock”makes it mandatory to enter thiscode to access “phone”functionality. Without this code,one would not be able to makecalls or send SMS messages. Toenable SIM lock, go to “Settings” -

Page 680: Android Security - Misra, Anmol

> “Set up SIM card lock” (seeFigures 9.3 and 9.4) and enable“Lock SIM card.” Pick a value thatis different from the screen lock.

Page 681: Android Security - Misra, Anmol
Page 682: Android Security - Misra, Anmol

Figure 9.1 Enabling Screen Lock

Remote Wipe

System administrators can enablethe “Remote Wipe” functionthrough Exchange ActiveSync mailpolicies. If a user is connected tothe corporate Exchange server, it iscritical to enable this feature incase the device is lost or stolen.There are other settings that can bepushed as well (e.g., passwordcomplexity). These are coveredlater in this chapter.

Remote Wipe essentially wipesout all data from the phone and

Page 683: Android Security - Misra, Anmol

restores it to factory state. Thisincludes all e-mail data,application settings, and so forth.However, it does not deleteinformation on external SDstorage.

Other Settings

In addition to the above settings,we strongly recommend disablingthe “Make passwords visible”option. This will prevent shouldersur ng attacks, as characters won’tbe repeated back on screen if youare typing a password or PIN. Goto “Settings” and uncheck “Make

Page 684: Android Security - Misra, Anmol

passwords visible” (see Figure 9.5).

Page 685: Android Security - Misra, Anmol
Page 686: Android Security - Misra, Anmol

Figure 9.2 Automatic Lock Timeout Value

Page 687: Android Security - Misra, Anmol
Page 688: Android Security - Misra, Anmol

Figure 9.3 Enable SIM Card Lock

It is also recommended to disable“Allow installation of apps fromunknown sources.” As we havementioned before, there aresecondary application stores apartfrom Google Play, and it is prudentto not trust applications from thesesources before ascertaining theirauthenticity. Disabling this optionwill prevent applications frombeing installed from other sources(see Figure 9.5).

As a rule of thumb, it isrecommended to turn o servicesthat are not being used. A user

Page 689: Android Security - Misra, Anmol

should turn o “Bluetooth,” “NFC,”and “Location features” unlessusing them actively (see Figure9.6), as well as the “Networknoti cation” feature from the Wi-Fisettings screen (see Figure 9.7).This will make the user choose aconnection rather than connectingto any available network.Discourage backing up of data to“Gmail or Google” accounts orDropbox. Create a whitelist ofapplications and educate users onthe list so they do not installapplications outside of theapproved list.

Page 690: Android Security - Misra, Anmol
Page 691: Android Security - Misra, Anmol

Figure 9.4 Enter SIM Card Lock PIN

Page 692: Android Security - Misra, Anmol
Page 693: Android Security - Misra, Anmol

Figure 9.5 Disabling “Make Passwords Visible”and “Unknown Sources”

Figure 9.6 Disabling “Location Services”

Page 694: Android Security - Misra, Anmol

Figure 9.7 Disabling “Network Notification”

Page 695: Android Security - Misra, Anmol

A new feature of Android 4.2enhances protection againstmalicious applications. Android 4.2has a feature that, if enabled,veri es an application beinginstalled with Google. Dependingon the risk of the application,Android warns users that it ispotentially harmful to proceed withthe installation. Note that somedata is sent to Google to enablethis process to take place (log,URL, device ID, OS, etc.). To turnon this feature, go to “Settings” ->“Security” -> “Verify Apps.”

Another useful feature might beto enable “Always on VPN.” This

Page 696: Android Security - Misra, Anmol

prevents applications fromconnecting to the network unlessVPN is on. We also recommendturning o the USB debuggingfeature from phones (see Figure9.8). USB debugging allows a userto connect the phone to an adbshell. This can lead to theenumeration of information on thedevice.

Browser is one of the mostcommonly used applications onAndroid devices. Browser securityand privacy settings should be ne-tuned (e.g., disable locationaccess). Figure 9.9 shows securitysettings for the screen browser.

Page 697: Android Security - Misra, Anmol
Page 698: Android Security - Misra, Anmol

Figure 9.8 Disabling “USB Debugging”

Page 699: Android Security - Misra, Anmol
Page 700: Android Security - Misra, Anmol

Figure 9.9 Browser Security Settings

Encryption

Android 3.0 and later have thecapability to perform full-diskencryption (this does not includethe SD card). Turning this featureon encrypts all data on the phone.In case the phone is lost or stolen,data can not be recovered becauseit is encrypted. The caveat here isthat the screen lock password hasto be the same as encryptionpassword. Once the phone isencrypted, during boot time youwill be required to enter this

Page 701: Android Security - Misra, Anmol

password to decrypt the phone.To turn on encryption, prepare

your phone by going through thefollowing steps:

1. Set up a strong PIN orpassword

2. Plug in and charge your phone

Once ready to encrypt thephone, go to “Settings” ->“Security” -> “Encrypt Phone.”Enable “Encrypt phone” and entera lock screen password or PIN.Once the encryption process iscomplete, you will be required todecrypt your phone at boot time by

Page 702: Android Security - Misra, Anmol

entering the screen lock passwordor PIN. Figure 9.10 shows the“Encrypt phone” screen from thesecurity settings.

9.2.2 Device Administration

The Android Device AdministrationAPIs have been available sinceAndroid 2.2. These APIs allowsecurity-aware enterpriseapplications to be developed.

Page 703: Android Security - Misra, Anmol

Figure 9.10 Encrypt Phone

Page 704: Android Security - Misra, Anmol

The built-in e-mail applicationleverages this API to improveExchange support and enablesadministrators to enforce certainsecurity settings, such as remotewipe, screen lock, time out,password complexity, andencryption. Mobile DeviceManagement (MDM) applicationsfrom third-party providers leveragethese APIs.

System administrators ordevelopers write security-awareapplications leveraging these APIs.Such an application can enforce alocal or remote security policy.Policy can be either hard coded in

Page 705: Android Security - Misra, Anmol

an application (local) or can befetched from a remote server (e.g.,E-mail Exchange server—see Figure9.11). Typically, such anapplication will need to beinstalled by users from Google Playor another installation medium. Inthe case of e-mail, a default e-mailapplication comes preinstalled, andthus it is easiest to push securitypolicies through this application ifthe devices are to sync/connect toa corporate Exchange server. Oncethe application is installed (orcon gured, in the case of e-mail),the system prompts the user toenable the device admin

Page 706: Android Security - Misra, Anmol

application. If the user consents,security policies are enforced goingforward, and if he or she does not,the user won’t be able to usecertain functionality (i.e., connectto corporate resources, sync withExchange server).

Page 707: Android Security - Misra, Anmol

Figure 9.11 E-mail Application Pushing Server

Page 708: Android Security - Misra, Anmol

Specified Policies

Below are some of the policiessupported by DeviceAdministration APIs. These policiescan be enforced by the deviceadmin application.

- Password enabled- Minimum password length- Strength/complexity of

passwords- Password expiry- Password history restrictions- Screen lock timeout- Storage encryption

Page 709: Android Security - Misra, Anmol

- Remote wipe

Page 710: Android Security - Misra, Anmol
Page 711: Android Security - Misra, Anmol

Figure 9.12 Policies Pushed through the E-mailApplication

Figure 9.12 shows policiespushed by the e-mail application.This is typical policy enforcementin a corporate environment.

9.3 Summary

In this chapter, we rst reviewedsecurity concerns for deployingmobile devices in an enterpriseenvironment and how to mitigatethem. We then walked throughAndroid security settings thatenable us to mitigate some of therisk. Finally, we concluded by

Page 712: Android Security - Misra, Anmol

looking at the DeviceAdministration API mechanism thatcan be used to enforce securitypolicies on Android devices.

Page 713: Android Security - Misra, Anmol

Chapter 10Browser Security andFuture Threat Landscape

In this chapter, we review HTMLand browser security on mobiledevices. We cover different types ofattacks possible, as well as browservulnerabilities. We then discusspossible advanced attacks usingmobile devices.

10.1 Mobile HTML Security

The increasing adoption of mobiledevices and their use as a means to

Page 714: Android Security - Misra, Anmol

access information on the Web hasled to the evolution of websites.Initially, mobile browsers had toaccess information throughtraditional (desktop-focused)websites. Today most of thesewebsites also support WirelessApplication Protocol (WAP)technology or have an equivalentmobile HTML (trimmed-down sitesfor mobile devices).

WAP speci cation de nes aprotocol suite that enables theviewing of information on mobiledevices. The WAP protocol suite iscomposed of the following layers(Figure 10.1): Wireless Datagram

Page 715: Android Security - Misra, Anmol

Protocol (WDP), WirelessTransport Layer Security (WTLS),Wireless Transaction Protocol(WTP), Wireless Session Protocol(WSP), and Wireless ApplicationEnvironment (WAE). The protocolsuite operates over any wirelessn e twork . Table 10.1 describesdi erent layers in the protocolsuite.

In a typical Internet or WWWmodel, there is a client that makesa request to a server. The serverprocesses the request and sends aresponse (or content) back to theclient (see Figure 10.2). This ismore or less same in the WAP

Page 716: Android Security - Misra, Anmol

model, as well. However, there is agateway or proxy that sits betweenthe client and the server thatadapts the requests and responses(encodes/decodes) for mobiledevices (see Figure 10.3). WAP 2.0provides support for richer contentand end-end security than WAP1.0.

Page 717: Android Security - Misra, Anmol
Page 718: Android Security - Misra, Anmol

Figure 10.1 WAP Protocol Suite

WAP 1.0 did not provide end-endsupport for SSL/TLS. In WAP 1.0,communications between a mobiledevice and WAP gateway could beencrypted using WTLS. However,these communications wouldterminate at the proxy/gatewayserver. Communications betweenthe gateway and application/HTTPserver would use TLS/SSL. Thisexposed WAP 1.0 communicationsto MITM (Man-In-The-Middle)attacks. In addition, all kinds ofsensitive information would beavailable on the WAP gateway (inplaintext). This meant that a

Page 719: Android Security - Misra, Anmol

compromise of the WAPgateway/proxy could result in asevere security breach. WAP 2.0remediates this issue by providingend-end support for SSL/TLS.

WAP and Mobile HTML sites arealso susceptible to typical Webapplication attacks, includingCross-Site Scripting, SQL Injection,Cross-Site Request Forgery, andPhishing. Mobile browsers are fullyfunctional browsers withfunctionality that rivals desktopversions. They include support forcookies, scripts, ash, and so forth.This means that users of mobiledevices are exposed to attacks

Page 720: Android Security - Misra, Anmol

similar to those on desktop/laptopcomputers. We will cover theseattacks brie y. A good source fordetailed information on theseattacks is the Open WebApplication Security Project(OWASP) website.

Table 10.1 – WAP Protocols

Layer Description

Wireless

Lowest layer in thesuite. Providesunreliable data toupper layers (i.e.,

Page 721: Android Security - Misra, Anmol

DatagramProtocol(WDP)

the UDP) andfunctions somewhatlike the transportlayer. Runs on topof bearers, includingSMS, CSD, CDPD,and so forth

WirelessTransportLayerSecurity(WTLS)

Provides public-keycryptographysecurity mechanisms

Page 722: Android Security - Misra, Anmol

WirelessTransactionProtocol(WTP)

Provides transactionreliability support(i.e., reliablerequests andresponses)

WirelessSessionProtocol(WSP)

Provides HTTPfunctionality

Provides WirelessMarkup Language(WML), WMLScript,

Page 723: Android Security - Misra, Anmol

WirelessApplicationEnvironment(WAE)

and WTA (WirelessTelephonyApplicationInterface). WML is amarkup languagelike HTML,WMLScript is ascripting languagelike JavaScript, andWTA providessupport for phonefunctionality

Page 724: Android Security - Misra, Anmol

Figure 10.2 WWW Model

Figure 10.3 WAP Model

10.1.1 Cross-Site Scripting

Cross-Site Scripting (XSS) allowsthe injection of client-side scriptinto web pages and can be used byattackers to bypass access controls.XSS attacks can result in attackers

Page 725: Android Security - Misra, Anmol

obtaining the user’s sessioninformation (such as cookies). Theycan then use this information tobypass access controls. Figure 10.4shows re ected XSS in a vulnerablewebsite accessed through theAndroid browser.

At the heart of XSS attacks is thefact that untrusted user input is notthoroughly vetted and is usedwithout sanitization/escaping. Inthe case of XSS, user input is notsanitized for and is then eitherdisplayed back to the browser(re ected XSS) or stored (persistentXSS) and viewed later.

Mobile sites are as prone to XSS

Page 726: Android Security - Misra, Anmol

attacks as their regularcounterparts, as mobile HTML sitesmight have even less controlsaround validating/sanitizing userinput. Treating mobile HTML siteslike regular websites andperforming proper validation ofuser input can prevent a site frombeing vulnerable to XSS attacks.

Page 727: Android Security - Misra, Anmol

Figure 10.4 Example of XSS on Mobile Device

10.1.2 SQL Injection

SQL injection allows the injection

Page 728: Android Security - Misra, Anmol

of an SQL query from a client intoan application. A successful SQLquery (or attack) can provideattackers with sensitiveinformation and enable them tobypass access controls, runadministrative commands, andquery/update/delete databases.

At the heart of SQL injectionattacks is the fact that untrusteduser input is directly used incrafting SQL queries withoutvalidation. These SQL queries arethen executed against the backenddatabase.

Similar to XSS, mobile HTML andWAP sites are prone to SQL

Page 729: Android Security - Misra, Anmol

injection attacks. Mobile sitesmight have the same aws as theirdesktop counterparts, or, evenworse, they might not beperforming the validation of userinput when accepting inputsthrough mobile sites. Usingparameterized queries or storedprocedures can prevent SQLinjection attacks.

10.1.3 Cross-Site Request Forgery

A Cross-Site Request Forgery(CSRF, XSRF) attack results inunwanted (unauthorized)commands from a user alreadyauthenticated to a website. The

Page 730: Android Security - Misra, Anmol

website trusts an authenticateduser and, therefore, commandscoming from him, as well. In CSRF,the website is the victim of the trustin the user, whereas in XSS, theuser is the victim of the trust in theserver/website.

It is typical for a user to beauthenticated to multiple websiteson a mobile device. Thus, CSRFattacks are possible, just as theyare on desktop/laptop computers.In addition, small interface and UIlayouts can disguise CSRF attacks(e.g., an e-mail with a URL link)and trick the user into performingunwanted operations on a website.

Page 731: Android Security - Misra, Anmol

10.1.4 Phishing

Phishing attacks targetunsuspecting users and trick theminto providing sensitiveinformation (e.g., SSN, passwords,credit card numbers, etc.). Throughsocial engineering, attackers trickusers to go to legitimate-lookingwebsites and perform certainactivities. Users trusting the sourcefor this request (e.g., typically inan e-mail) performs therecommended operation and, inturn, provides an attacker withsensitive data.

As an example, a user gets an e-

Page 732: Android Security - Misra, Anmol

mail that seems legitimate andlooks like it came from his bank. Itis requesting the user to change hispassword due to a recent securitybreach at the bank. For hisconvenience, the user is providedwith a URL to change hispassword. On clicking the link, theuser is taken a website that lookslike the bank’s website. The userperforms the password-resetoperation and, in turn, providesthe current password to theattacker.

Such attacks are even moredi cult for users to recognize onmobile devices. Due to small UI

Page 733: Android Security - Misra, Anmol

real estate, users can’t really readthe entire URL that they areviewing. If they are beingredirected to a website, they wouldnot be able to tell it easily on amobile device. Di erences betweenlegitimate and fake websites arenot easy to distinguish on a smallUI screen of mobile devices. IfURLs are disguised (e.g., tiny URL)or if these are URLs that are sentthrough a Short Message Service(SMS) message (tiny URL via SMS),it is even more di cult todistinguish between legitimate andfake requests. Many users (evenones who are aware of such

Page 734: Android Security - Misra, Anmol

attacks) can be tricked into goingthrough with an attack. Asmentioned in the previous chapter,Quick Response (QR) codes canalso be used for such attacks.

10.2 Mobile Browser Security

In this section, we review recentbrowser vulnerabilities on Androidplatforms, as well as drive-by-download attacks.

10.2.1 Browser Vulnerabilities

As of the writing of this chapter,there are ~200+ CommonVulnerabilities and Exposures(CVEs) related to the Android

Page 735: Android Security - Misra, Anmol

platform (search cve.mitre.org for“android”). Of these, many arerelated to browsers (either built-inbrowsers or downloadablebrowsers, such as Firefox). Table10.2 describes the following CVEs:CVE 2008-7298, CVE 2010-1807,CVE 2010-4804, CVE 2011-2357,and CVE 2012-3979, as well astheir descriptions, as depicted onthe NIST website(http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE).

CVE 2008-7298 can result inattackers modifying or deletingcookies; CVE 2010-1807 can allowattackers to execute arbitrary code

Page 736: Android Security - Misra, Anmol

or cause application crashes; CVE2010-4804 could cause informationleakage on an SD Card; CVE 2011-2357 can cause an XSS attack; andCVE 2012-3979 can cause codeexecution. If we look at computerbrowser vulnerabilities, we see thatvulnerabilities found on mobilebrowsers are of a similar nature.Often, mobile applicationdevelopment does not followestablished Security DevelopmentLifecycle (SDL) processes, and theyare treated as “plug-ins” orapplications with lesser relevance.This can result in one or morecontrols (e.g., threat modeling,

Page 737: Android Security - Misra, Anmol

static and dynamic analysis,penetration testing, code review)not being applied to mobileapplication development.

Table 10.2 – Examples ofBrowser-Related Vulnerabilitiesof Android Devices

Vulnerability Description

The Android browserin Android cannotproperly restrictmodifications tocookies established in

Page 738: Android Security - Misra, Anmol

CVE 2008-7298

HTTPS sessions, whichallows man-in-the-middle attackers tooverwrite or deletearbitrary cookies via aSet-Cookie header inan HTTP response.This is due to the lackof the HTTP StrictTransport Security(HSTS) enforcementWebKit in Apple Safari4.x before 4.1.2 and

Page 739: Android Security - Misra, Anmol

CVE 2010-1807

5.x before 5.0.2;Android before 2.2;and webkitgtk before1.2.6. Does notproperly validatefloating-point data,which allows remoteattackers to executearbitrary code or causea denial of service(application crash) viaa crafted HTMLdocument, related to

Page 740: Android Security - Misra, Anmol

nonstandard NaNrepresentation

CVE 2010-4804

The Android browserin Android before2.3.4 allows remoteattackers to obtain SDcard contents viacrafted content://URIs, related to (1)BrowserActivity.javaand (2)BrowserSettings.javain

Page 741: Android Security - Misra, Anmol

com/android/browser/Cross-applicationscripting vulnerabilityin the Browser URLloading functionalityin Android 2.3.4 and3.1 allows localapplications to bypassthe sandbox andexecute arbitraryJavascript in arbitrarydomains by (1)causing the MAX_TAB

Page 742: Android Security - Misra, Anmol

CVE 2011-2357

number of tabs to beopened, then loading aURI to the targeteddomain into thecurrent tab, or (2)making twostartActivity functioncalls beginning withthe targeted domain’sURI followed by themalicious Javascriptwhile the UI focus isstill associated with

Page 743: Android Security - Misra, Anmol

the targeted domain

CVE 2012-3979

Mozilla Firefox before15.0 on Android doesnot properlyimplement unspecifiedcallers ofthe—android_log_print

function, which allowsremoteattackers toexecute arbitrary codevia a crafted web pagethat calls theJavaScript dump

Page 744: Android Security - Misra, Anmol

function

Source:http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE (vulnerabilitydescriptions from NVD list).

Drive-by Downloads

Drive-by downloads have been anissue with computers for sometime. However, we are starting tosee them as an emerging threat onmobile devices, as well. A drive-bydownload is basically malware thatgets downloaded and ofteninstalled when a user visits an

Page 745: Android Security - Misra, Anmol

infected website.Recently, we saw the rst drive-

by download malware for Android(named “NonCompatible”). Whenvisiting an infected website, thebrowser could download thismalware le. However, it can’tinstall itself without userintervention. In addition,installation from non-trustedsources needs to be enabled for theuser to install this malware. Anattacker can disguise such adownload by renaming it as apopular Android application orupdates to Android itself. Users arewilling to install such les without

Page 746: Android Security - Misra, Anmol

much thought and, thus, end upinfecting their devices withmalware.

As long as “side loading” andinstallation of applications from“non-trusted” sources is disabled,such malware should not be able toimpact Android devices.

10.3 The Future Landscape

Thus far, we have coveredvulnerabilities that have beenwidely exploited or can beexploited today. In this section, wetalk about possible attacks onAndroid devices in the near future.Note that these attacks cannot be

Page 747: Android Security - Misra, Anmol

executed by amateurs and wouldrequire planning, execution, andresources probably available toorganized crime, state, andintelligence agencies. Althoughscenarios in this section seemfuturistic, in reality, they are verypossible and for the future, quiteprobable. We now present thefollowing scenarios—using a phoneas a spying/tracking device,controlling corporate networks andother devices through mobiledevices, and exploiting Near FieldCommunication (NFC) on mobiledevices.

Page 748: Android Security - Misra, Anmol

10.3.1 The Phone as aSpying/Tracking Device

Imagine exploiting vulnerabilitieson an Android device orapplication and gaining full accessto a phone. Rooted Android phonesare most vulnerable to these kindsof attacks. One can potentiallyturn a phone into a tracking andspying device. Consider thefollowing functionalities that canbe potentially exploited: thecamera and photos, GPS co-ordinates, the microphone, e-mailand chat information, social mediainformation (location ofrestaurants, places of interest),

Page 749: Android Security - Misra, Anmol

medical information (e.g., hospitaland clinics visited, doctors searchedor met), medicines looked upthrough the device, and so forth.

One could argue that anexploited smartphone could be thebest tracker/spy that one can get,as it will provide you with everylittle bit of information to piecetogether the daily routines of usersand people around them. A usernot aware of such a compromisewould carry it willingly and sowould a malicious user who isintentionally using the device as atracking/spying mechanism.Smartphones are preferred devices

Page 750: Android Security - Misra, Anmol

for organized crime, criminals,terrorists, and law enforcementagencies alike. Given the thingsyou can accomplish using thesedevices, they can also be a greattool for law enforcement. All ofthis should raise concerns for atypical user in terms of securityand privacy.

10.3.2 Controlling CorporateNetworks and OtherDevices through MobileDevices

Exploiting vulnerabilities onmobile applications or the Androidplatform itself can lead to other

Page 751: Android Security - Misra, Anmol

security concerns. Besides being acorporate espionage tool, it can beused to launch attacks againstcorporate resources and evencontrol corporate informationsystems.

As we have already seen,corporations do not really controlAndroid devices purchased andowned by users. Most companiesdo not require the hardening ofthese devices to the extent thatthey should. The patching ofapplications and platforms is notsomething that securityadministrators always control in aBYOD world. All of this has very

Page 752: Android Security - Misra, Anmol

signi cant implications forinformation resources in acorporate environment. The factthat these devices are not coveredby typical security controls (e.g.,security scans, patching, incidentresponse) adds to the risk. Rooteddevices can expose not only theuser but also the environment tosecurity attacks. With all kind ofapplications available on Android(e.g., Wireshark), as well as thepossibly of writing customapplications to launch securityattacks, one can imagine theheadaches security professionalswill have dealing with these

Page 753: Android Security - Misra, Anmol

devices in their environments. In adi erent scenario, more and morehome appliances and systems arecontrolled through mobile devices.A vulnerable or exploited Androiddevice can be used to attack theseappliances and devices.

10.3.3 Mobile Wallets and NFC

We brie y covered NFC in Chapter7 and discussed Google Walletvulnerability. Increasingly,retailers and banks are looking touse NFC for processing payments.Although still in its infancy,concerns have been raised aboutprivacy and security issues using

Page 754: Android Security - Misra, Anmol

NFC for mobile walletfunctionality. In addition toconcerns around secure NFCapplications, there are other issueswith such a mechanism, such aseavesdropping, interception, andloss of control. NFC is essentially aradio communication, and it ispossible to eavesdrop oncommunication, if in range. NFC islimited in range compared toRadio-Frequency Identi cation(RFID), although it is possible toamplify this using an antenna.Assuming that communication issecure (encrypted), it is stillpossible to perform tra c analysis.

Page 755: Android Security - Misra, Anmol

Another issue is the possibility of alost/stolen phone, in which case allof the user’s bank and credit cardinformation can be at risk(including corporate cards).Although users might be eager toadopt this feature, they often do sowithout having an understandingof the risk or best practices theyneed to follow.

NFC is not only used forpayment processing. The recentlylaunched Samsung Galaxy S III usesNFC to transfer contents from onedevice to another, seamlessly, byplacing the devices back-to-back.Although this is a user-friendly

Page 756: Android Security - Misra, Anmol

feature, it can have seriousimplications for security, includingdata security. Imagine that datacan be directly sent to devices thatare even beyond the control ofsecurity administrators.

10.4 Summary

In this chapter, we reviewedmobile HTML security (includingWAP). We covered typical attackspossible on mobile websites. Wethen walked through browservulnerabilities and drive-bydownloads. We then coveredpossible advanced attacks throughmobile devices.

Page 757: Android Security - Misra, Anmol

Appendix A

I n Chapter 4, we discussedManifest permissions that arerequested by applications forperforming operations such asaccessing the Internet, sending SMSmessages, and so forth. We haverated these permissions based ontheir security implications.Permission to access SMS messagesor install packages is rated higherin terms of security implications(severity) than permission to accessbattery statistics. The table below

Page 758: Android Security - Misra, Anmol

shows the assigned score andseverity/risk rating.

Score Description/Risk

4 Critical

3 High

2 Medium

1 Information Disclosure

Table A.1 comprises acomprehensive list of Android“Manifest Permissions.” It containsa description as well as the riskrating assigned to each permissionlisted.

Page 759: Android Security - Misra, Anmol

Table A.1 – Manifest Permissions

Permission Name

ACCESS_CHECKIN_PROPERTIES

ACCESS_COARSE_LOCATION

Page 760: Android Security - Misra, Anmol

ACCESS_FINE_LOCATION

ACCESS_LOCATION_EXTRA_COMMANDS

ACCESS_MOCK_LOCATION

ACCESS_NETWORK_STATE

Page 761: Android Security - Misra, Anmol

ACCESS_SURFACE_FLINGER

ACCESS_WIFI_STATE

ACCOUNT_MANAGER

ADD_VOICEMAIL

Page 762: Android Security - Misra, Anmol

AUTHENTICATE_ACCOUNTS

BATTERY_STATS

BIND_ACCESSIBILITY_SERVICE

BIND_APPWIDGET

Page 763: Android Security - Misra, Anmol

BIND_DEVICE_ADMIN

BIND_INPUT_METHOD

BIND_REMOTEVIEWS

BIND_TEXT_SERVICE

Page 764: Android Security - Misra, Anmol

BIND_VPN_SERVICE

BIND_WALLPAPER

BLUETOOTH

Page 765: Android Security - Misra, Anmol

BLUETOOTH_ADMIN

BRICK

BROADCAST_PACKAGE_REMOVED

BROADCAST_SMS

Page 766: Android Security - Misra, Anmol

BROADCAST_STICKY

BROADCAST_WAP_PUSH

CALL_PHONE

Page 767: Android Security - Misra, Anmol

CALL_PRIVILEGED

CAMERA

CHANGE_COMPONENT_ENABLED_STATE

Page 768: Android Security - Misra, Anmol

CHANGE_CONFIGURATION

CHANGE_NETWORK_STATE

CHANGE_WIFI_MULTICAST_STATE

CHANGE_WIFI_STATE

Page 769: Android Security - Misra, Anmol

CLEAR_APP_CACHE

CLEAR_APP_USER_DATA

CONTROL_LOCATION_UPDATES

DELETE_CACHE_FILES

DELETE_PACKAGES

Page 770: Android Security - Misra, Anmol

DEVICE_POWER

DIAGNOSTIC

DISABLE_KEYGUARD

DUMP

EXPAND_STATUS_BAR

Page 771: Android Security - Misra, Anmol

FACTORY_TEST

FLASHLIGHT

FORCE_BACK

GET_ACCOUNTS

Page 772: Android Security - Misra, Anmol

GET_PACKAGE_SIZE

GET_TASKS

GLOBAL_SEARCH

HARDWARE_TEST

Page 773: Android Security - Misra, Anmol

INJECT_EVENTS

INSTALL_LOCATION_PROVIDER

INSTALL_PACKAGES

Page 774: Android Security - Misra, Anmol

INTERNAL_SYSTEM_WINDOW

INTERNET

KILL_BACKGROUND_PROCESSES

MANAGE_ACCOUNTS

MANAGE_APP_TOKENS

Page 775: Android Security - Misra, Anmol

MASTER_CLEAR

MODIFY_AUDIO_SETTINGS

MODIFY_PHONE_STATE

MOUNT_FORMAT_FILESYSTEMS

MOUNT_UNMOUNT_FILESYSTEMS

Page 776: Android Security - Misra, Anmol

NFC

PERSISTENT_ACTIVITY

Page 777: Android Security - Misra, Anmol

PROCESS_OUTGOING_CALLS

READ_CALENDAR

READ_CALL_LOG

READ_CONTACTS

READ_EXTERNAL_STORAGE

READ_FRAME_BUFFER

Page 778: Android Security - Misra, Anmol

READ_HISTORY_BOOKMARKS

READ_INPUT_STATE

READ_LOGS

Page 779: Android Security - Misra, Anmol

READ_PHONE_STATE

READ_PROFILE

READ_SMS

READ_SOCIAL_STREAM

READ_SYNC_SETTINGS

Page 780: Android Security - Misra, Anmol

READ_SYNC_STATS

READ_USER_DICTIONARY

REBOOT

RECEIVE_BOOT_COMPLETED

Page 781: Android Security - Misra, Anmol

RECEIVE_MMS

RECEIVE_SMS

RECEIVE_WAP_PUSH

RECORD_AUDIO

Page 782: Android Security - Misra, Anmol

REORDER_TASKS

RESTART_PACKAGES

SEND_SMS

SET_ACTIVITY_WATCHER

Page 783: Android Security - Misra, Anmol

SET_ALARM

SET_ALWAYS_FINISH

SET_ANIMATION_SCALE

SET_DEBUG_APP

Page 784: Android Security - Misra, Anmol

SET_ORIENTATION

SET_POINTER_SPEED

SET_PREFERRED_APPLICATIONS

SET_PROCESS_LIMIT

Page 785: Android Security - Misra, Anmol

SET_TIME

SET_TIME_ZONE

SET_WALLPAPER

SET_WALLPAPER_HINTS

SIGNAL_PERSISTENT_PROCESSES

Page 786: Android Security - Misra, Anmol

STATUS_BAR

SUBSCRIBED_FEEDS_READ

SUBSCRIBED_FEEDS_WRITE

SYSTEM_ALERT_WINDOW

Page 787: Android Security - Misra, Anmol

UPDATE_DEVICE_STATS

USE_CREDENTIALS

USE_SIP

VIBRATE

WAKE_LOCK

Page 788: Android Security - Misra, Anmol

WRITE_APN_SETTINGS

WRITE_CALENDAR

WRITE_CALL_LOG

WRITE_CONTACTS

Page 789: Android Security - Misra, Anmol

WRITE_EXTERNAL_STORAGE

WRITE_GSERVICES

WRITE_HISTORY_BOOKMARKS

WRITE_PROFILE

Page 790: Android Security - Misra, Anmol

WRITE_SECURE_SETTINGS

WRITE_SETTINGS

WRITE_SMS

WRITE_SOCIAL_STREAM

Page 791: Android Security - Misra, Anmol

WRITE_SYNC_SETTINGS

WRITE_USER_DICTIONARY

Page 792: Android Security - Misra, Anmol

Appendix B: JEBDisassembler andDecompiler Overview

I n Chapters 6 and 7, we showedhow to decompile and reverseengineer Android apps withdi erent open source tools. InAppendix B we are going to do aquick overview of JEB. JEB is anAndroid app disassembler anddecompiler. It can handle APK orDEX les. The analyses can besaved to JDB files.

Page 793: Android Security - Misra, Anmol

The workspace is divided intofour areas, as seen in Figure B.1:

1 - The menu and toolbar, at thetop

2 - The console window andstatus bar, at the bottom

3 - The class hierarchy browser4 - A tab folder consisting of

many important subviews

B.1 Views

Within a workspace, viewsrepresenting portions of theanalyzed le are contained withinthe tab folder (4). The views can be

Page 794: Android Security - Misra, Anmol

closed and reopened via theWindows menu. Here is a list ofcommon views:

• The Assembly view. This viewcontains the disassembly codeof all classes contained in theDEX le. This view isinteractive. The assembly canbe exact Smali or simpli edDalvik assembly for improvedclarity.

Page 795: Android Security - Misra, Anmol
Page 796: Android Security - Misra, Anmol

Figure B.1 JEB Main Window

• The Decompiled view. Thisview contains the decompiledbyte-code of a class, in Java.Switching back and forth withthe assembly view can bedone by pressing the Tab key,while the caret is positionedon a class.

• The Strings view. This viewcontains the list of stringspresent in the DEX le.Double-clicking on a stringswitches back to the assemblyview and positions the careton the rst occurrence in

Page 797: Android Security - Misra, Anmol

which the string is being used.• Th e Constants view. This

view contains a list ofnumerical constants present inthe DEX le. Double-clickingon a constant switches back tothe assembly view andpositions the caret on the rstoccurrence in which theconstant is being used.

• The Manifest view. This viewrepresents the decompressedmanifest of the application.

• Th e Resources view. Thistree view allows the user toexplore the applications

Page 798: Android Security - Misra, Anmol

decompressed resources.• The Assets view. This view is

very similar to the Resourcesview and is used to browse anassets files.

• The Certificates view. Thisview o ers a human-readablerepresentation of thecerti cates used to sign theAPK.

• The ExternalClasses/Methods/Fieldsview. These views list theexternal (outside the DEX le)classes, methods, and eldsreferenced and used within the

Page 799: Android Security - Misra, Anmol

DEX file.• The Notes view. This view is

a placeholder for analysisnotes.

The class hierarchy view (3)contains the entire list of classespresent in the DEX le. Classes areorganized by package.

Clicking or double-clicking on aclass name will bring up theAssembly view and position thecaret on the chosen class.

For the sake of clarity, the usermay decide to temporarily maskinner classes by marking the

Page 800: Android Security - Misra, Anmol

appropriate checkbox at thebottom of the tree.

B.2 Code Views

The assembly and decompiled codeviews are the most crucial viewswhen it comes to analyzing anapp. These code views areinteractive and work hand-in-hand.

Both views contain interactiveitems: they can be classes, elds,methods, opcodes, instructions,comments, and so forth.

When users set the focus oneither one of these views, they can:

Page 801: Android Security - Misra, Anmol

• Rename items (N): Classes,elds, and methods can be

renamed. Changes arere ected in the other view. Inthe decompiled view,variables and parameters canalso be renamed. Externalitems (those not de ned in theDEX file) cannot be renamed.

• Insert comments (C):Comments may be speci c toa class, a eld, a method, or aspeci c method instruction.Comments can be text, audio,or both. Audio comments aredenoted by a bang character(!) prepended to the optional

Page 802: Android Security - Misra, Anmol

text comment.• Examine cross references (X):

Most interactive items can becross-referenced to see wherethey are used. The cross-references are listed by orderof appearance in the code.Double-click a cross-referenceto jump to its location.

• Navigate (Enter): A user can“follow” items. In in thiscontext, it means jumping tothe de nition of that item. Forinstance, following a methodcall to foo() means jumping tothe location where foo() isdefined.

Page 803: Android Security - Misra, Anmol

From the assembly view, theuser can decide to decompile aclass by pressing Tab. The currentview will switch to the decompiledview for the target class, and thecaret will be positioned on theclosest high-level Java item thatmatches the source byte-codeinstruction. Conversely, whenpositioning the caret on a high-level Java item and switching backto the assembly view, JEB tries toposition the caret on the low-levelbyte-code instruction that mostclosely matches the source Javastatement.

Page 804: Android Security - Misra, Anmol

B.3 Keyboard Shortcuts

Keyboard shortcuts (see Table B.1)can be used within the code views.For improved productivity, it ishighly recommended to use them.Experienced reverse-engineers willrecognize the shortcuts used bystandard disassembler tools.

B.4 Options

The Edit/Options menu allowsusers to customize various aspectsand styles of JEB. The options aregrouped into various categories(general/speci c to the assemblyview, speci c to the code view,

Page 805: Android Security - Misra, Anmol

etc.), and most of them are self-explanatory, as can be seen inFigure B.2.

T h e show debug directives/linenumbers options show the speci cmetadata in the assembly code. Theuser should be aware that suchmetadata can be easily forged, andtherefore, should not be trusted.

T h e keep Smali compatibilityoption will try to produce assemblycode compliant with Smali.Compliance in this context means,for instance, invoke instructionswith parameters rst, fullyquali ed method names and classnames, speci c switch structure,

Page 806: Android Security - Misra, Anmol

and so forth. By disabling the Smalicompatibility, a user can greatlyimprove the readability of theassembly code.

Table B.1 Keyboard ShortcutsAvailable within Code View

Shortcut Description

Tab

Decompile a class (whenin assembly view) /Switch back to assembly(when in decompiledview)

Rename an internal

Page 807: Android Security - Misra, Anmol

N item (class, field,method, variable)

C (orSlash)

Insert a comment

X

Examine the cross-references of aninteractive item (xrefscan be double-clickedand followed)

EnterFollow an interactiveitem

Go back to the previous

Page 808: Android Security - Misra, Anmol

Escape caret position in thefollow-history

Ctrl-Enter

Go forward to the nextcaret position in thefollow-history

F5Refresh/synchronize thecode view

Page 809: Android Security - Misra, Anmol
Page 810: Android Security - Misra, Anmol

Figure B.2 JEB Options

Figure B.3 JEB Code Style Manager

Style options include fontselection (which a ect variousviews) and color styles.

Page 811: Android Security - Misra, Anmol

The default font is set to astandard xed font, usually CourierNew. This may vary from system tosystem. Recent versions of CourierNew have a good amount ofUnicode glyphs. However, yoursmay not have the CJK glyphs,which are essential when dealingwith Asian locale apps. Should thathappen, other fonts may be used,such as Fang Song on Windows, orSans on Ubuntu. These fonts o ergood BMP support, including CJK,Russian, Thai, and Arabic.

The “Style manager” buttonallows the user to customize colorsand aspects of various interactive

Page 812: Android Security - Misra, Anmol

items. This a ects the code viewsas well as the XML views used torender the manifest and other XMLresources. Foreground andbackground colors as well as fontattributes for interactive items canbe customized (see Figure B.3).

Page 813: Android Security - Misra, Anmol

Appendix C: Cracking theSecureApp.ApkApplication

In this appendix, we detail how amalicious user can reverse engineerand modify the behavior of aparticular application. In Chapter7, we showed this using theSecureApp.apk application as oneof many ways in which a malicioususer can achieve this. In thistutorial, we will demonstrate a fewways in which a malicious user can

Page 814: Android Security - Misra, Anmol

modify an application’s behavior toadd or remove functionality.

Due to the hands-on nature ofthis exercise, this appendix isavailable on the book’s website—www.androidinsecury.com—inthe Chapters section. All lesrelated to this exercise areavailable in the Resource section ofthe website. You will need thefollowing credentials to access thefiles under the Resource section.

Username: androidPassword: 1439896461

Page 815: Android Security - Misra, Anmol

Glossary

Chapter 1

A5/1 Encryption A stream cipherused to provide over-the-aircommunication privacy in the GSMcellular telephone.(http://en.wikipedia.org/wiki/A5/1_encryption_algorithm

AOSP Android Open Source Project

OHA Open Handset Alliance

Chapter 2

Page 816: Android Security - Misra, Anmol

/etc/shadow le Used to increasethe security level of passwords byrestricting all but highly privilegedusers’ access to hashed passworddata.(http://en.wikipedia.org/wiki/Shadow_(file)

Abstract Window Toolkit (AWT)Java’s platform-independentwindowing graphics and user-interface widget toolkit.

Android Development Tools(ADT) A plug-in for Eclipse IDE todevelop Android applications.

API Application ProgrammingInterface

Page 817: Android Security - Misra, Anmol

Daemon A computer program thatruns as a background process.(http://en.wikipedia.org/wiki/Daemon_(computing)

Dalvik Debug Monitor Service(DDMS) A debugging tool thatprovides port forwarding services.(http://developer.android.com/tools/debugging/ddms.html

SDK Software Development Kit

Chapter 3

Broadcast Receivers Enableapplications to receive intents thatare broadcast by the systems ofother applications.

Page 818: Android Security - Misra, Anmol

Intents Messages through whichother application components(activities, services, and BroadcastReceivers) are activated.

Chapter 4

IMEI International MobileEquipment Identity

IMSI International MobileSubscriber Identity

IPC Interprocess Communication

MAC Mandatory Access Controlrefers to a type of access control bywhich the operating system

Page 819: Android Security - Misra, Anmol

constrains the ability of a subject toperform some sort of operation onan object.(http://en.wikipedia.org/wiki/Mandatory_access_control

Superuser A user account used forsystem administration.

TAN Tax Deduction AccountNumber

Chapter 5

JNI Java Native Framework, whichenables Java code running in aJava Virtual Machine to call and becalled by native applications.(http://en.wikipedia.org/wiki/JNI)

Page 820: Android Security - Misra, Anmol

OS Fingerprinting A passivecollection of con gurationattributes from a remote device.(http://en.wikipedia.org/wiki/TCP/IP_stack_fingerprinting

OSSTMM Open Source SecurityTesting Methodology Manual

Pen Testing Penetration testing isa method of evaluating the securityof a computer system by simulatingan attack from malicious outsiders.(http://en.wikipedia.org/wiki/Pen_testing

RPC Remote procedure call is aninter-process communication thatallows a computer program tocause a function to execute in

Page 821: Android Security - Misra, Anmol

another address space.(http://en.wikipedia.org/wiki/Remote_procedure_call

Static Analysis The analysis ofcomputer software that isperformed without actuallyexecuting programs.(http://en.wikipedia.org/wiki/Static_program_analysis

SYN Scan In this type of scanning,the SYN packet is used for portscans.

Chapter 6

AndroidManifest An Androidmanifest le provides essentialinformation the system must have

Page 822: Android Security - Misra, Anmol

before it can run any of theapplication code.(http://developer.android.com/guide/topics/manifest/manifest-intro.html)

APK Android Application PackageFile

apktool A tool to reverse engineerAndroid apps.

BOT Application A proof-of-concept Android applicationwritten by the authors todemonstrate security issues withthe Android OS.

CnC A central server for a BOT

Page 823: Android Security - Misra, Anmol

network which issues commands toall BOT clients.

Cute Puppies Wallpaper Anapplication developed by theauthors for analysis.

Decompile Process of convertingexecutable binary to a higher levelprogramming language.

DEX Dalvik Executable Format

dex2jar A tool to work withAndroid .dex and java .class les.(http://code.google.com/p/dex2jar/

Inter-process Communication A

Page 824: Android Security - Misra, Anmol

set of methods for the exchange ofdata among one or more processes.(http://en.wikipedia.org/wiki/Inter-process_communication)

jar Java Archive; an aggregate ofmany Java class files.

jd-gui A standalone graphicalutility that displays Java sourcecode .class les.(http://java.decompiler.free.fr/?q=jdgui)

Key Logger An application thatcan log keys pressed by the user.The key logger can be legitimate,but more often than not, most key

Page 825: Android Security - Misra, Anmol

logger applications are maliciousin nature.

Malware Short for malicious (ormalevolent) software, is softwareused or created by attackers todisrupt computer operation.(http://en.wikipedia.org/wiki/Malware

Reverse Engineering The processof discovering the technologicalprinciples of a device, object, orsystem through analysis of itsstructure, function, or operation.(http://en.wikipedia.org/wiki/Reverse_engineering

Chapter 7

Page 826: Android Security - Misra, Anmol

Access Control Refers to exertingcontrol over who can interact witha resource.(http://en.wikipedia.org/wiki/Access_control

Assembler Creates object code bytranslating assembly instructionmnemonics into opcodes.(http://en.wikipedia.org/wiki/Assembly_language

Baksmali A dissembler for dexformat used by Dalvik.

Brute Force Problem-solvingmethods involving the evaluationof every possible answer forfitness.(http://en.wikipedia.org/wiki/Brute_force

Page 827: Android Security - Misra, Anmol

Byte Code Also know as a p-code;a form of instruction set designedfor e cient execution by asoftware interpreter.(http://en.wikipedia.org/wiki/Bytecode

dexdump Android SDK utility todump disassembled dex files.

Disassembler Translates machinelanguage into assembly language.

Disk Encryption A technology thatprotects information by convertinginformation into unreadable code.(http://en.wikipedia.org/wiki/Disk_encryption

Google Wallet An app on the

Page 828: Android Security - Misra, Anmol

Android platform that stores userscredit and debit card informationfor online purchases on theAndroid platform.

Hash Functions An algorithm thatmaps large data sets of variablelength to smaller data sets of a

xed length.(http://en.wikipedia.org/wiki/Hash_function

NFC Near Field Communication

Obfuscation The hiding ofintended meaning incommunication makingcommunication confusing,ambiguous, and harder to

Page 829: Android Security - Misra, Anmol

interpret.(http://en.wikipedia.org/wiki/Obfuscation

ProGuard The proguard toolshrinks, optimizes, and obfuscatesAndroid application code byremoving unused code andrenaming classes, elds, andmethods with obscure names.(http://developer.android.com/tools/help/proguard.html

Rainbow Tables A precomputedtable for reversing cryptographichash functions for crackingpassword hashes.(http://en.wikipedia.org/wiki/Rainbow_table

RFID Radio Frequency

Page 830: Android Security - Misra, Anmol

Identification

“salt” Used in cryptography tomake it harder to decryptencrypted data by hashingencrypted data.

SHA-256 A 256-bit SHA hashalgorithm.

Signapk An open source utility tosign Android application packages.(http://code.google.com/p/signapk/

Smali An assembler for dex formatused by Dalvik.

SQlite A relational database

Page 831: Android Security - Misra, Anmol

management system contained in asmall C programming library.(http://en.wikipedia.org/wiki/SQLite

Chapter 8

adb Also known as Android DebugBridge; a command line tocommunicate with an Androidemulator/device.

ext2 Second extended le system isa file system for Linux kernel.

ext3 Third extended le system is afile system for Linux kernel.

ext4 Fourth extended le system is

Page 832: Android Security - Misra, Anmol

a file system for Linux kernel.

Gingerbreak An Androidapplication to root the AndroidGingerbread version.

MOBILedit MOBILedit is a digitalforensics tool for cell phonedevices.

nodev A Linux partition optionthat prevents having specialdevices on set partitions.

Rooting A process for allowingusers of smartphones, tablets, andother devices to attain privilegedcontrol.

Page 833: Android Security - Misra, Anmol

(http://en.wikipedia.org/wiki/Android_rooting

Seesmic A cross-platformapplication that allows users tosimultaneously manage useraccounts for multiple socialnetworks.(http://en.wikipedia.org/wiki/Seesmic

vfat An extension that can work ontop of any FAT file system.

Virtual File System (VFS) Allowsclient applications to accessdi erent types of concrete lesystems in a uniform way.(http://en.wikipedia.org/wiki/Virtual_file_system

Page 834: Android Security - Misra, Anmol

YAFFS (Yet Another Flash FileSystem) The rst version of this

le system and works on NANDchips that have 512 byte pages.(http://en.wikipedia.org/wiki/YAFFS

YAFFS2 (Yet Another Flash FileSystem) The second version ofYAFFS partition.

Chapter 9

Acceptable Use Policy (AUP) Aset of rules applied by the owner ofa network that restrict the ways inwhich the network, website orsystem may be used.(http://en.wikipedia.org/wiki/Acceptable_use_policy

Page 835: Android Security - Misra, Anmol

Bluetooth A wireless technologystandard for exchanging data overshort distances.(http://en.wikipedia.org/wiki/Bluetooth

BYOD Bring Your Own Device

Exchange ActiveSync (EAS) AnXML-based protocol thatcommunicates over HTTP (orHTTPS) designed forsynchronization of email, contacts,calendar, and notes.(http://en.wikipedia.org/wiki/Exchange_ActiveSync

Google Play Formerly known asthe Android Market; a digitalapplication distribution platform

Page 836: Android Security - Misra, Anmol

for Android developed andmaintained by Google.(http://en.wikipedia.org/wiki/Google_Play

Hardening Usually the process ofsecuring a system by reducing itssurface of vulnerability.(http://en.wikipedia.org/wiki/Hardening_(computing)

IEC International ElectrotechnicalCommission

ISO 27001-2 An informationsecurity standard published by theInternational Organization forStandards (ISO).(http://en.wikipedia.org/wiki/ISO/IEC_27002

Page 837: Android Security - Misra, Anmol

Man-in-the-Middle (MITM) Aform of active eavesdropping inwhich the attacker makesindependent connections with thevictims and relays the messagesbetween them.(http://en.wikipedia.org/wiki/Man-in-the-middle)

Near Field Communication (NFC)A set of standards for devices toestablish radio communication witheach other by touching themtogether or bringing them intoclose proximity.(http://en.wikipedia.org/wiki/Near_field_communication

Page 838: Android Security - Misra, Anmol

NIST 800-53 RecommendedSecurity Controls for FederalInformation Systems andOrganizations.(http://en.wikipedia.org/wiki/NIST_Special_Publication_800-53)

Patching A security patch is achange applied to an asset tocorrect the weakness described by avulnerability.(http://en.wikipedia.org/wiki/Patch_(computing)#Security_patches

Payment Card Industry DataSecurity Standard (PCI DSS) Aninformation security standard fororganizations that handle

Page 839: Android Security - Misra, Anmol

cardholder information for majorcredit/debit cards.(http://en.wikipedia.org/wiki/PCI_DSS

Remote Wipe Ability to delete allthe data on a mobile devicewithout having physical access tothe device.

Shoulder Sur ng Refers to usingdirect observation techniques, suchas looking over someone’sshoulder, to get information.(http://en.wikipedia.org/wiki/Shoulder_surfing_(computer_security)

SP800-124 A National Institute ofStandards & Technology (NIST)standard that makes

Page 840: Android Security - Misra, Anmol

recommendations for securingmobile devices.(http://csrc.nist.gov/publications/nistpubs/800-124/SP800-124.pdf)

Whitelist A list or register ofentities that, for one reason oranother, are being provided aparticular privilege, service,mobility, access or recognition.(http://en.wikipedia.org/wiki/Whitelist

Chapter 10

CSRF/XSRF Cross-Site RequestForgery

Drive-by Downloads Any

Page 841: Android Security - Misra, Anmol

download that happens without aperson’s knowledge; often acomputer virus, spyware, ormalware.(http://en.wikipedia.org/wiki/Drive-by_download)

HTML Hyper Text MarkupLanguage

OWASP An open-sourceapplication security project.

Phishing The act of attempting toacquire information bymasquerading as a trustworthyentity.(http://en.wikipedia.org/wiki/Phishing

Page 842: Android Security - Misra, Anmol

QR Code (Quick Response Code)The trademark for a type of matrixbarcode.(http://en.wikipedia.org/wiki/QR_code

SQLi SQL Injection

WAE Wireless ApplicationEnvironment

WAP Wireless Application Protocol

WDP WAP Datagram Protocol

WML Wireless Markup Language

WSP Wireless Session Protocol

Page 843: Android Security - Misra, Anmol

WTA Wireless TelephonyApplication

WTLS Wireless Transport LayerSecurity

WTP Web Tools platform

XSS Cross-Site Scripting

Page 844: Android Security - Misra, Anmol

Index

/data/data, 73, 74, 172, 173, 176–178, 181, 183

/etc/shadow, 18

Access Control List (ACL), 98ACL. See Access Control Listactivity, 3, 27, 28, 39–43, 47–51,

53, 57, 61–70, 78, 86, 100,124, 128, 196, 217

activity lifecycle, 49, 61–70adb, 22, 28, 31, 35, 38, 78, 79, 81,

Page 845: Android Security - Misra, Anmol

82, 101, 170, 172, 180, 181,183, 206

ADB. See Android Debug BridgeADT. See Android Development

Toolsanalyze, 1, 39, 90, 99, 100, 103,

119, 121–125, 128, 144,147, 148, 150, 161, 170,176, 180, 181, 183, 187, 194

Android architecture, 17, 71, 97,169

Android attack, 88Android BOT, 119Android Debug Bridge (ADB), 22,

28, 31, 35, 38, 78, 79, 81,

Page 846: Android Security - Misra, Anmol

82, 101, 170, 172, 180, 181,183, 206

Android Development Tools (ADT),28, 31, 33, 35, 37

Android kernel, 18, 25Android Manifest, 51, 223Android marketplace, 13, 16, 77,

120Android Open Source Project

(AOSP), 11Android Package files (APK), 35,

43, 75, 76, 78, 83, 88, 107,108, 125, 148, 150, 153,155, 156, 160–163, 180, 181

Android releases, 11, 12, 18, 20

Page 847: Android Security - Misra, Anmol

Android runtime, 17, 26, 79, 80, 83Android SDK, 17, 28–31, 35, 36,

46, 149Android stack, 17–19, 31Android start up, 28, 43AOSP. See Android Open Source

ProjectAPK. See Android Package filesApktool, 107, 123, 124, 150, 153,

155, 156, 161application-based attack, 9application components, 47, 51,

60, 70, 71application framework, 17, 25–27application security, 87, 113, 116,

Page 848: Android Security - Misra, Anmol

118, 216assembly, 233, 235, 236, 238

attack surface, 5, 9, 20, 106

Bluetooth, 4, 21, 195, 203BotWorker, 125, 132, 134, 136–141bring your own device (BYOD),

195–197, 221broadcast, 51, 57, 58, 70, 86, 107Broadcast Receiver, 51, 57, 58, 70,

107browser vulnerability, 213, 218,

222brute force, 117, 155, 162, 167Burp Suite, 110

Page 849: Android Security - Misra, Anmol

BusyBox, 100–102BYOD. See bring your own device

callbacks, 49, 61CDMA, 10, 88cloud, 117, 118CnC. See Command and Control

Centercode, 11, 18, 21, 22, 25, 35, 39,

41–43, 49, 50, 58–60, 63,72, 88, 90, 91, 97, 99, 100,103, 106, 109, 113, 117,118, 120–122, 125, 129, 139,147, 148, 150, 154, 155,163, 165, 166, 168, 183,196, 197, 199, 218, 233,

Page 850: Android Security - Misra, Anmol

235–238code obfuscation, 163, 168Command and Control Center

(CnC), 139, 144compliance, 193, 197compliance/audit considerations,

193content provider, 60, 70, 86controlling corporate networks,

220, 221Cross-Site Request Forgery (CSRF,

XSRF), 87, 217Cross-Site Scripting (XSS), 87, 117,

214, 216–218cryptography, 109, 114, 167, 168,

Page 851: Android Security - Misra, Anmol

198CSRF. See Cross-Site Request

ForgeryCutePuppiesWallpaper, 35, 125,

128, 130, 137

Dalvik Debug Monitoring Service(DDMS), 28, 31, 34–37, 170,175

Dalvik Virtual Machine (DVM), 11,17, 26, 28, 72, 125, 148

database, 99, 109, 117, 118, 162,168, 176–178, 183, 185, 187,217

data privacy, 87

Page 852: Android Security - Misra, Anmol

data storage, 117, 118DDMS. See Dalvik Debug

MonitoringServicedecompile, 107, 119, 125, 147,

148, 153, 161, 163, 235, 236decompiler, 125, 129, 233decompiling APK, 125defensive strategies, 163device access, 199device administration, 208, 210,

211API, 208, 210, 211DEX, 26, 107, 125, 128, 147–152,

233, 235, 236

Page 853: Android Security - Misra, Anmol

dexdump tool, 149DEX file format, 147, 148directory ownership, 74directory structure, 170, 172, 175disassembler, 150, 233, 236disk encryption, 168drive-by-download, 218DroidDream, 88, 89, 91variant, 88DVM. See Dalvik Virtual Machinedynamic analysis, 218

Eclipse, 28, 31, 33, 35, 37, 39, 43,163, 164, 170

Page 854: Android Security - Misra, Anmol

encryption, 9, 10, 87, 118, 168,207–210

end-user awareness, 197enterprise, 11, 98, 193–199, 208,

211error handling, 117ext2, 170external storage, 87, 91, 117, 198extracting data, 187

file system, 23, 35, 78, 167, 169,170, 173, 174, 181, 187, 191

flash, 215forensics, 100, 101, 148, 169

Page 855: Android Security - Misra, Anmol

GID. See group idGingerbreak, 180, 181Global Smartphone Sales, 4Google Wallet, 161, 168, 221GPS, 4, 9, 22, 86, 87, 139, 169,

196, 198, 220group id (GID), 21, 23, 72, 73, 79,

80, 83GSM, 10, 88

hacking, 169hardening Android, 193, 199hashing, 154, 167, 168Hello World, 39, 41–43, 149

Page 856: Android Security - Misra, Anmol

Honeycomb, 12HTML security, 213, 222

imaging Android, 181Intents, 48, 51–54, 57–61, 70, 97,

107, 124intercepting traffic, 110internal storage, 117, 118Interprocess Communication (IPC),

20, 25, 71, 73, 107, 114,124, 127, 128

investigation, 169, 181, 183IPC. See Interprocess

CommunicationISO 27002, 198

Page 857: Android Security - Misra, Anmol

iterative hashing, 167, 168

JD-GUI, 125, 128, 163, 165, 166

kernel version, 18, 20, 180keyboard, 87

Legacy Code, 88library, 17, 25, 26, 28, 29, 72, 100,

109, 116, 122, 162, 172Linux kernel, 11, 17, 18, 20, 21, 25,

26, 28, 43, 71, 72, 75, 79,94, 122, 170

LogCat, 25, 28, 35, 41–43, 45, 47,63

Page 858: Android Security - Misra, Anmol

malicious software, 87, 120, 121.See also malware

malware, 9–11, 88–90, 92, 93, 119–122, 144, 220. See alsomalicious software

man-in-the-middle (MITM), 91,195, 214

Manifest, 42, 50, 51, 54–60, 72, 75,76, 78, 83, 94, 107, 108,123, 223, 224, 226, 228,230, 232, 235, 238

Manifest Permissions, 72, 75, 76,78, 94, 107

MDM. See Mobile DeviceManagement

Page 859: Android Security - Misra, Anmol

MITM. See man-in-the-middlemkfs, 183mobile browser security, 218Mobile Device Management

(MDM), 209MOBILedit, 187–189mobile security issue, 86mobile threats, 5Mobile Wallets, 221mount points, 169–171, 187

NAND, 170native layer libraries, 25near field communication (NFC),

Page 860: Android Security - Misra, Anmol

10, 22, 161, 162, 195, 203,220–222

NFC. See near field communicationNIST 800-53, 198NIST 800-115, 99OHA. See Open Handset AllianceOnCreate, 41, 42, 49, 50, 59, 61–

63, 150onDestroy, 49, 59, 61, 62, 70OnPause, 49, 61–64OnRestart, 49, 61onResume, 49, 61–63OnStart, 49, 61–63onStop, 49, 61, 62, 64, 70

Page 861: Android Security - Misra, Anmol

Open Handset Alliance (OHA), 4,11

Package Manager, 27partitions, 170, 187patching, 86, 97, 116, 194, 197,

198, 221PCI DSS, 198penetration testing, 97, 99, 100,

106, 118, 218. See also pentesting

external, 98internal, 98pen testing, 97, 98, 101, 106, 109,

116, 118. See also

Page 862: Android Security - Misra, Anmol

penetration testingpermission, 20, 22, 23, 25, 51, 54,

57–60, 72, 73, 75–85, 87–95,97, 107–109, 114, 120, 122,123, 125, 126, 139, 162,167, 172, 176, 178, 180,183, 223, 224, 226, 228,230, 232

permission enforcement, 72persistent, 60, 173, 187, 216persistent XSS, 216phishing, 9, 87, 215, 217process ownership, 74ProGuard, 31, 35, 39, 40, 163, 164

Page 863: Android Security - Misra, Anmol

QR. See quick responsequick response (QR), 196, 218

rainbow tables, 167receiver, 51, 57, 58, 70, 107, 124,

139reflected XSS, 216remote wipe, 198, 200, 201, 209,

210reporting, 99, 116resource, 27, 43, 49, 51, 59, 61, 62,

70, 72, 100, 106, 107, 109,114, 116, 117, 121, 128,194–198, 210, 220, 221, 235,238

Page 864: Android Security - Misra, Anmol

reverse engineering, 119–121, 123,153, 163, 168

RFID, 10, 162, 222risk, 10, 14, 78, 86, 87, 100, 194–

197, 199, 206, 211, 221,222, 223

rooting, 10, 178, 180

salt, 155, 162, 167, 168screen lock, 194, 199, 200, 207–

210SDK. See Software Development KitSecureApp.apk, 153, 156security issue, 16, 86, 87, 97, 99,

106, 116, 118, 120, 198, 221

Page 865: Android Security - Misra, Anmol

security model, 71–73, 93, 94, 169,180

security practices, 88, 197, 198sensitive information, 9, 54, 87,

114, 116, 117, 121, 167,168, 177, 194, 214, 217

server side processing, 163, 167service, 3, 9, 10, 17, 27, 28, 31, 35,

47, 51, 58–60, 70, 75, 86,90, 98, 100, 101, 109, 119,124, 128, 137, 139, 194,196, 199, 203, 205, 218

session management, 116severity, 99, 113, 223

Page 866: Android Security - Misra, Anmol

shell, 17, 22, 24, 25, 35, 73, 78, 79,81, 82, 100, 101, 170, 172,176, 180, 182, 183, 206

Short Message Service (SMS), 9, 10,27, 72, 75, 76, 78, 80, 83,91, 93, 119, 136, 137, 139,169, 187, 190, 200, 218

SignApk tool, 160SIM card, 93, 199, 200, 202, 203SIM lock, 199, 200Skype vulnerability, 162Smali, 147, 148, 150, 154–158,

233, 236, 238smartphone, 1–5, 9, 86, 169, 194,

221

Page 867: Android Security - Misra, Anmol

SMS. See Short Message ServiceSoftware Development Kit (SDK),

17, 28–31, 34–36, 39, 46,149

spying, 220, 221spying/tracking device, 220SQL injection, 214, 217SQlite, 25, 117, 118, 162, 170, 177,

179, 183, 186browser, 183static analysis, 97–100, 118strings, 23, 39, 42, 43, 235strings.xml, 39, 42, 43Symbian, 3, 8, 91

Page 868: Android Security - Misra, Anmol

tool, 17, 25, 28, 29, 31, 33–36, 43,86, 98–100, 118, 119, 121,149, 160, 162, 181, 183,187, 199, 221

trojan, 90, 91, 121

UID. See user idunapproved networks, 195unknown content, 196unknown source, 14, 196, 202, 204untrusted application, 194, 195untrusted device, 195untrusted networks, 195untrusted systems, 196user id (UID), 40, 57, 72–75, 79,

Page 869: Android Security - Misra, Anmol

80, 167, 172, 180

verify apps, 206vfat, 170vulnerability, 97–99, 103, 109, 116,

161, 162, 168, 180, 194,213, 218–222

WAP. See Wireless ApplicationProtocol

WDP. See Wireless DatagramProtocol

Wireless Application Protocol(WAP), 213–215, 217, 222

Wireless Datagram Protocol

Page 870: Android Security - Misra, Anmol

(WDP), 213Wireless Transaction Protocol

(WTP), 213Wireshark, 100, 103–105, 113, 114,

221WTP. See Wireless Transaction

Protocol

XML, 22, 39, 42, 43, 54–60, 75, 76,80, 83, 85, 89, 92, 107, 123,124, 167, 177, 178, 238

XSRF. See Cross-Site RequestForgery

XSS. See Cross-Site Scripting

Page 871: Android Security - Misra, Anmol

Yaaic application, 113yaffey, 183, 184yaffs2, 170, 183

Zitmo, 91, 93–95Zsone, 90, 92zygote, 28, 43