testing and securing android studio applications and securing... · table of contents testing and...

281

Upload: dinhdat

Post on 18-Feb-2019

270 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 2: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 3: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TestingandSecuringAndroidStudioApplications

Page 4: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TableofContents

TestingandSecuringAndroidStudioApplications

Credits

AbouttheAuthors

AbouttheReviewers

www.PacktPub.com

Supportfiles,eBooks,discountoffers,andmore

Whysubscribe?

FreeaccessforPacktaccountholders

Preface

Whatthisbookcovers

Whatyouneedforthisbook

Whothisbookisfor

Conventions

Readerfeedback

Customersupport

Downloadingtheexamplecode

Errata

Piracy

Questions

1.IntroductiontoSoftwareSecurity

Softwaresecurityterms

Threats,vulnerabilities,andrisks

Threat

Vulnerability

Risk

Securecode-designprinciples

Testingthebasics

Summary

2.SecurityinAndroidApplications

Page 5: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Themobileenvironment

AnoverviewofAndroidsecurity

Permissions

Interapplicationcommunication

Intents

Contentproviders

Summary

3.MonitoringYourApplication

DebuggingandDDMS

Threads

Methodprofiling

Heap

AllocationTracker

NetworkStatistics

FileExplorer

EmulatorControl

SystemInformation

Summary

4.MitigatingVulnerabilities

Inputvalidation

SQLinjection

Permissions

Handlingauser’sdataandcredentials

Interapplicationcommunication

SecuringIntents

Securingthecontentproviders

Summary

5.PreservingDataPrivacy

Dataprivacy

Sharedpreferences

Filesintheinternalstorage

Page 6: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Filesintheexternalstorage

Thedatabasestorage

Encryption

Theencryptionmethods

Generatingakey

Usingencryptiontostoredata

Summary

6.SecuringCommunications

HTTPS

SSLandTLS

Serverandclientcertificates

Keytoolintheterminal

AndroidStudio

CodeexamplesusingHTTPS

Summary

7.AuthenticationMethods

Multifactorauthentication

Theknowledgefactor

Thepossessionfactor

Theinherencefactor

Loginimplementations

AccountManager

Summary

8.TestingYourApplication

TestinginAndroid

TestingtheUI

TheuiautomatorAPI

TheUiDeviceclass

TheUiSelectorclass

TheUiObjectclass

TheUiCollectionclass

Page 7: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TheUiScrollableclass

Theuiautomatorviewertool

TheUItestproject

RunningUItestcases

Summary

9.UnitandFunctionalTests

Testingactivities

Thetestcaseclasses

Instrumentation

Thetestcasemethods

TheAssertclassandmethod

TheViewAssertsclass

TheMoreAssertsclass

UItestingandTouchUtils

Themockobjectclasses

Creatinganactivitytest

Creatingaunittest

Theunittestsetup

Theclocktest

Thelayouttest

TheactivityIntenttest

Creatingafunctionaltest

Thefunctionaltestsetup

TheUItest

TheactivityIntenttest

Thestatemanagementtest

Gettingtheresults

Summary

10.SupportingTools

Toolsforunittesting

Spoon

Page 8: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Mockito

AndroidMock

FESTAndroid

Robolectric

Toolsforfunctionaltesting

Robotium

Espresso

Appium

Calabash

MonkeyTalk

Bot-bot

Monkey

Wireshark

Othertools

Genymotion

Summary

11.FurtherConsiderations

Whattotest

Networkaccess

Mediaavailability

Changeinorientation

Serviceandcontentprovidertesting

Developeroptions

Gettinghelp

Summary

Index

Page 9: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 10: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TestingandSecuringAndroidStudioApplications

Page 11: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 12: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TestingandSecuringAndroidStudioApplicationsCopyright©2014PacktPublishing

Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.

Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthors,norPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.

PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.

Firstpublished:August2014

Productionreference:1190814

PublishedbyPacktPublishingLtd.

LiveryPlace

35LiveryStreet

BirminghamB32PB,UK.

ISBN978-1-78398-880-8

www.packtpub.com

CoverimagebyRavajiBabu(<[email protected]>)

Page 13: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 14: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

CreditsAuthors

BelénCruzZapata

AntonioHernándezNiñirola

Reviewers

NicoKüchler

AnandMohan

RaviShanker

KevinSmith

AbhinavaSrivastava

CommissioningEditor

AmarabhaBanerjee

AcquisitionEditor

RebeccaYoué

ContentDevelopmentEditor

ParitaKhedekar

TechnicalEditor

MrunmayeePatil

CopyEditors

RoshniBanerjee

AdithiShetty

ProjectCoordinators

NehaThakur

AmeySawant

Proofreader

AmeeshaGreen

Indexers

MariammalChettiyar

RekhaNair

TejalSoni

PriyaSubramani

Page 15: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Graphics

RonakDhruv

ProductionCoordinator

ConidonMiranda

CoverWork

ConidonMiranda

Page 16: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 17: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

AbouttheAuthorsBelénCruzZapatareceivedherengineeringdegreeinComputerSciencefromtheUniversityofMurciainSpain,withspecializationinsoftwaretechnologiesandintelligentandknowledgetechnologies.ShehasearnedanMScdegreeinComputerScienceandisnowworkingonherPhDdegreeinSoftwareEngineeringResearchGroupfromtheUniversityofMurcia.

BelénisbasedinSpain;however,duetothefieldofherPhD,sheisnowcollaboratingwithUniversitéMohammedV-SoussiinRabat.Herresearchisfocusedonmobiletechnologiesingeneralandalsoappliestomedicine.

Belénhasworkedasamobiledeveloperforseveralplatforms,suchasAndroid,iOS,andtheWeb.SheistheauthorofthebookonAndroidStudio:AndroidStudioApplicationDevelopment,PacktPublishing.

Tofollowherprojects,shemaintainsablogathttp://www.belencruz.comandyoucanfollowheronTwitterat@belen_cz.

IwouldliketothankPacktPublishingforofferingmetheopportunitytowritethisbook.IwouldparticularlyliketothankParitaKhedekar,RebeccaYoué,andAmeySawantfortheirvaluablehelp.

IwouldalsoliketothankAntonio,theco-authorofthisbook,formakingeverythingsoeasy;mynewfriendsofadventure,especiallyPaloma,Camilla,andAdrián,fortheselastmonths;myfriendsfromwaybackforvisitingme;andfinally,myfamilyforsupportingme.

AntonioHernándezNiñirolahasanengineeringdegreeinComputerScienceandisamobileapplicationdeveloper.HewasbornandraisedinMurciainthesoutheastregionofSpainandiscurrentlylivinginRabat,Morocco.Hehasdevelopedseveralwebsitesandmobileapplications.

AftercompletinghisdegreeinComputerScience,hepursuedaMaster’sdegreeinTeacherTrainingforInformaticsandTechnology.AntoniopushedhisstudiesfurtherandisnowadoctoralcandidateundertheSoftwareEngineeringResearchGroupofthefacultyofComputerScienceattheUniversityofMurcia,andisactuallyaresearcherfortheUniversitéMohammedV-SoussiinRabat.

Youcanvisithiswebsiteathttp://www.ninirola.estofindoutmoreabouthimandhisprojects.

IwouldliketobeginbythankingRebeccaYoué,ParitaKhedekar,andAmeySawantfortheirvaluableinput.ThankyoutoeveryoneatPacktPublishingwhomakewritingabooksuchanenjoyableexperience.

ThankyouBelén,theotherhalfofthisbook,formakingeverythingmuchbetter.Iwouldfinallyliketothankmyfamilyfortheirsupport,mynewfriendsinMorocco,myoldfriendsinSpain,andeveryonewhohelpedmebewhoIamtoday.

Page 18: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 19: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

AbouttheReviewersNicoKüchlerlivesinBerlin,Germany.Hedidanapprenticeshipasamathematical-technicalsoftwaredeveloper.Hehasworkedforthegambleindustryandasanonlineshopprovider.HehasbeenworkingatDeutschePostE-POSTDevelopmentGmbHfor2yearswithinthescopeofAndroidappdevelopment.

Hehasbeenmaintainingaprojectthatprovidesaquickstartwithtest-drivenAndroidappdevelopmentathttps://github.com/nenick/android-gradle-template.

AnandMohanisageekandastart-upenthusiast.HegraduatedfromtheIndianInstituteofInformationTechnology,Allahabad,in2008.HehasworkedwithOracleIndiaPvt.Ltd.for4years.In2012,Anandstartedhisownventure,TripTern,alongwithhisfriends,whichisacompanythatalgorithmicallyplansoutthemostoptimizedtravelitineraryfortravelersbyutilizingBigDataandmachine-learningalgorithms.AtTripTern,AnandhasdevelopedandimplementedofflineAndroidapplicationssothattravelerscanmodifytheiritineraryonthegowithoutrelyingonanydataplan.

Apartfromworkingonhisstart-up,Anandalsolikestofollowthelatesttrendsintechnologyandbestsecuritypractices.

RaviShankerhasalwaysbeenfascinatedwithtechnology.He’sbeenapassionatepractitionerandanavidfollowerofthedigitalrevolution.HelivesinSydney,Australia.Helovestraveling,presenting,reading,andlisteningtomusic.Whennottinkeringwiththetechnology,healsowieldsasetofbrushesandpaletteofcolorstoputtherightsideofhisbraintowork.

Ravihashonedhisskillsoveradecadeindevelopment,consulting,andproductandprojectmanagementforstart-upstolargecorporationsinairline,transportation,telecom,media,andfinancialservices.HehasworkedintheUSA,UK,Australia,Japan,andmostofAsia-Pacific.Hehasalsorunacoupleofstart-upsofhisowninthepast.

Raviisoftenseenblogging,answeringoraskingquestionsonStackExchange,postingorupvoting,andtweetingonthelatestdevelopmentsindigitalspace.Hehasmadepresentationsatmeetingsandinterestgroupsandhasconductedtrainingclassesonvarioustechnologies.He’salwaysexcitedattheprospectofnewandinnovativedevelopmentsinimprovingthequalityoflife.

AbhinavaSrivastavahascompletedhisBachelorofTechnologydegreeinComputerScienceEngineeringfromIndiain2008andhasalsoreceivedaDiplomainWirelessandMobileComputingfromACTS,C-DAC,Indiain2009.

HestartedhiscareerasaSoftwareEngineeratPersistentSystemsbeforemovingtoSingapore,andiscurrentlyworkingwithMasterCard,Singapore.

Abhinavaisacoretechnologistbyheartandlovestoplaywithopensourcetechnologies.Hemaintainshisownblogathttp://abhinavasblog.blogspot.in/andkeepsjottinghisthoughtsfromtimetotime.

Iwouldliketothankmyfamilymembersfortheircontinuoussupport,especiallymyelder

Page 20: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

brother,AbhishekSrivastava,whohasbeenamentorandaninspiration.Lastbutnotleast,IwouldliketoextendmygratitudetoPacktPublishingforgivingmetheopportunitytobeapartofsuchawonderfulexperience.

Page 21: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 22: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

www.PacktPub.com

Page 23: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Supportfiles,eBooks,discountoffers,andmoreYoumightwanttovisitwww.PacktPub.comforsupportfilesanddownloadsrelatedtoyourbook.

DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusat<[email protected]>formoredetails.

Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeoffreenewsletters,andreceiveexclusivediscountsandoffersonPacktbooksandeBooks.

http://PacktLib.PacktPub.com

DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt’sonlinedigitalbooklibrary.Here,youcanaccess,readandsearchacrossPackt’sentirelibraryofbooks.

Page 24: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Whysubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,printandbookmarkcontentOndemandandaccessibleviawebbrowser

Page 25: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

FreeaccessforPacktaccountholdersIfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccessPacktLibtodayandviewnineentirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess.

Page 26: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 27: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

PrefaceMobileapplicationshavebecomeverypopularinthelastfewyearsthankstoahugeincrementintheuseofmobiledevices.Fromadeveloper’spointofview,Androidhasbecomeanimportantsourceofincomethankstothedifferentapprepositories,suchasGooglePlayandAmazonAppstore.

Withanincreaseinthenumberofapplicationsavailable,usershavebecomemoredemandingaboutthefeaturesoftheapplicationstheyaregoingtouse.Asolidtestingoftheapplicationanditssecurityaspectsarethekeyfactorsinthepursuitofsuccessforanapplication.BugsandsecurityissuesareobviouslynotfeaturesthathelpyourapplicationdowellintheincreasinglymoreexigentmarketofAndroid.

Inthisbook,youaregoingtolearnhowtoturnyourAndroidapplicationintoasolidlydebuggedandsecureapplication.Toachievethis,youwilllearnhowtouseAndroidStudioanditsmostimportantfeatures:testingandsecurity.

Page 28: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

WhatthisbookcoversChapter1,IntroductiontoSoftwareSecurity,introducestheprinciplesofsoftwaresecurity.

Chapter2,SecurityinAndroidApplications,describesthedistinctivefeaturesfoundinmobileenvironmentsandtheAndroidsystem.

Chapter3,MonitoringYourApplication,presentsthedebuggingenvironment,oneofthemostimportantfeaturesofanIDE.

Chapter4,MitigatingVulnerabilities,describesthemeasuresthatshouldbetakentopreventattacks.

Chapter5,PreservingDataPrivacy,presentsthemechanismsofferedbyAndroidtopreservetheprivacyofuserdata.

Chapter6,SecuringCommunications,explainsthemechanismsofferedbyAndroidtosecurecommunicationsbetweenanAndroidapplicationandanexternalserver.

Chapter7,AuthenticationMethods,presentsdifferenttypesofauthenticationmethodsusedinAndroidmobiledevices.

Chapter8,TestingYourApplication,introduceswaystotestanapplicationusingAndroidStudio.

Chapter9,UnitandFunctionalTests,coversunitandfunctionalteststhatallowdeveloperstoquicklyverifythestateandbehaviorofanactivityonitsown.

Chapter10,SupportingTools,presentsasetofexternaltoolsdifferentfromAndroidStudiotohelpdeveloperstestanAndroidapplication.

Chapter11,FurtherConsiderations,providessomefurtherconsiderationsthatareusefulfordevelopers.

Page 29: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 30: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

WhatyouneedforthisbookForthisbook,youneedacomputerwithaWindows,MacOS,orLinuxsystem.YouwillalsoneedtohaveJavaandtheAndroidStudioIDEinstalledonyoursystem.

Page 31: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 32: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

WhothisbookisforThisbookisaguidefordeveloperswithsomeAndroidknowledge,butwhodonotknowhowtotesttheirapplicationsusingAndroidStudio.Thisbookissuitablefordeveloperswhohaveknowledgeaboutsoftwaresecuritybutnotaboutsecurityinmobileapplications,andalsofordeveloperswhodonothaveanyknowledgeaboutsoftwaresecurity.It’sassumedthatyouarefamiliarwithAndroidanditisalsorecommendedtobefamiliarwiththeAndroidStudioIDE.

Page 33: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 34: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ConventionsInthisbook,youwillfindanumberoftextstylesthatwillhelpyoudistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestylesandanexplanationoftheirmeaning.

Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,dummyURLs,userinput,andTwitterhandlesareshownasfollows:“Tosendanorderedbroadcast,youcancallthesendOrderedBroadcastmethod.”

Ablockofcodeissetasfollows:

Instrumentation.ActivityMonitormonitor=

getInstrumentation().addMonitor(SecondActivity.class.getName(),null,

false);

Whenwewishtodrawyourattentiontoaparticularpartofacodeblock,therelevantlinesoritemsaresetinbold:

@Override

protectedvoidsetUp()throwsException{

super.setUp();

Intentintent=newIntent(getInstrumentation().getTargetContext(),

MainActivity.class);

startActivity(intent,null,null);

mActivity=getActivity();

Anycommand-lineinputoroutputiswrittenasfollows:

adbshellmonkey–pcom.packt.package–v100

Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen,inmenusordialogboxesforexample,appearinthetextlikethis:“ThemultiplicationismadewhentheButton1buttonisclicked.”

NoteWarningsorimportantnotesappearinaboxlikethis.

TipTipsandtricksappearlikethis.

Page 35: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 36: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook—whatyoulikedormayhavedisliked.Readerfeedbackisimportantforustodeveloptitlesthatyoureallygetthemostoutof.

Tosendusgeneralfeedback,simplysendane-mailto<[email protected]>,andmentionthebooktitlethroughthesubjectofyourmessage.

Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideonwww.packtpub.com/authors.

Page 37: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 38: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.

Page 39: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

DownloadingtheexamplecodeYoucandownloadtheexamplecodefilesforallPacktbooksyouhavepurchasedfromyouraccountathttp://www.packtpub.com.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.

Page 40: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ErrataAlthoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdohappen.Ifyoufindamistakeinoneofourbooks—maybeamistakeinthetextorthecode—wewouldbegratefulifyouwouldreportthistous.Bydoingso,youcansaveotherreadersfromfrustrationandhelpusimprovesubsequentversionsofthisbook.Ifyoufindanyerrata,pleasereportthembyvisitinghttp://www.packtpub.com/support,selectingyourbook,clickingontheerratasubmissionformlink,andenteringthedetailsofyourerrata.Onceyourerrataareverified,yoursubmissionwillbeacceptedandtheerratawillbeuploadedtoourwebsite,oraddedtoanylistofexistingerrata,undertheErratasectionofthattitle.

Page 41: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

PiracyPiracyofcopyrightmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.Ifyoucomeacrossanyillegalcopiesofourworks,inanyform,ontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.

Pleasecontactusat<[email protected]>withalinktothesuspectedpiratedmaterial.

Weappreciateyourhelpinprotectingourauthors,andourabilitytobringyouvaluablecontent.

Page 42: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

QuestionsYoucancontactusat<[email protected]>ifyouarehavingaproblemwithanyaspectofthebook,andwewilldoourbesttoaddressit.

Page 43: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 44: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Chapter1.IntroductiontoSoftwareSecurityYouwanttolearnhowtoimproveyourAndroidapplicationssothatthey’resecureandrobust.Youwouldliketolearnaboutmobilesoftwaresecurityanditsmostimportantthreatsandvulnerabilities.Youwantyouruserstobesatisfiedwhileensuringthattheirdataissecureandthattheapplicationhasnobugs.Canyoudothiseasily?Whatdoyouneedtodoinordertoachievethis?

Thischapterwillteachyouthebasicsofsoftwaresecurity.We’llbeginbyteachingyouthedifferentsecuritytermsthatwewilluseinthisbook.You’llseethemostimportantthreatsandvulnerabilitiesthatmayaffectyourapplication.You’llthenlearnaboutsecurecodedesignprinciples,aswellashowtotestourapplicationforsecurityissues.

Inthischapter,wewillcoverthefollowingtopics:

SoftwaresecuritytermsThreats,vulnerabilities,andrisksSecurecodedesignprinciplesSecuritytesting

Page 45: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SoftwaresecuritytermsInrecentyears,theInternethasexperiencedahugeincreaseinelectroniccommerce(e-commerce).Thisincreaseinmonetizationofinformationinthecloudmeansthatattackerscannowberewardedfinancially,socially,andevenpoliticallyforasuccessfulattack.Thereisalowriskinattemptingtheseattacks,sincethereisasmallchanceofgettingcapturedandtherefore,ofprosecution.Withamoremotivatedenemy,companiesandenterpriseshavetoimprovetheirsecuritymeasurestofacethesenewthreats.Theymustidentifythethreatsanddefendthevulnerabilitiesthatmayaffectthedatathathasabigimpactontheirbusiness.

Inordertounderstandthecontentofthisbookcompletely,youwillfirstneedtounderstandsomebasicconceptsaboutsoftwaresecurity:

Accesscontrol:Thisensuresselectiveaccesstoresourcesbyusersthatareentitledtoit.Asymmetriccryptography:Thisisalsoknownasthepublickeycryptographyandusesalgorithmsthatemployapairofkeys—onepublicandoneprivate.Apublickeyisusedtoencryptthedatawhileaprivatekeyisusedtodecryptdata.Authentication:Thisisaprocessthroughwhichwecanconfirmtheidentityofauser.Authorization:Thisisaprocessthroughwhichwegivesomeonepermissiontodoorhavesomething.Availability:Thismeansthatthesystemanddataareavailabletoauthorizeduserswhentheymaymakeuseofit.Bruteforce:Thisisaverybasicandnonoptimalcryptanalysistechniquethattrieseverypossibilitytocrackakeyorapassword.Cipher:Thisisacryptographicalgorithmthatmaybeusedforencryptionanddecryption.Codeinjection:Thisisanattackwherethecodeisinsertedintoapplicationqueries.ThiskindofattackiscommonlyusedtoalterdatabasesviaSQLinjections.Confidentiality:Thisspecifiesthatthedataisonlyavailableforuserswhohavepermissiontoaccessit.Crack:Thisistheprocessthroughwhichanattackerattemptstogainaccesstoamachine,network,orsoftware.Decryption:Thisistheprocessthroughwhichanencryptedmessageistransformedintoitsoriginalstate.Denial-of-service(DoS):Thisisatypeofattackthatmakesanonlineresourceunavailableforafixedamountoftime.Distributeddenial-of-service(DDoS):ThistypeofattackissimilartotheDoSattack,butitisperpetratedfromseveralmachinesandisgenerallymoreeffectivethanaDoSattack.Dictionaryattack:Thisisabasiccryptanalysistechniquethatusesallthewordsinadictionarywhentryingtocrackakeyorpassword.Encryption:Thisisaprocessthroughwhichaplainpieceofdataistransformedinto

Page 46: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

anencryptedstate,withtheobjectiveofconcealingthisinformationinordertopreventaccessfromunwantedsources.Hashfunction:Thisisatypeofalgorithmthatmapsdataofdifferentsizesintodataofafixedsize.Hijackattack:Thisisaformofattackinwhichanalreadyestablishedcommunicationisseizedandactsasoneoftheoriginalparticipants.HypertextTransferProtocolSecure(HTTPS):ThisisanapplicationlevelprotocolbasedonHTTPthatallowsasecuretransferofsensitiveinformationintheformofhypertext.Integrity:Thismeansthattheinformationisaccurateandisnotchangedaccidentallyordeliberately.MD5:Thisisaverycommonlyusedhashfunction.Man-in-the-middleattack:Thisisatypeofattackwheretheattackerassumesapositioninthemiddleofacommunication,interceptsandreadsthemessagesofacommunication,andletsthevictimsbelievethattheyaredirectlyconnectedtoeachother.Password:Thisisastringofcharactersusedforauthentication.Phishing:Thisisanattackattemptthatappearstobefromareliablesourceandtrickstheuserintoenteringtheirauthenticationcredentialsinadifferentdomainorapplication.Risk:Thisisthelikelihoodofanattackhappeningandsucceeding.SHA1:Thisisacommonlyusedhashfunction.Sniffingattack:Thisisanattackthatanalysesthepacketsexchangedinanetworkinordertoextractusefulinformationfromthem.Spoofingattack:Thisisanattackwhereanunauthorizedentitygainsaccesstoasystemwiththecredentialsofanauthorizeduser.Symmetriccryptography:Thisisatypeofcryptographythatusesthesamekeyforencryptionanddecryption,andtherefore,everyentitysharesthesamekey.Threat:Thisisacircumstancethatcouldbreachsecurityandcauseharmtothesystem.Vulnerability:Thisisaweaknessthatallowsforathreattooccur.

Page 47: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 48: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Threats,vulnerabilities,andrisksTherearethreekeytermsthatyouneedtounderstand.Theyweredefinedintheprevioussection,butwewilltalkalittlebitmoreaboutthemsincetheyarecommonlymixedup.Thesetermsarethreat,risk,andvulnerabilityandtheyarediscussedinthefollowingsections.

Page 49: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ThreatAthreatisanythingthatmayexploitvulnerabilityinordertoaccess,modify,ordestroyinformation.Athreatisthesourceandtypeofanattackandiswhatwetrytodefendagainst.Threatassessmentsareusedtodeterminethebestwaytodefendagainstadeterminedclassofthreat.

Whenweconsideracommunicationbetweentwoauthorizedentities,asource(S)andadestination(D),threatscanbecategorizedintothefollowingfoursegments:

Interception:Thishappenswhenanattackingentityhasanaccesstoacommunicationbetweentwoauthorizedentities.Theentitiesdonotrealizethatinterceptionishappeningandkeeponwiththeircommunicationnormally.Interruption:Thisreferstowhentheattackingentityinterceptsthecommunication.Thesourceentitymaynotrealizethisishappening,whilethedestinationentityhasnoknowledgeofthecommunicationattempt.Modification:Thishappenswhentheattackingentitychangestheinformationsentbetweenthetwoauthorizedentities.Thedestinationentitydoesnotrealizethattheinformationhasbeentamperedwithbytheattackingentity.Fabrication:Thishappenswhentheattackingentityactslikethesourceentity.Thedestinationentityacknowledgesthecommunicationasifitwasproducedbythesourceentity.

Page 50: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

VulnerabilityVulnerabilityisaweaknessoraflawinthesecuritysystemofourapplicationthatmaybeusedbyadeterminedthreattoaccess,modify,ordestroyinformation.Vulnerabilitytestingismandatoryandshouldbeperformedrepeatedlytoensurethesecurityofourapplication.

Whenahumanorasystemtriestoexploitvulnerability,itisconsideredtobeanattack.Someofthemostcommonkindsofvulnerabilitiesthatcanbeexploitedtodamageoursystemareasfollows:

Improperauthentication:Thishappenswhenanentityclaimsthatithasbeenauthenticatedandthesoftwaredoesnotcheckwhetherthisistrueorfalse.Thisvulnerabilityaffectsoursystemofaccesscontrol,sinceanattackercanevadetheauthenticationprocess.Averycommonexampleofexploitingthisvulnerabilityismodifyingacookiewhichhasafieldthatdetermineswhethertheuserisloggedin.Settingloggedintotruecancheatthesystemintobelievingthattheentityisalreadyloggedinandisthereforegrantedaccesswhenitshouldnotbegranted.Bufferoverflow:Thishappenswhenthesoftwarehasaccesstoadeterminedamountofmemorybuttriestoreadabufferoutofthelimits.Forexample,ifthesoftwarehasabufferofsizeNbuttriestoreadthepositionN+2,itwillreadinformationthatmaybeusedbyanotherprocess.Thisgrantsaccessandevenmodifiestheinformationthatbelongstoapartofthememorywherethesoftwareshouldnothaveaccess.Cross-sitescripting(XSS):Thisisakindofvulnerabilitythatallowsathird-partytoinjectcodeinoursoftware.Itisespeciallycommoninwebsites,butitalsoappliestocertainmobileapplications.ThemostcommonlyusedexamplesofXSSaretheaccesstocookiesfromadifferentsiteandtheinjectionofJavaScriptintoadifferentsite.Inputvalidation:Whenreadinginformationprovidedbytheuser,itisalwaysagoodideatovalidatethedata.Notvalidatingthedatamayresultinanattackerintroducingcertainunexpectedvaluesthatcancauseanissueinthesystem.SQLinjection:Thisisakindofinputvalidationvulnerability.Itisverycommontouseasearchfeatureinalmostanyapplication.ThestringthattheuserintroducesinthesearchfieldisthenintroducedinaSQLsentence.Ifthereisnoanalysisandfilterofthestringprovidedbytheuser,anattackercouldwriteaSQLquerythatwouldbeexecuted.Ifthisiscombinedwithabadaccesscontrol,theattackercouldevendeletethewholedatabase.

Page 51: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

RiskAriskisthepotentialforanattackhappeningandbeingsuccessful.Themoresensitivetheinformation,thehighertheriskofattack,asitcancauseahigherlevelofdamagetooursystem.Risksaretheresultofathreatexploitingvulnerabilityandaccessing,modifying,ordestroyingapieceofinformationthatwewanttobeprotected.Riskassessmentsareperformedtoidentifythemostcriticaldangersandtoevaluatethepotentialdamage.Thispotentialdamageiscalculatedthroughastatebetweenthecostofabreachhappening,whichdependsonhowsensitivetheinformationis,andtheprobabilityofthatevent,whichdependsonthethreatsandvulnerabilitiesthatmayaffecttheapplication.

Asyoucansee,thereisaveryimportantrelationshipbetweenthesethreeterms;especiallywhentryingtocorrectlyidentifytheriskthattheinformationstoredsuffers.Assessingthreatsanddetectingvulnerabilitiesiscrucialtotheprotectionoftheinformationinourapplication.

Page 52: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 53: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Securecode-designprinciplesInordertoreducethenumberofvulnerabilitiesofyourapplication,agoodsecuritydesignismandatory.Therearemanystandardsandguidelinesthatrecommenddifferentprocessestoproducesecureapplications.Inthissection,wearegoingtoidentifythemostimportantprinciplesthatyoushouldfollowwhendesigningyourapplication:

Securedefaults:Securityisoftheutmostimportanceforanaverageuser.Whendesigningyourapplication,youshouldmakesurethatthemostdemandinguserisgoingtobesatisfiedand,therefore,yourapplicationshouldofferthebestsecuritymethodsavailable.However,therearesomeuserswhomaypreferaccessibilityoversecurityandmaywanttoreducethelevelofsecurity.Forexample,youmaywanttoaddpasswordagingtoyourauthenticationsystem.Thismeansthateveryestablishedperiodoftime,theusersshouldchangetheirpasswordtoanewone.Thismeansanadditionallevelofsecuritybutcanbeannoyingforcertainusers.Addinganoptioninthepreferencestoturnoffthisfeaturecanbeagoodidea.However,alwaysmakesuretosetthedefaulttothemoresecuresetting,andlettheuserdecidewhethertheywanttoincreasetheriskofbreachingtheirinformation.Leastprivileges:Privilegesaresometimesconcededinexcessinordertospeeduptheprocessofdevelopment.Thisprinciplestatesthatyoushouldalwaysconcedetheleastprivilegesaspossibleinordertominimizesecurityrisks.Clarity:Nevertrustobscuritytoensurethesecurityofyourapplication.Concealingtheinformationonhowyoursecuritysystemworksisagoodidea,butitshouldnotbegrantedasenoughbyitself;thesecuritymustcomefromgoodcryptographictechniquesandagoodsecuritydesign.Smallsurfacearea:Ifyouknowyoumayhavevulnerabilityinadeterminedsectionofyourcode,youcantrytominimizetheriskofathreatexploitingitbyminimizingtheoveralluseofthissection.Forexample,ifyouthinkthatcertainfunctionalitymaybeexploited,youcanrestrictthisfunctionalitytoauthenticatedusers.Strongdefense:Whendefendingagainstacertainattack,theremaybedifferentmethodstouse.Onecontrolcansurelybeenoughbutsensitiveinformationdemandsextraordinarymeasures.Also,usingmorethanonemethodofprecautionismostofthetimesconvenient.Failingsecurely:Whendevelopingourapplication,weaimforthehighestrobustness.However,applicationsfailsometimesandweneedtoadaptourcodetomakesuretheapplicationfailssecurely.WhenprogrammingforAndroid,wecanaddressthisissuebycontrollingeveryexception,forexample,throughthecorrectusageoftryandcatch.Nottrustingthethird-partycompanies:Therearemanyservicesavailablethathavebeendevelopedbythethird-partycompanieswithdifferentprivacyandsecuritypolicies.Itisimportanttoknowthatwhileusingoneoftheseservices,youtrustthecompaniesonhowtheyuseyourinformation.Theprincipleofnottrustingthethird-partycompaniesrecommendsthatyoushouldonlytrustanexternalservicewiththeminimalamountofinformationpossibleandalwaysimpliesacertainleveloftrust

Page 54: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

withthem.Simplicity:Alwaystrytokeepyoursecuritycodesimple.Althoughitisrecommendedtousecodepatterns,whentalkingaboutsecurity,thesafestandmorerobustwayisitssimplicity.Addressvulnerabilities:Whenyoudetectvulnerability,itisimportanttoaddressthisissuecorrectly.Youneedtounderstandboththevulnerabilityandthethreatandthenactaccordingly.

Page 55: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 56: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TestingthebasicsAsstatedbyBorisBeizer,authorofthebookSoftwareTestingTechniques,DreamtechPress:

“Bugslurkincornersandcongregateatboundaries.”

Securitytestingcanbedefinedasaprocessthroughwhichwefindvulnerabilitiesorflawsinoursecuritysystem.Althoughwemaydoexhaustivesecuritytesting,itdoesnotimplythatnoflawsexist.Inthissection,wewillfocusonthetaxonomyofteststhatcanbeperformedinanycircumstance.

Testscanbecategorizedintotwobiggroups:white-boxtestsorstructuraltestsandblack-boxtestsorfunctionaltests.Structuraltesting,morecommonlyknownasthewhite-boxtesting,isatestingmethodthatevaluatestheinternalbehaviorofacomponent.Itisfocusedontheanalysisofthebehaviorofeachprocedureindifferentmomentsofexecution.Thewhite-boxtestevaluateshowthesoftwareproducesaresult.Functionaltesting,specificationtesting,orblack-boxtesting,aremethodsoftestingthatfocusonthefunctionalityofthecomponentratherthanitsstructure.Whenusingthiskindoftest,thetesterisawarethatacertaininputshouldgenerateaparticularoutput.Thistestevaluateswhatthesoftwareproduces.

Thetwotestcategories,white-boxtestandblack-boxtest,areshowninthefollowingdiagrams:

Therearevariouswhite-boxtechniques.However,themostcommonlyusedarecontrolflowtesting,dataflowtesting,basispathtesting,andstatementcoverageandtheyareexplainedasfollows:

Controlflowtesting:Thisevaluatestheflowgraphofthesoftwaretoindicatewhetherthesetoftestscoverseverypossibletestcase.Dataflowtesting:Thisrequiresanevaluationofhowtheprogramvariablesareused.Basispathtesting:Thisensuresthateverypossiblepathinacodehasbeenincludedinthetestcases.Statementcoverage:Thisconsistsoftheevaluationofthecodeandthedevelopment

Page 57: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ofindividualteststhatwillworkoneveryindividuallineofcode.

Theblack-boxtestingdesignalsoincludesdifferenttechniques.Themostfrequentlyusedtechniquesareequivalencepartitioning,boundaryvalueanalysis,cause-effectgraphing,statetransitiontesting,allpairstesting,andsyntaxtesting,andtheyareexplainedasfollows:

Equivalencepartitioning:Thisdividestestcasesindifferentpartitionsthatpresentsimilarcharacteristics.Thistechniquecanhelpinreducingthenumberoftestscases.Boundaryvalueanalysis:Thisisperformedinordertoanalyzethebehaviorofacomponentwhentheinputisneartheextremevalidvalues.Cause-effectgraphing:Thisgraphicallyillustratestherelationshipbetweencircumstancesoreventsthatcauseadeterminedeffectonthesystem.Statetransitiontesting:Thisisperformedthroughanumberofinputsthatmakethesystemexecutevalidorinvalidstatetransitions.Allpairstesting:Thisisacombinatorialmethodthattestseverypossiblecombinationofparameters.Whenthenumberofparametersandthepossiblevaluesforeachparameterarebig,thistesttechniquecanbecombinedwiththeequivalentpartitioningtechniquetoreducethenumberoftestcases.Syntaxtesting:Thisanalysesthespecificationsofacomponenttoevaluateitsbehaviorwithahugenumberofdifferentinputs.Thisprocessisusuallyautomatizedduetothelargenumberofinputsrequired.

Whentestinganapplication,therearedifferentlevelsoftestingthatdependonthesizeofthepartofthesysteminvolved.Therearefivecommonlyknownlevelsoftests:unit,integration,validation,system,andacceptance.

Unittests:Thesetestsfocusoneachindividualcomponent.Thesetestsareusuallyperformedbythesamedevelopmentteamandconsistofaseriesofteststhatevaluatethebehaviorofasinglecomponentcheckingforthecorrectnessofthedataanditsintegrity.Integrationtests:Thesetestsareperformedbythedevelopmentteam.Thesetestsassessthecommunicationbetweendifferentcomponents.Validationtests:Thesetestsareperformedbythefullydevelopedsoftwareinordertoevaluatethefulfilmentoffunctionalandperformancerequirements.Theycanalsobeusedtoassesshoweasyitistomaintainortoseehowthesoftwaremanageserrors.Systemtests:Thesetestsinvolvethewholesystem.Oncethesoftwareisvalidated,itisintegratedinthesystem.Acceptancetests:Thesetestsareperformedintherealenvironmentwherethesoftwareisused.Theuserperformsthesetestsandacceptsthefinalproduct.

Thehighertheleveloftesting,unittestingbeingthelowestandacceptancetestingthehighest,themorelikelyitistouseblack-boxtests.Unittestsevaluatecomponentsthataresmallandthereforeeasytoanalyzeinbehavior.However,thehigherthelevel,thebiggerthesystem,andthereforethemoredifficultandmoreresource-consumingitistoapplywhite-boxtestingcategory.Thisdoesnotmeanthatyoushouldnotapplytheblack-box

Page 58: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

testingcategorywhileperformingunittests,aseachonecomplementstheother.

Page 59: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 60: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SummaryInthischapter,learnedthebasicandmostcommonlyusedterminologieswhilediscussingsoftwaresecurity.Youknowthedifferencebetweenthreat,vulnerability,andrisk,andunderstandhoweachoneisrelatedtotheother.Youalsolearnedaboutthedifferentkindsofthreatsandvulnerabilitiesthatcanaffectasystem.Younowknowhowtoproperlyapproachcodingyoursecuritysystemthankstothesecurecodeprinciples.Finally,youlearnedaboutthedifferentmethodsoftestingthatyoushouldconsiderinordertomakeyourapplicationrobust.Properlyunderstandingthesedefinitionsallowsyoutodesignbettersecuritysystemsforyoursoftware.

Soasadeveloper,youhavetoaddressthesecurityofyourapplication,butwhatdoesAndroiddoforyou?Androidhasseveralbuilt-insecuritymeasuresthatreducethefrequencyandthepotentialdamagethatapplicationsecurityissuesmaycause.Inthenextchapter,youwilllearnaboutthesefeaturesandunderstandhowtheywork.

Page 61: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 62: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Chapter2.SecurityinAndroidApplicationsYouunderstandthesecurityconceptsinsoftwareandnowyouwanttodiscoverhowthosethreatsandvulnerabilitiesareappliedtoamobileenvironment.YouwanttobeawareofthespecialsecurityfeaturesintheAndroidoperatingsystem.YouarealreadyfamiliarwithAndroid,butyouneedtoknowthecomponentsthatarecriticalforitssecurity.

Thischapterwillshowyouthechallengesthatexistinthemobileenvironment.YouwilllearnabouttheAndroidsecurityarchitectureandaboutwhatapplicationsandboxingmeans.ThischapterwillshowyouthemainfeaturesinAndroidthatwillallowyouprotectyourlocation:permissionsandinterprocesscommunication.

Wewillbecoveringthefollowingtopicsinthischapter:

VulnerabilitiesinthemobileenvironmentAndroidsecurityoverviewPermissionsInterapplicationcommunication

Page 63: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ThemobileenvironmentAndroidisanoperatingsystem(OS)createdforintelligentmobiledeviceswithatouchscreen,suchassmartphonesortablets.Knowingthefeaturesofadeviceisimportanttoidentifythevulnerabilitiesthatcanpotentiallycompromisetheintegrity,confidentiality,oravailabilityofyourapplication(app).

Asmartphoneisaconnecteddeviceandsomalicioussoftwarecaninfectitinseveralways.Thesmartphonecancommunicatewithdifferentdevicesbyawirelessorwiredconnection.Forexample,itcanconnecttoacomputerbyacableoritcanconnecttoanothermobiledevicebyawirelessBluetoothnetwork.Thesecommunicationsallowtheusertotransferdata,files,orsoftware,whichisapossiblepathtoinfectthesmartphonewithmalware.

AsmartphoneisalsoaconnecteddeviceinthesensethatitcanconnecttotheInternetbycellularnetworkslike3GoraccesspointsviaWi-Fi.Internetisthereforeanotherpathofpotentialthreatstothesecurityofsmartphones.

Smartphonesalsohaveinternalvulnerabilities,forexample,maliciousappsthatareinstalledbytheuserthemselves.Thesemaliciousappscancollectthesmartphone’sdatawithouttheuser’sknowledge.Sensitivedatamightbeexposedbecauseofimplementationerrorsorbecauseoferrorsthatoccurwhilesendingdatatothewrongreceiver.Communicationbetweentheappsinstalledinthesmartphonecanbecomeawaytoattackthem.

Thefollowingfigurerepresentsthetypesofexistingvulnerabilitiesinsmartphones.Theconnectiontothenetworkisoneoftheexternalvulnerabilities,sincenetworkconnectionsaresusceptibletosniffingorspoofingattacks.Theconnectionstoexternaldevicesalsoinvolvepotentialvulnerabilitiesasmentionedearlier.Regardinginternalvulnerabilities,implementationerrorscancausefailuresandattackerscantakeadvantageofthem.Finally,userunawarenessisalsoavulnerabilitythataffectstheinternalsofthesmartphone.Forexample,installingappsfromuntrustedsourcesorsettinganimprudentconfigurationforWi-FiorBluetoothservicesisarisk.

Asadeveloper,youcannotcontroltherisksassociatedwithexternaldevicesorthenetwork,noteventhoserelatedtouserunawareness.Therefore,yourresponsibilityistocreaterobustappswithoutimplementationerrorsthatcancausesecuritybreaches.

Page 64: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 65: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 66: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

AnoverviewofAndroidsecurityAndroidprovidesasecurearchitecturetoprotectthesystemanditsapplications.Androidarchitectureisstructuredlikeasoftwarestackinwhicheachcomponentofalayeracceptsthatthelayerfollowingitissecure.ThefollowingfigureshowsasimplifiedversionoftheAndroidsecurityarchitecture:

AndroidOSisamultiuser,Linux-basedplatforminwhicheachapphasadifferentuser.EachapphasitsownuserID(UID)intheLinuxkernelthatisunique.TheUIDisassignedbythesystemandisunknowntotheapp.BecauseoftheuniqueUID,Androidappsruninseparateprocesseswithdifferentpermissions.Thismechanismisknownasapplicationsandboxing.TheAndroidApplicationSandboxisolateseachapplication’sdataandcodeexecutiontoimproveitssecurityandpreventmalware.Thismeansthatundernormalcircumstances,youcannothaveaccesstootherapplication’sdataandotherapplicationsdonothaveaccesstoyourapplication’sdata.AstheApplicationSandboxisimplementedintheLinuxkernel,thesecurityprovidedbythismechanismisextendedtoallthelayersabovethekernel(suchaslibraries,Androidruntime,applicationframework,andapplicationruntime).Forexample,ifamemorycorruptionerrorisgenerated,thiserrorwillonlyhaveconsequencesfortheapplicationinwhichtheerrorwasproduced.

ApplicationsandboxingisoneofthemainsecurityfeaturesofAndroid,butwecanalsofindthefollowingfeaturesinthesecuritymodel:

Application-definedpermissions:Ifapplicationsareisolatedfromeachother,howcantheyshareinformationwhenrequired?Applicationscandefinepermissionstoallowotherapplicationstocontrolitsdata.Therearealsomanypredefinedsystem-basedpermissionscovermanysituationsandthatwillreducethenecessityofcreatingpermissions,especiallyforyourapplication.Interprocesscommunication:Undernormalcircumstances,everycomponentofanapplicationrunsinthesameprocess.However,therearetimeswhendevelopers

Page 67: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

decidetoruncertaincomponentsindifferentprocesses.Androidprovidesaninterprocesscommunicationmethodthatissecureandrobust.Supportforsecurenetworking:NetworktransactionsareespeciallyriskyonmobiledevicesthatcommonlyuseunsecuredWi-Finetworksinpublicspaces.Androidsupportsthemostcommonlyusedprotocolstosecureconnectionsundertheseextremeconditions.Supportforcryptography:Androidprovidesaframeworkthatdeveloperscanusewithtestedandrobustimplementationsofcommonlyusedcryptographicmethods.Encryptedfilesystem:Androidprovidesafullfilesystemencryption.ThismeansthattheinformationstoredonanAndroiddeviceisencryptedandisthereforeprotectedatanytimeagainstexternalentities.Thisoptionisnotactivebydefaultandrequiresausernameandapassword.Applicationsigning:Theinstallationpackageofeveryappmustbesignedwithacertificate,whichcanbeaself-signedcertificate.Anattackercanpreservetheiranonymity,sinceit’snotnecessaryforatrustedthird-partytosignthecertificate.Certificatesaremainlyusedtodistinguishdevelopersandallowthesystemtomanagepermissions.Topreventanattackerfrommodifyingyourapplication,youshouldkeepyourcertificatesafe.Furthermore,applicationupdatesmustbesignedwiththissamecertificate.

Page 68: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 69: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

PermissionsWithapplicationsandboxing,appscannotaccesspartsofthesystemwithoutpermission,butevenwithit,Androidallowsdatasharingwithotherappsoraccesstosomesystemservices.Anappneedstorequestpermissiontoaccessdevicedataortoaccesssystemservices.PermissionsareasecurityfeatureofAndroidsystem,butmisusedpermissionsmakeyourapplicationvulnerable.

Thepermissionneedsofanapparedeclaredinitsmanifestfile.Thismanifestfileisbundledintotheapp’sAndroidapplicationpackage(APK),whichincludesitscompiledcodealongwithotherresources.Thepermissionsrequestedinthemanifestfile(manifestpermissions)willbeshowntotheuserwheninstallingtheapp.Theusershouldreviewthesepermissionsandacceptthemtocompletetheinstallationprocess.Iftheuseragreestothem,theprotectedresourcesareavailabletotheapp.

TipDonotrequestpermissionsthatyourappdoesnotneed.Reducingthenumberofpermissionsmakesyourapplessvulnerable.

PermissionscontrolhowanappinteractswiththesystembyusinganAndroidapplicationprogramminginterface(API).SomeoftheprotectedAPIsthatneedpermissionincludethefollowing:

BluetoothCameraLocationGPSNetworkanddataconnectionsNFCSMSandMMSTelephony

Forexample,torequestpermissiontousethecamera,youhavetoaddthefollowinglinecodeinourmanifestfile:

<uses-permissionandroid:name="android.permission.CAMERA"/>

ThefollowingcodeisusedtorequestpermissiontoaccesstheInternet:

<uses-permissionandroid:name="android.permission.INTERNET"/>

ThefollowingcodeisusedtorequestpermissiontosendaSMS:

<uses-permissionandroid:name="android.permission.SEND_SMS"/>

Page 70: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 71: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

InterapplicationcommunicationAppsinAndroidcannotaccesseachother’sdatadirectlybecauseofapplicationsandboxing,butAndroid’ssystemprovidessomeothermechanismsfortheapplicationstocommunicatewitheachother.IntentsandcontentprovidersaremechanismsthatwecanuseontheJavaAPIlayer.Intentsandcontentprovidersshouldbeusedcarefullytopreventattacksfrommalwareapplications.Thisisthereasonwhyitisimportanttounderstandtheircharacteristics.

Page 72: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

IntentsIntentsareanasynchronousinterprocesscommunicationmechanism.Intentisamessagethatincludesthereceiverandoptionalargumentstopassthedata.ThereceiverofIntentcanbedeclaredexplicitlysothattheIntentissenttoaparticularcomponent,oritcanbedeclaredimplicitlysothattheIntentissenttoanycomponentthatcanhandleit.Intentsareusedforintra-applicationcommunication(inthesameapplication),orforinterapplicationcommunication(indifferentapplications).ThefollowingcomponentscanreceiveIntents:

Activities:Anactivityrepresentsascreenintheapp.Intentscanstartactivities,andtheseactivitiescanreturndatatotheinvokingcomponent.TostartanactivityusingIntent,youcancallthestartActivitymethodorthestartActivityForResultmethodtoreceivearesultfromtheactivity.Services:Aserviceperformslong-runningbackgroundtaskswithoutinteractingwiththeuser.TostartaserviceusingIntent,youcancallthestartServicemethodorthebindServicemethodtobindothercomponentstoit.Broadcastreceivers:Intentscanbesenttomultiplereceiversthroughbroadcastreceivers.WhenareceiverisstartedbecauseofIntent,itrunsinthebackgroundandoftendeliversthemessagetoanactivityoraservice.Somesystemeventsgeneratebroadcastmessagestonotifyyou,forexample,whenthedevicestartschargingorwhenthedevice’sbatterylevelislow.TosendabroadcastmessageusingIntent,youcancallthesendBroadcastmethod.Tosendanorderedbroadcast,youcancallthesendOrderedBroadcastmethod.Tosendastickybroadcast,youcancallthesendStickyBroadcastmethod.Therearethreetypesofbroadcastmessages:

Normalbroadcast:Inthistypeofbroadcast,themessageisdeliveredtoallthereceiversatthesametime.Soonafter,themessageisnolongeravailable.Orderedbroadcast:Inthistypeofbroadcast,themessageisdeliveredtoonereceiveratatimedependingonitsprioritylevel.Anyreceivercanstopthepropagationofthemessagetotherestofthereceivers.Soonafter,themessageisnolongeravailable.Stickybroadcast:Inthistypeofbroadcast,themessageissentbutitdoesnotdisappear.Anexampleofastickybroadcastisthebatterylevel.Anappcanfindoutwhichwasthelastbatterylevelbroadcastbecauseitremainsaccessible.

ApplicationcommunicationbyIntentsallowsthereceiverandoptionalargumentstoreuseeachother’sfeatures.Forexample,ifyouwanttoshowawebpageinyourapp,youcancreateIntenttostartanyactivitythatisabletohandleit.Youdonotneedtoimplementthefunctionalitytodisplayawebpageinourapp.ThefollowingcodeshowsyouhowtocreateIntenttodisplaywebpagecontent:

Intenti=newIntent(Intent.ACTION_VIEW);

i.setData(Uri.parse("http://www.packtpub.com"));

startActivity(i);

Tip

Page 73: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Downloadingtheexamplecode

YoucandownloadtheexamplecodefilesforallPacktbooksyouhavepurchasedfromyouraccountathttp://www.packtpub.com.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.

TheprecedingcodeisanexampleofanimplicitIntentinwhichageneralactionisindicated:Intent.ACTION_VIEW.TheAndroidsystemsearchesforalltheappsthatmatchtheIntent.IfthereismorethanoneapplicationthatmatchestheIntentandtheuserhasnotsetadefaultone,adialogisdisplayedsothattheusercanchoosewhichoneofthemtouse.

IntentsthataresupportedbyacomponentaredeclaredinthemanifestfileusingtheIntentfilters.Thebroadcastreceiverscanbealsobedeclaredatruntime.IntentfilterdeclaresthetypesofIntentsthatacomponentcanrespondto.WhenacomponentincludesanIntentfilter,thecomponentisexportedsoitcanreceiveIntentsfromothercomponents.IntentfiltercanconstrictbytheactionoftheIntent,bythetypeofdata,orbythecategoryoftheIntent.Forexample,ifyouwantyourapptobehaveasabrowser,youhavetocreateanactivitywiththefollowingIntentfiltersinyourmanifestfile:

<activity…>

<intent-filter>

<actionandroid:name="android.intent.action.VIEW"/>

<dataandroid:scheme="http"/>

<categoryandroid:name="android.intent.category.DEFAULT"/>

<categoryandroid:name="android.intent.category.BROWSABLE"/>

</intent-filter>

</activity>

Thefollowingexampleshowsyouhowtoregisterareceivertorunwhenthedevicestartscharging:

<receiver…>

<intent-filter>

<actionandroid:name="android.intent.action.ACTION_POWER_CONNECTED"/>

</intent-filter>

</receiver>

NoteIfyouwanttolearnmoreaboutIntents,youmightwanttocheckouttheofficialdocumentation:http://developer.android.com/guide/components/intents-filters.html.

Page 74: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ContentprovidersContentprovidersareamechanismthatallowssharingbetweenapplicationsandservesaspersistentinternaldatastoragefacility.ThedatastoredthroughacontentproviderisstructuredandtheinterfaceisdesignedtobeusedwithaStructuralQueryLanguage(SQL)backend.AlthoughitiscommontouseaSQLdatabasebehindcontentproviders,filestorageorRESTcallscanalsobeused.Ifyouarenotfamiliarwithcontentproviders,youmightwanttocheckouttheofficialdocumentationsinceitisabroadtopic:http://developer.android.com/guide/topics/providers/content-providers.html.Ourinterestincontentprovidersisrelatedtotheirsecurityandpermissions.ContentprovidersaretheperfectscenarioforSQLinjectionattacks.

Toaccessthedataofcontentproviders,therearecontentresolversthatyoucanuseinyourapp.Theprovider’sdataisidentifiedbyacontentURI.Toaccessthecontentprovider,youshouldusethegetContentResolver().query()method,whichreceivesthefollowingparameters:

ContentURI:ThisistheURIthatidentifiesthedata(theFROMclauseinSQL)Projection:Thisspecifiesthecolumnstoretrieveforeachrow(theSELECTclauseinSQL)Selection:Thisisthecriteriatoselecttherows(theWHEREclauseinSQL)Selectionarguments:ThiscomplementsthecriteriatoselecttherowsSortorder:Thisisthesortorderfortherows(theORDERBYclauseinSQL)

TherearesomecontentprovidersofferedbytheAndroidsystemitself,suchasthecalendarproviderandthecontactsprovider.Toaccessthesystemcontentproviders,youneedtorequestthepermissioninyourmanifestfile.Forexample,tobeabletoreadthecontacts,youmustaddthefollowingpermissiontoyourapp:

<uses-permissionandroid:name="android.permission.READ_CONTACTS"/>

Toacquirethewritingaccesspermissions,youmustaddthefollowinglineofcodeinyourmanifest:

<uses-permissionandroid:name="android.permission.WRITE_CONTACTS"/>

Anyothercontentprovider,notonlythoseofthesystem,canindicatetherequiredpermissionsthatotherappsmustrequestsothattheycanaccesstheprovider’sdata.

Page 75: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 76: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SummaryInthischapter,youlearnedaboutthevulnerabilitiesassociatedwithmobiledevices—bothexternalandinternal.YounowunderstandtheAndroidarchitectureandthefeaturesprovidedbythesystemtokeepitsafe.YounowknowwhichcomponentsoftheJavaAPIlayerarevulnerabletoattacks,soyoucanlearnhowtomitigatetheminthenextchaptersofthisbook.

Inthenextchapter,wewillstartusingAndroidStudioIDE.AsthefirststeptocreatesecureAndroidapplications,youwilllearnhowtomonitorAndroidapplicationsinthedebuggingenvironmentinordertodetectincorrectbehaviors.

Page 77: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 78: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Chapter3.MonitoringYourApplicationYouarenowawareoftheimportanceoflearninghowtomonitortheactivityofyourAndroidapplicationandarealsofamiliarwiththebasicconsoleorlogsthatyouusetodebugyourapplication.However,thereismoretolearnaboutthedebuggingtoolavailableinAndroidStudio.AndroidStudioincludestheDalvikDebugMonitorServer(DDMS)debuggingtool.DoyouwanttousethisdebuggingtoolwhileprogramminginAndroidStudio?

Thischapterpresentsthedebuggingenvironment,oneofthemostimportantfeaturesofanIDE.MonitoringyourAndroidapplicationallowsyoutodetecttheincorrectbehaviorsandsecurityvulnerabilities.Inthischapter,youwilllearnabouttheinformationavailableintheadvanceddebuggingtoolincludedinAndroidStudio:DDMS.

Thetopicsthatwillbecoveredinthischapterareasfollows:

DebuggingandDDMSThreadandmethodprofilingHeapusageandmemoryallocationNetworkstatisticsFileexplorerEmulatorcontrolandsysteminformation

Page 79: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

DebuggingandDDMSInAndroidStudio,youcanusedifferentmechanismstodebugyourapplication.Oneofthemisthedebugger.Thedebuggermanagesthebreakpoints,controlstheexecutionofthecode,anddisplaysinformationaboutthevariables.Todebuganapplication,navigatetoRun|Debug‘MyApplication’orclickonthebugiconpresentinthetoolbar.

AnothermechanismistheConsole.TheConsoledisplaystheeventsthataretakingplacewhiletheapplicationisbeinglaunched.Actionssuchasuploadingtheapplicationpackage,installingtheapplicationinthedevice,orlaunchingtheapplicationaredisplayedintheConsole.

LogCatisanotherusefultooltodebugyourapplication.ItisanAndroidloggingsystemthatdisplaysallthelogmessagesgeneratedbythesystemintherunningdevice.Logmessageshaveseverallevelsofsignificance:verbose,debug,information,warning,anderror.

Finally,youalsohaveDDMS,anexcellentdebuggingtoolavailableintheSDKthatisavailabledirectlyinAndroidStudio.Thistoolisthemaintopicofthischapter.

ToopentheDDMStoolinAndroidStudio,navigatetoTools|Android|Monitor(DDMSincluded).Alternatively,youcanclickontheAndroidiconpresentinthetoolbar,whichwillopenawindowwiththeDDMSperspective.

Oncetheperspectiveisopen,asshowninthefollowingscreenshot,youcanseethelistofconnecteddevicestotheleft-handsideofthescreen,alongwithalistoftheprocessesrunningoneachdevice.Ontheright-handsideofthescreen,youcanseethedetailedinformationoftheprocess.Thisinformationisdividedintoseventabs:Threads,Heap,AllocationTracker,NetworkStatistics,FileExplorer,EmulatorControl,andSystemInformation.LogCatandConsoleareaccessibleatthebottomofthewindow.

Page 80: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 81: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ThreadsTheThreadstabdisplaysthelistofthreadsthatareapartoftheselectedprocess.Applicationshaveonemainthread,alsocalledastheUIthread,whichdispatchestheeventstotheuserinterface(UI)widgets.Toperformlongoperations,itisnecessarytocreatenewthreadssothatthemainthreadisnotblocked.Ifthemainthreadgetsblocked,thewholeUIwillalsogetblocked.

Toillustratetheworkingofthistool,runthefollowingexample.InAndroidStudio,createanewbasicprojectwithamainlayoutandamainactivity.Addabuttontothemainlayoutnamed,forexample,StartNewThread.Createanewmethodtobeexecutedwhenthebuttonisclickedandaddthefollowingcodeinthemethod:

publicvoidstartNewThread(Viewv){

newThread(newRunnable(){

publicvoidrun(){

Thread.currentThread().setName("MyexampleThread");

try{

Thread.sleep(30000);

}catch(InterruptedExceptione){

e.printStackTrace();

}

}

}).start();

}

Theprecedingmethodcreatesanewthreadintheapplication,althoughitdoesnothingandcontainsonlyasleepinstruction.Youcansetthethreadanametorecognizeiteasily.RuntheapplicationandopentheDDMSperspective.

SelectyourapplicationprocessfromtheDevicessectionandclickontheUpdateThreadsiconpresentonthetoolbaroftheDevicessectionandthethreadswillbeloadedinthecontentofthetab.TheStatuscolumnindicatesthethreadstate,utimeindicatesthetotaltimespentbythethreadexecutingusercode,stimeindicatesthetotaltimespentbythethreadexecutingsystemcode,andNameindicatesthenameofthethread.YoucanidentifythemainthreadintheresultlistwiththeIDnumber1,asshowninthefollowingscreenshot:

Page 82: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ClickontheStartNewThreadbuttonofyourapplicationandnoticethatanewthreadappearsinthelistascanbeobservedinthefollowingscreenshot,MyexampleThread:

Thethreadisactiveforaperiodof30seconds.EverytimeyouclickontheStartNewThreadbutton,anewthreadiscreated.

Thistoolisespeciallyusefulwhilecreatingthreadsinourapplicationapartfromthemainthread.Thankstothistool,wecaneasilycheckwhetherourthreadsarebeingexecutedatacertainpointoftheexecutionorwhethertheyareperformingasexpectedinmemoryusage.

Page 83: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 84: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

MethodprofilingThemethodprofilingtoolisusedtomeasuretheperformanceofthemethodsofaselectedprocess.Withthistool,youcanaccessthenumberofcallsofamethodandtheCPUtimespentontheirexecution.Therearetwotypesofvaluesavailable,theexclusivetimeandtheinclusivetime:

Exclusivetime:Thisreferstothetimespentintheexecutionofthemethoditself.Inclusivetime:Thisreferstothetotaltimespentintheexecutionofthemethod,whichincludesboththetimespentbythemethodaswellasthetimespentbyanyothermethodcalledinsidethemethod.

Toillustratetheworkingofthistool,wearegoingtorunthefollowingexample.CreateanewbasicprojectwithamainlayoutandamainactivityinAndroidStudio.Youcanalsoreusetheprojectcreatedintheprevioussection.Addabuttontothemainlayout,forexample,StartMethodHierarchy.Createanewmethodthatistobeexecutedwhenthebuttonisclickedandaddthefollowingcodeinthemethod:

publicvoidstartMethodHierarchy(Viewv){

secondMethod();

}

Addthesecondandthethirdmethodinyouractivity,shownasfollows:

privatevoidsecondMethod(){

thirdMethod();

}

privatevoidthirdMethod(){

try{

Thread.sleep(30000);

}catch(InterruptedExceptione){e.printStackTrace();}

}

Asseeninthepreviouscode,youcreateahierarchyofmethodcallsthatyouwillbeabletoobserveinthemethodprofiling.Totakealookatyourmethodprofilingdata,selectyourapplicationprocessinthedevicessectionandclickontheStartMethodProfilingiconpresentonthetoolbaroftheDevicessection.ClickontheStartMethodHierarchybuttonofyourapplicationandwaitforaperiodofatleast30secondssothatthethirdmethodfinishesitsexecution.Oncethethirdmethodfinishesitsexecution,youcanstopthemethodprofilingbyclickingontheStopMethodProfilingicon.

Whenyoustopthemethodprofiling,anewtabwiththeresultanttracewillappearwithintheDDMSperspective.Thetopofthisnewtabrepresentsthemethodcallsinatimegraphwhereeachrowbelongstoeachthreadoftheapplication.Thebottomofthetracerepresentsthesummaryofthetimespentonamethodinatable.

Tosearchforyourapplicationpackageandmainactivity,clickontheNamelabeltoorderthemethodsbytheirname,forexample,com/example/myapplication/app/MainActivity.Thethreemethods

Page 85: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

(startMethodHierarchy,secondMethod,andthirdMethod)shouldappearinthelistasisshowninthefollowingscreenshot:

OnexpandingthedetailedinformationofthesecondMethod,youcanseethattheparentisthestartMethodHierarchymethodandthatthethirdMethodmethodisitschild.Thisinformationispresentedinthefollowingscreenshot:

Also,examinetheexclusiveandinclusiverealtimes.TheprecedingscreenshotrevealsthattheinclusiverealtimeforthirdMethodwas30001,138ms,becauseofthesleepclauseof30seconds.ThetimespentintheexecutionofthesecondMethoditselfis0,053ms(exclusiverealtime),butsincetheinclusivetimeincludesthetimespentbythechildrenmethods,itsinclusiverealtimewas30001,191ms.

Methodprofilingcanbeusedtodetectmethodsthatarespendingmoretimethananticipatedintheirexecution.Withthisinformation,youcanlearnwhichmethodsarecausingproblemsandneedtobeoptimized.Youcanalsolearnwhichmethodsaremoretime-consumingsothatyoucanavoidunnecessarycallstothem.

Page 86: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 87: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

HeapTheHeaptabstoresallnewobjectscreatedintheapplication.Thegarbagecollector(GC)deletestheobjectsthatarenotreferredanymore,releasingunusedmemory.TheHeaptabdisplaystheheapusageforaselectedprocess.

Toillustratetheworkingofthistool,runthefollowingexample.CreateanewbasicprojectwithamainlayoutandamainactivityinAndroidStudio.Addabuttontothemainlayout,forexample,StartMemoryConsumption.Createanewmethodtobeexecutedwhenthebuttonisclickedandaddthefollowingcodetothemethod:

publicvoidmemoryConsumption(Viewv){

list=newArrayList<Button>();

for(inti=0;i<=1000;i++){

list.add(newButton(this));

}

}

Finally,addthedeclarationofthelistasaglobalvariableintheactivity.Thisway,youarepreventingtheGCtoreleasethememorythatstoresthelistafterthemethodfinishesitsexecution.Thedeclarationofthelistasaglobalvariableintheactivityisshownasfollows:

privateList<Button>list;

Inthismethod,youarecreatingalargenumberofnewobjects,forexample,alistcontaining1000buttons.Usingthismethod,youaregoingtoexaminehowthecreationofthelistisreflectedintheheap.RuntheapplicationandopentheDDMSperspective.SelecttheapplicationprocessintheDevicestabandclickontheUpdateHeapiconpresentonthetoolbartoenableit.TheheapinformationisshownafteraGCexecution.SelecttheHeaptabandclickontheCauseGCbutton,andyou’llseetheheapusage.

Thefirsttableofthetabdisplaysasummary:thetotalsize,theallocatedspace,thefreespace,andthenumberofallocatedobjects.Thestatisticstablepresentsthedetailsoftheobjectsthatareallocatedontheheapbyitstype:numberofobjects,totalsizeoftheobjects,sizeofthesmallestandlargestobjects,mediansize,andaveragesize.Wecanselecteachtypeindividually.Thisactionwillloadthebottombargraphwiththenumberofobjectsofthattypeorderedbyitssizeinbytes.Wecanthenclickonthegraphusingtherightbuttonofthemousetochangeitsproperties:title,colors,font,labels,andsoon.WecanalsosaveitasaPNGimage.

Observethenumberofdataobjectsallocatedontheheapasshowninthefollowingscreenshot:

Page 88: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ClickontheStartMemoryConsumptionbuttonoftheapplication.IntheDDMSperspective,causemoreGCexecutionsandnotehowthenumberofobjectsincreaseswhilethemethodisbeingexecuted.Thefollowingscreenshotshowstheheapinformationwhenthemethodhasalreadyfinisheditsexecution.Theallocateddataobjectshavegrownfrom24.822to60.821.

Finally,youcanalsotrytochangethedeclarationofthelistsothatitbecomesalocalvariableinthememoryConsumptionmethod.RepeatthepreviousprocessandnotethatthenewdataobjectsarereleasedbytheGConcetheexecutionofthemethodisfinished.

Page 89: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 90: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

AllocationTrackerTheAllocationTrackertabdisplaysthememoryallocationsoftheselectedprocess.Theallocationtracker,unliketheheaptool,showsthespecificobjectsbeingallocatedalongwiththethread,themethod,andthelinecodethatallocatedthem.

Youcanagainrunthepreviousexamplecreatedfortheheapmonitortoshowtheresultsoftheallocationtracker.SelecttheapplicationprocessandintheAllocationTrackertabandclickontheStartTrackingbuttontostarttrackingthememoryinformation.Now,clickontheGetAllocationsbutton.Thiswillgetthelistofallocatedobjects,whichincludesafilteronthetopofthetabthatyoucanusetofiltertheobjectsallocatedinyourownclasses.

ClickontheStartMemoryConsumptionbuttonoftheapplication.IntheDDMSperspective,againclickontheGetAllocationsbuttonandobservethenewobjectsthatarelistedintheresults.TheobjectsarethebuttonscreatedinthememoryConsumptionmethod.

Theresultstablepresentstheallocationsize,thethread,theobjectorclass,andthemethodinwhicheachobjectwasallocated.ClickonanyoftheButtonobjectstoseemoreinformationasshownthefollowingscreenshot.

YoucannoticethattheButtonobjectisallocatedinthemainactivityinthememoryConsumptionmethod,andthelineofcodethatallocateditisthelinenumber26.

Wheneveryouneedtoexaminetheobjectsallocatedintheheap,youcanusetheallocationtracker.Youcananalyzetheinteractionsinyourapplicationandimprovethememoryusage.

ThefollowingscreenshotshowsthedetailsoftheButtonobjects:

Page 91: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 92: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 93: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

NetworkStatisticsTheNetworkStatisticstabdisplaysthenetworkresourcesusedbyourapplication.Let’screateasimpleexampletotestthistool.Createanewprojectandaddthefollowingpermissionsinyourmanifestfile:

<uses-permissionandroid:name="android.permission.INTERNET"/>

<uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>

Inthemainlayout,addabuttonnamed,forexample,StartNetworkConnection.Createanewmethodtobeexecutedwhenthebuttonisclickedandaddthefollowingcode:

publicvoidstartNetworkConnection(Viewv){

newThread(newRunnable(){

publicvoidrun(){

try{

//Smallimage

TrafficStats.setThreadStatsTag(0x0001);

downloadURL("http://goo.gl/iGoYng");

TrafficStats.clearThreadStatsTag();

Thread.sleep(5000);

//Mediumimage

TrafficStats.setThreadStatsTag(0x0002);

downloadURL("http://goo.gl/eQHDRh");

TrafficStats.clearThreadStatsTag();

Thread.sleep(5000);

//Largeimage

TrafficStats.setThreadStatsTag(0x0003);

downloadURL("http://goo.gl/tUDnRv");

TrafficStats.clearThreadStatsTag();

}catch(IOExceptione){

e.printStackTrace();

}catch(InterruptedExceptionie){ie.printStackTrace();}

}

}).start();

}

Usingtheprecedingexample,youaredownloadingthreeimagesofdifferentsizes:small,medium,andlarge.Consideringthatconnectingtothenetworkisalongoperation,weneedtoexecutethecodeinanewthread.UsinganAsyncTaskclassisabettersolution,butinsteadtheThreadclassisusedtokeepthecodecleaner.Afterdownloadinganimageandbeforedownloadingthenextone,youwillhavetowaitforaperiodof5secondssothattheresultsdisplayedlaterarenotconfusing.Finally,toclearlyseparatethedifferentdownloads,weestablishadifferenttagforeachdownloadusingthesetThreadStatsTagandclearThreadStatsTagmethodsoftheTrafficStatsclass.TheTrafficStatsclassprovidesnetworktrafficstatisticssuchasthenumberofbytesorpackagesreceivedandtransmitted.

Page 94: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Todownloadanimage,youhavetoaddthefollowingmethodinyouractivity:

privateBitmapdownloadURL(Stringimage)throwsIOException{

InputStreamis=null;

try{

URLurl=newURL(image);

HttpURLConnectionconn=(HttpURLConnection)url.openConnection();

conn.setRequestMethod("GET");

conn.connect();

intresponse=conn.getResponseCode();

is=conn.getInputStream();

//ConverttheInputStreamintoabitmap

returnBitmapFactory.decodeStream(is);}finally{

if(is!=null){

is.close();

}

}

}

Inordertohavesimplecode,thepreviousmethoddoesnotexecuteanyadditionalactionsontheimages.Theimagesareonlydownloaded.

RuntheapplicationandopentheDDMSperspective.Togetthenetworkstatisticsofyourapplication,clickontheStartbuttonintheNetworktab.Then,clickontheStartNetworkConnectionbuttonoftheapplicationtostartdownloadingtheimages.Thedatatransferswillappearinthegraphaspacketsaresentorreceived.Thefollowingscreenshotshowstheresultsofthenetworkstatistics:

Page 95: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Inthepreviousscreenshot,thedownloadofthethreeimagescanbeeasilyidentified.ThecolumnsRXbytesandRXpacketsrepresentthetotalnumberofbytesandpacketsreceived.ThecolumnsTXbytesandTXpacketsrepresentthetotalnumberofbytesandpacketstransmitted.Wecanusethenetworkstatisticstooltooptimizethenetworkrequestsinourapplicationandcontrolthepacketsthatarebeingtransferredatacertainpointoftheexecution.

Page 96: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 97: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

FileExplorerTheFileExplorertabexposesthewholefilesystemofthedevice.Wecanexaminethesize,date,orpermissionsforeachelement.Navigateto/data/app/yourpackagetosearchforyourapplication.apkpackagefile.Tocheckthepathinwhichyourfilesaresavedwhentheyarecreatedoninternalstorage,youcanusethegetFilesDir()methodinyouractivity.Thefilesrelatedtoyourapplicationareusuallylocatedat/data/data/yourpackage.Let’sperformanexample.

Createanewprojectandinthemainlayoutaddabuttonnamed,forexample,CreateNewFile.Createanewmethodtobeexecutedwhenthebuttonisclickedandaddthefollowingcode:

publicvoidcreateNewFile(Viewv){

Stringstring="Helloworld!";

FileOutputStreamoutputStream;

try{

outputStream=openFileOutput("MyFile",MODE_PRIVATE);

outputStream.write(string.getBytes());

outputStream.close();

}catch(Exceptione){e.printStackTrace();}

}

Usingthepreviouscode,youarecreatinganewtextfileontheinternalstorageofourapplication.RuntheapplicationandopentheFileExplorertaboftheDDMSperspective.Navigateto/data/data/yourpackage/files,whichisempty.ClickontheCreateNewFilebuttonofyourapplicationandcheckthatthenewfilehasbeencreatedat/data/data/yourpackage/files,asshowninthefollowingscreenshot:

Page 98: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 99: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

EmulatorControlTheEmulatorControltabmakesitpossibletochangestatesoractivitiesinthevirtualdevice.Withthisemulator,youcantestyourapplicationinenvironmentsandsituationsthatwouldotherwisebeimpossibleortime-consumingtoachieve.Thisallowsyoutocheckwhetheritisbehavingasexpectedunderthefollowingspecialconditions:

TelephonyStatus:Youcanchoosethevoiceanddatastatus,changingitsspeedandlatencyTelephonyActions:Youcansimulateanincomingcalls,MMS,orSMSLocationControls:Youcanchangethegeolocationofthedevice

Page 100: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 101: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SystemInformationIntheSystemInformationtab,youcanaccessFrameRenderTime,CPUload,andMemoryusageofthedeviceintheformofgraphs.Youcanselectyourapplicationindividuallyandcompareitwiththerestofapplicationsthatarerunningonthedevice.

Ifyouclickonthegraphwiththerightbuttonofthemouse,youwillseeapopupwiththegraphpropertiessuchascolors,font,andtitle.ThegraphcanbecustomizedhereandcanalsobesavedasaPNGimage.

Page 102: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 103: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SummaryAftergoingthroughthischapter,youknowhowtodebuganapplication.YoucreatedseveralexamplesinthischaptersoyouknowhowtointerpretthedataprovidedbytheDDMSineachofthetabsavailable.Younowunderstandbetterhowthreads,methodcalls,memoryallocation,andnetworkusageworkinAndroidapplications.

Inthenextchapter,youwillapplyallthatyouhavelearnedfromthisandthepreviouschapter.YouwilllearnhowtoidentifyandmitigatethevulnerabilitiesinAndroidapplications,andyouwillbeabletocreatesecureapplicationsbyfollowingtherecommendationsincludedinthenextchapter.

Page 104: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 105: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Chapter4.MitigatingVulnerabilitiesInChapter1,IntroductiontoSoftwareSecurity,wealreadydiscussedthemostimportantvulnerabilitiesthatcanbeexploitedinordertocompromiseyourapplication.Now,youneedtolearnwhatmeasuresyoucantakeinordertoaddressthesevulnerabilitiesandmakeyourapplicationmoresecure.Whateasystepscanbetakeninordertoachievethis?

Thischapterwillshowyouhowtomitigatevulnerabilities.Removingoratleasttreatingvulnerabilitieswillsignificantlyreducetherisksofyoursystem.We’llbeginbylearninghowtovalidateinputfields.We’llalsolearnhowtoavoidcodeinjection,especiallythemostcommonone:SQLinjection.We’llthenseerecommendedpracticeswhenhandlingusercredentialsandwewilllearnhowtomakeourcomponentsmoresecureinordertoavoidvulnerabilitiesintheinterapplicationcommunications.

Thetopicsthatwillbecoveredinthischapterareasfollows:

InputvalidationPermissionsHandlingusers’dataandcredentialsInterapplicationcommunication

Page 106: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

InputvalidationAccordingtotheAndroiddevelopmentguidelines,thelackofsufficientinputvalidationmeasuresisoneofthemostcommonsecurityproblemsinAndroidapplications.Thereareseveralproblemsthatcanbederivedfrominsufficientinputvalidationsuchasbufferoverflows,nullpointers,off-by-oneerrors,inconsistenciesinthedatabase,andevencodeinjectionproblems.

Now,wewillseesometipsthatwillhelpustomitigatethisvulnerability.

WecanusetheinputTypeattributeinordertolimitthepossiblecharacterstheusercansetinafield.Forexample,ifwehaveanEditTextfieldwherewewantatelephonenumber,wecandefinetheEditTextasfollowsinyourlayoutfile:

<EditText

android:id="@+id/EditTextTelephone"

android:hint="@string/telephone"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:inputType="phone">

</EditText>

Althoughthisshouldnotbeconsideredasecurityfeature,itcanhelptomitigatethisvulnerability.However,inordertoensurethatthefieldiscorrect,additionalmeasuresshouldbetaken.

Forexample,ifwehaveEditTextforane-mail,wecancheckifitscontentmatchestheformatofane-mailsimplybyusingthePatternclassfromthejava.util.regexpackageandthePatternclassfromthejava.utilpackage:

publicvoidisEmail(EditTextet){

if(et.getText()==null)returnfalse;

elsereturnPatterns.EMAIL_ADDRESS.matcher

(et.getText().toString()).matches();

}

Therearemorepatternsavailableinthisclassthatwecanuse:

DOMAIN_NAME:ThispatternisusedtocheckthedomainnamesEMAIL_ADDRESS:Thispatternisusedtocheckthee-mailaddressesIP_ADDRESS:ThispatternisusedtochecktheIPaddressesPHONE:ThispatternisintendedtocheckthesubstringsthataresimilartophonenumbersintextandshouldnotbeusedtovalidateaphonenumberTOP_LEVEL_DOMAIN:ThispatternisusedtochecktheInternetAssignedNumbersAuthority(IANA)top-leveldomainsWEB_URL:ThispatternisusedtocheckmostpartsofthewebURLs

Ifweneedtovalidateaninputthatisnotinthislist,wecanuseourownregularexpressions.Thereareplentyofoptionstodothevalidation,butusingthePatternclassfromthejava.util.regexpackageisrecommended.Tolearnmoreaboutregularexpressions,whichwillallowyoutodefineyourownpatterns,youcanchecktheofficial

Page 107: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

documentationathttp://developer.android.com/reference/java/util/regex/Pattern.html.

Page 108: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SQLinjectionOneofthemostcommonandharmfulattacksisaparticularkindofcodeinjectionwhereunauthorizedSQLqueriescanaccessorevenalterourdatabase.Toillustratethissituation,let’sconsiderthefollowingexamplewhereyouhavethefollowingcodetochecktheusernameandpasswordthatwasjustenteredbytheuser:

//Wehavetheusername/passwordintwoEditTexts

Stringusername=usernameEditText.getText().toString();

Stringpassword=passwordEditText.getText().toString();

//Weformourquery

Stringquery=

"SELECT*FROMusersWHEREusername='"+username+"'AND

password='"+password+"'";

SQLiteDatabasedb=this.getWritableDatabase();

//ThemethodrawQueryperformsthequery

Cursorc=db.rawQuery(query,null);

//Incyouhaveacursortotheuseriftherewasamatchinthequery

if(c.getCount!=0)returntrue;//Ifthereisoneresult,grantaccess

Sowhat’stheproblemwiththeprecedingcode?AnattackercansimplywriteausernameandenterthefollowingstringinEditTextforpassword:

''OR'1'='1'

Thiswillgranttheuseraccesstotheusernamesincethestringquerywillappearasfollows:

"SELECT*FROMusersWHEREusername='admin'ANDpassword=''OR'1'=

'1'"

Thebestdefenseagainstthisvulnerabilityistouseparameterizedqueries.Themostimportantmethodsthatwewillbeusingareasfollows:

query(Uriuri,String[]projection,Stringselection,String[]

selectionArgs,StringsortOrder)

insert(Uriuri,ContentValues)

update(Uriuri,ContentValuesvalues,Stringselection,String[]

selectionArgs)

delete(Uriuri,Stringselection,String[]selectionArgs)

NotethatiftheselectionArgsparametercontainsanymeaningfulSQLcharacters,thosecharactersaresanitizedandcanthereforemeannoharmtotheintegrityofthedatabase.Inordertoexecutethecodeusedinthepreviousexamplesafely,wecanusethemethodshowninthefollowingcode:

//Wehavetheusername/passwordintwoEditTexts

Stringusername=usernameEditText.getText().toString();

Stringpassword=passwordEditText.getText().toString();

//WesettheURIofthetable;

StringtableName="USERS";

//Wesettheprojection

String[]projection=newString[]{"username","password"}

Page 109: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

//WesettheWHEREclauseorselection

Stringselection="username=?ANDpassword=?";

//Finallywesettheselectionarguments

String[]selectionArgs=newString[]{username,password};

//Nowwegetthedatabase

SQLiteDatabasedb=this.getWritableDatabase();

//ThemethodrawQueryperformsthequery

Cursorc=db.query(tableName,projection,selection,selectionArgs,null);

//Incyouhaveacursortotheuseriftherewasamatchinthequery

if(c.getCount!=0)returntrue;//Ifthereisoneresult,grantaccess

Page 110: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 111: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

PermissionsTheAndroidsandboxingsystemalienatesapplicationsfromeachother.Thismeansthattheapplicationsmustexplicitlyshareresourcesthroughtheuseofpermissions.Inordertoaccesstheadditionalcapabilities,weneedtodeclarethepermissionsthatwerequireinourmanifest,andthesepermissionsmustbeacceptedbytheuserafterinstallation.

Ifourapplicationdoesnothaveaccesstomanypermissions,itreducesthevulnerabilitiesthatmayaffectourapplication.Whendevelopingtheapplication,weshouldalwaystrytorequestasfewpermissionsaspossible.Forexample,trytostoredatalocallyinsteadofaskingforapermissionforexternalstorage.Ifitisnotpossible,wecanobviouslyrequestpermissionsbutweshouldaddressthevulnerabilitiesthatthesepermissionscanleadto.

Ifthesystem-definedpermissionsarenotenough,wecancreateourownpermissiontouse,whichwillbedefinedandwillrequireotherentitiestoaskforpermissionwhenrequired.Whencreatingapermission,wehavetoconsiderthedifferentprotectionlevelsavailable:

normal:Thisisthelowestpossiblepermissionlevelandissetbydefaultdangerous:Thispermissionlevelcanbegrantedbytheuserduringinstallationsignature:ThispermissionlevelisgrantedbythesystemifarequestingappissignedwiththesamecertificateastheappthatdeclaredthepermissionsignatureOrSystem:ThispermissionlevelisgrantedbythesystemifarequestingappisintheAndroidsystemimageorissignedwiththesamecertificateastheappthatdeclaredthepermission

Alwaystrytousethesignaturepermissionssincetheyaretransparenttotheuserandgrantaccessonlytoapplicationssignedbythesamedeveloper.Ifweneedtousethedangerouspermissionlevel,wehavetounderstandthatthispermissionisgrantedbytheuserand,therefore,needstobewellexplainedwhendefined.Userscandecidenottoinstalltheapplicationiftheydonotunderstandthepermissionthattheyhavetograntoriftheyperceiveitasapossibleharm.

Wewillseesomeexamplesofcreatingpermissionsinthefollowingsections.

Page 112: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 113: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Handlingauser’sdataandcredentialsThebestwaytohandleauser’sdataandcredentialsistominimizetheuseofthisinformation.Weshouldhaveaccesstotheuserdata,storeuserdata,ortransmituserdataonlywhenitiscompletelynecessary.

Inthecaseswherehandlinguser’sdataandcredentialsisnecessary,therearesomeconsiderationsthatweshouldhaveasdevelopers:

Considerusinghashornonreversibleformsofdataifthelogicofyourapplicationallowsit.Donotexposeuser’sdatatootherapplicationsonthedevice.Trytomaketheinterprocesscommunicationasstrictaspossible.Programmingwithmoreflexibleinterprocesscommunicationpermissionscanbemorecomfortable,butitcanalsobeahugevulnerabilityinyoursystem.MinimizetheuseofAPIsthataccesssensitiveinformation,especiallywhentheinformationispersonaldata.DifferentAPIshavedifferentprivacypoliciesandcanevenbemalicioussometimes.Makesureyouunderstandwhateachandeverypieceofdatathatwehavetosupplytoathird-partycomponentisfor.Whenyoudon’tunderstandwhyathird-partycomponentorAPIrequirescertaindata,itisbetternotprovideit.Limitthenumberoftimesusersareaskedforcredentialsasmuchaspossible.Askingforcredentialsanumberoftimescanmaketheuserlessawareofpossiblephishingattacks.LogsareasharedresourceinAndroid,andthereforeyoushouldbecarefulaboutwhichinformationyouwriteontotheselogs.Avoidtransmittingunnecessaryinformationwheneveritispossible.Whentreatingsensitiveinformation,evaluatewhetheritisnecessarytotransmitthatinformationontheserver.Iftheoperationcanbeperformedlocally,youshouldperformitlocally.Whenusingausernameandpasswordauthenticationsystem,besurenottostorethisinformationonthedevice.Ifitisstrictlynecessarytodoso,usecryptographymethodsandneverstoreitasplaindata.

YoucanavoidsomeoftheseproblemsusingtheAndroidclassAccountManager.TheclassAccountManagerprovidesaccesstotheuser’sonlineaccountsthataresetinthedevice.Google,Facebook,andWhatsApphavetheirownauthenticatorsthatareusedtomanagetheauthenticationofyourapplication.Thisalsohasanaddedvalue,thatis,toavoidtheprocessofregistration,whichsometimescandriveawaylazyusers.YouwilllearnmoreaboutthisauthenticationmethodinChapter7,AuthenticationMethods.

Page 114: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 115: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

InterapplicationcommunicationAsweseeninChapter2,SecurityinAndroidApplications,therearewaystocommunicatebetweenAndroidappsastheycannotsharedataduetoApplicationsandboxing.Thiscommunicationraisessecuritychallengesthatshouldnotbeoverlooked.

Page 116: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SecuringIntentsWhenusingIntents,therearetwokindsofvulnerabilities:unauthorizedIntentreceiptandIntentspoofing.AnunauthorizedIntentreceipthappenswhileusinganimplicitIntent.AstheIntentisbroadcasted,thereisnoguaranteethattheintendedrecipientwillreceiveit.AmaliciousapplicationcandeclareanimplicitIntentbydeclaringallthepossibleactionsintheintentfilter.ThiskindofinterceptioncanleadtoDoSandphishingattacks.

ThebestwaytoprotectagainstthiskindofvulnerabilityistobeverycautiouswithimplicitIntents.

NoteIfyouaresharingsomeprivateinformation,avoidusingimplicitIntents.

Whenpossible,andespeciallywhilesharingprivateinformation,yourapplicationshouldconsiderusingexplicitIntents.YoucanmaketherecipientexplicitbysettingthedestinationclassusingthemethodsetClassName(Contextctxt,StringclassName)asfollows:

Intenti=newIntent();

i.setClassName("com.example.myapplication",

"com.example.myapplication.MyActivity");

YoucanalsousethesetPackage(stringpackageName)methodtolimittheaccesstoasinglepackage:

Intenti=newIntent();

i.setPackage("com.example.myapplication");

AnapplicationwithanexportedcomponentthatdoesnotexpectIntentsfromamaliciousapplicationisvulnerabletoIntentspoofingattacks.Asadeveloper,youshouldlimityourcomponent’sexposurebysettingdifferentpermissionlevelrequirementsinthemanifest.

Thedefaultvaluesofcertainpropertiescanbemisleadingandmaychangefromoneversiontoanother.Itisagoodideatoindicatethenatureofyouractivityexplicitly.Forexample,let’smakeouractivityPrivateActivityprivate:

<activity

android:name=".PrivateActivity"

android:exported="false">

</activity>

Ifwewanttomakeouractivityaccessibletoexternalapplications,wecanexplicitlyindicatewhichapplicationshavetheselectiveaccess.Inthiscase,we’llmakeSelectiveActivityaccessibletootherapplicationsthroughourownpermission.Then,wecanusethispermissiontoindicateselectiveaccesstoSelectiveActivityusingtheIntentfilter,asshowninthefollowingcode:

<permission

android:description="Packtpermission"

android:name="packt.permission"

android:protectionLevel="signature"/>

Page 117: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

<activity

android:name=".SelectiveActivity"

android:exported="true"

android:permission="packt.permission">

<intent-filter>

<actionandroid:name="packt.action.NAME_ACTION"/>

</intent-filter>

</activity>

NoteIntentfiltersarenotasecurityfeature.Theyperforminputvalidationinyourreceiverinordertoverifythedatareceived.

Page 118: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SecuringthecontentprovidersInChapter2,SecurityinAndroidApplicationswehavelearnedaboutthecontentprovidermechanismthatallowsapplicationstosharerawdata.OneexternalcomponentcanuseanauthoritynameasahandletoperformSQLqueriestobothreadand/orwritecontent.Weshouldbecarefulanduseacontentprovideronlywhenitiscompletelynecessaryandtakethefollowingprecautions:

Useseparatereadandwriteprovider-levelpermissions.Wecanspecifyeachofthemwiththeattributeandroid:readPermissionandandroid:writePermission.Wecanalsouseboththeattributesbyusingandroid:permission.Usepath-permissiontospecifyeachURIthatyouwanttocontrol.Inthisway,youcanallowpermissionforasingleordifferentURIsinyourprovider.

ThismechanismisalsovulnerabletoSQLinjections.Inordertoeasilyavoidthisvulnerability,Androidsupportsparameterizedqueries.Thecontentprovidermethodssupportparameterization.ThemethodsthatareusedinparameterizedqueriestoacontentproviderarethesameastoanyotherSQLdatabase,andwehavealreadyseentheminthischapter.

Page 119: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 120: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SummaryInthischapter,youlearnedhowtomitigatethemostimportantvulnerabilitiesthatcanaffectourAndroidapplication.Youknowhowtouseregularexpressionsinordertovalidateaninput.YouhavealsolearnedaboutSQLinjectionsandhowparameterizedqueriescanhelpovercomethisvulnerability.Weknowhowtohandleuserandcriticalinformation.Finally,welearnedhowtouseIntentsandcontentprovidersinthemostsecurewaypossible.

Inthenextchapter,youwilllearnhowtopreservetheprivacyofourdata.Youwilllearnhowtohandlethedatawhenstoredlocally,thedifferentpossibilities,andwaystosecurethem.Youwillalsolearnaboutcryptographyandhowtoencryptlocaldata.

Page 121: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 122: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Chapter5.PreservingDataPrivacyMostapplicationsneedtosavesomekindofdata.YouwanttolearnhowtousethestorageoptionsprovidedbytheAndroidsystem,howcanyouprotectyourdataapplication,whatsecuritymeasuresshouldbetakenineachtypeofstorage,andhowcanyouuseencryptioninAndroidtopreservetheprivacyofyourdata.

ThischapterpresentsthemechanismsofferedbyAndroidtopreserveuserdataprivacy.Youwilllearntohandledatawhenit’sstoredonthedevice,whataretherisksinvolvedwiththestorage,thedifferentstorageoptions,andhowtosecurethestorage.Youwillalsolearnaboutcryptographyandhowtoencryptlocaldata.

Thetopicsthatwillbecoveredinthischapterare:

DataprivacyEncryptionUsingencryptiontostoredata

Page 123: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

DataprivacyDataprivacyisanimportantconcernforapplicationsbecausealotofinformationisstoredandmanagedintheapplications:contacts,e-mails,bankaccounts,messages,agenda,socialnetworks,andsoon.Someofthisinformationcanalsobeconsideredassensitivedata.Sensitivedatacanbeanyofthefollowingtypesofinformation:

InformationthatallowsyoutoidentifyadeviceortheuserofthatdevicesuchasthephonenumberortheInternationalMobileStationEquipmentIdentity(IMEI)numberofthatdeviceInformationfromtheresourcesofthedevicesuchastheGPSlocationofthatdeviceInformationcreatedandmanagedbytheapplicationsUsers’personaldatasuchasphotosormessages

Asadeveloper,yourresponsibilityistoprotecttheprivacyoftheinformationthatisstoredbyyourapplication.TherearedifferentmechanismstostoreyourapplicationdatainAndroid,andeachstoragemechanismismeanttokeepaspecifickindofinformation.ThestoragemechanismsprovidedbyAndroidaresharedpreferences,internalandexternalstorage,anddatabasestorage.

Page 124: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SharedpreferencesSharedpreferencesareusedtosavethecollectionofkey-valuepairsoftheprimitivedatatypessuchasboolean,float,int,long,andstring.Thesekey-valuespairsaresavedinyourapplicationdataintheformofanXMLfile,whichisstoredonthedeviceat/data/data/yourpackage/shared_prefs/.Ifyouonlyneedonesharedpreferencefile,youcangetthedefaultonebyusingthegetPreferences()method.Ifyouneedtocreatemorethanonesharedpreferencefile,youcanspecifyitsnamebyusingthegetSharedPreferences()method.Boththesemethodsarereceivedasparametersintheoperatingmode.Theoperatingmodeisstaticfinalint,whichcanhavethefollowingvalues:

MODE_PRIVATE:ThesharedpreferencesinthismodeareprivateandonlyyourapplicationcanworkwiththemMODE_WORLD_READABLE:ThesharedpreferencesinthismodecanbereadbyotherapplicationsMODE_WORLD_WRITEABLE:Thesharedpreferencesinthismodecanbeeditedbyotherapplications

Toillustratethesethreemodes,createanewapplicationprojectandintheonCreatemethodofthemainactivity,addthefollowingtocodetocreatethreesharedpreferencefiles:

SharedPreferencessharedPref=

getSharedPreferences("com.example.MyPrefsFile",MODE_PRIVATE);

SharedPreferences.Editoreditor=sharedPref.edit();

editor.putBoolean("KeyA",true);

editor.commit();

SharedPreferencessharedPref2=

getSharedPreferences("com.example.MyReadablePrefsFile",

MODE_WORLD_READABLE);

SharedPreferences.Editoreditor2=sharedPref2.edit();

editor2.putBoolean("KeyB",true);

editor2.commit();

SharedPreferencessharedPref3=

getSharedPreferences("com.example.MyWriteablePrefsFile",

MODE_WORLD_WRITEABLE);

SharedPreferences.Editoreditor3=sharedPref3.edit();

editor3.putBoolean("KeyC",true);

editor3.commit();

TheprivatesharedpreferencefileisnamedMyPrefsFile,thereadablesharedpreferencefileisnamedMyReadablePrefsFile,andthewriteablesharedpreferencefileisnamedMyWriteablePrefsFile.Ineachfile,wesaveaBooleanvalue.ExecutetheapplicationandopentheDDMSperspective.OpentheFileExplorertabandnavigatetoyourapplicationfilesunder/data/data/yourpackage/.You’llseethatanewshared_prefsfolderhasbeencreatedandinsidethisfolderthethreepreferencefileshavealsobeencreated,asshowninthefollowingscreenshot:

Page 125: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Observethesystempermissionsofthethreepreferencefiles.TheMyReadablePrefsFilefileallowsanyuserofthesystemtoreaditandtheMyWriteablePrefsFilefileallowsanyuserofthesystemtowriteit.Creatingasharedpreferencefileusinganyofthesetwomodesisverydangerousastheprivacyofthedatastoredinthemisnotpreserved.Therearebettermechanismsthansharedpreferencestodistributedatabetweenapplicationssuchasthecontentproviders.

NoteAlwayscreateyoursharedpreferencesusingtheprivatemodetoreducesecurityholes.

Themodeflagofthesharedpreferencesdeterminesonlythesystempermissionofthefile.TheXMLfileisnotencrypted.YoucancheckthisbydownloadingtheMyPrefsFilefilefromtheDDMSperspective.Openthefileusinganytexteditorandnoticethatthesaveddataisnotencryptedandcanberead.Thecontentofthedownloadedsharedpreferencefileisasshowninthefollowingcode:

<?xmlversion='1.0'encoding='utf-8'standalone='yes'?>

<map>

<booleanname="KeyA"value="true"/>

</map>

Theactualuser,anyapplicationwiththerootsystempermission,oranyattackerthatgainsaccesstothedeviceisabletoreadthisfile.

NoteDonotsavesensitivedataonsharedpreferencesastheyarestoredinanunencryptedfile.

Page 126: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

FilesintheinternalstorageInternalstorageallowsyoutosaveanytypeoffileinyourapplication’sdatadirectory,whichisstoredonthedeviceat/data/data/yourpackage/files/.Tocreateafile,youcanusetheopenFileOutput()methodinwhichyoucanspecifythemodeflagasaparameter.Themodeflagcanhavethefollowingvalues:

MODE_PRIVATE:Thefileisprivateinthismodeflagandonlyyourapplicationcanworkwithit.MODE_APPEND:Inthismodeflag,ifthefilealreadyexists,dataiswrittentotheendoftheexistingfile.Ifthefiledoesnotexist,thesystempermissionsforthefilearelikethepermissionsforMODE_PRIVATE.MODE_WORLD_READABLE:Thefileinthismodeflagcanbereadbyotherapplications.MODE_WORLD_WRITEABLE:Thefileinthismodeflagcanbeeditedbyotherapplications.

Justlikethesharedpreferences,creatingafileusingtheMODE_WORLD_READABLEorMODE_WORLD_WRITEABLEflagisverydangerousastheprivacyofthefilecontentisnotpreserved.Infact,boththeflagsweredeprecatedinAndroidAPILevel17.

NoteDonotusetheflagsMODE_WORLD_READABLEorMODE_WORLD_WRITEABLEtocreateyourfiles.

Thecreatedfilesarenotencrypted,thereforeyoucanencryptthefilecontenttopreserveitsprivacy.

Page 127: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

FilesintheexternalstorageExternalstoragereferstoaworld-readablepartofstorageinanAndroiddevice.WetendtothinkaboutexternalstorageasanSDcard,butactually,externalstoragecanalsobeanon-removablestorage.Externalstoragemaynotalwaysbeavailable,forexample,iftheSDcardisremovedincasethestoragewasprovidedbyanSDcard,orifthestoragehasbeenmountedtoaPC.Forthisreason,youmustalwayscheckexternalstoragestatebeforeusingit,usingthefollowingcode:

StringexStorageState=Environment.getExternalStorageState();

Intheexternalstorage,therearetwotypesoffiles:publicandprivate.Thesetwotermsshouldnotbeconfusedwiththefilepermissions.Thepublicandprivatefilesinexternalstoragearediscussedindetailasfollows:

Publicfiles:Thesefilesintheexternalstoragearefilesthatcanbesharedwithotherapplications,suchaspictures,music,orringtones.Tofetchthepathofthedirectoriesinwhichthesetypesoffilesshouldbestored,youcanusetheEnvironment.getExternalStoragePublicDirectory()method.Youindicatethetypeofthepubliccontentyouwanttoworkwithasaparameter.SomeexamplesforthistypeflagareDIRECTORY_PICTURES,DIRECTORY_ALARMS,DIRECTORY_DOCUMENTS,DIRECTORY_MUSIC,andDIRECTORY_RINGTONES.Privatefiles:Thesefilesontheexternalstoragearefilesthatbelongtoyourapplicationandhence,theyhavenoutilityoutsideyourapplication.Thesefilesareremovedwhenyourapplicationisuninstalled.Rememberthatalthoughthesetypesoffilesbelongtoyourapplication,theirpermissionsarestillworldreadable.Togetthepathofyourprivatedirectory,youcanusethecontext.getExternalFilesDir()method.

NoteDonotsavesensitiveinformationonexternalstoragebecausefilesinitaregloballyreadableandwriteable.

Page 128: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ThedatabasestorageSQLitedatabasesallowyoutostoreyourdatainaprivatedatabase.Thedatabaseisa.dbfile,whichiscreatedintheinternalstoragedirectoryofyourapplication.Thespecificpathforthisfileis/data/data/yourpackage/databases/.Databasesareprivatebutnotencryptedandthus,theuseroranyattackerthatgainsaccesstothedevicecanreadthedatabasecontent.

NoteSensitivedatashouldbeencryptedandverysensitivedatashouldnotbesavedonthedevice.

Page 129: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 130: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

EncryptionEncryptionistheprocessofencodingdataintoaformthatcannotbeunderstoodbyunauthorizedusers.Sensitivedatastoredinthedeviceshouldbeencryptedtopreserveitssecurity.Youcanencodedatatosaveitassharedpreferences,asfilesintheinternalstorage,indatabases,oreveninexternalstorage.Butyoushouldrememberthatsensitivedatamustnotbestoredonexternalstorage.Therearetwotypesofencryptionmethods:

Symmetric:Insymmetricencryption,thekeysforencodinganddecodingarethesame.Someexamplesofwell-knownsymmetricalgorithmsareDES,TripleDES,AES,Serpent,Twofish,andBlowfish.Asymmetricorpublic-key:Inasymmetricorpublic-keyencryption,thekeyforencodingisdifferentfromthekeyfordecoding.Theencryptionkeycanbepublicandhence,anyonecanencodedatausingthepublickey.Butonlytheowneroftheprivatekeyisabletodecodeit.Someexamplesofwell-knownasymmetricalgorithmsareRSA,Diffie-Hellman,ElGamal,andDSA.

Usingasymmetricalgorithmisenoughtoencryptourdatasincenobodyelseneedsthepublicencryptionkey.Thefollowingfigureexplainshowsymmetricencryptionworks:

Let’sseeanexampleofhowtoencryptsomeinformation.TheclassthatprovidesimplementationsforencryptionanddecryptionistheCipherclassfromthejavax.cryptopackage.Tousethisclass,youneedtocreateaninstanceindicatingtheencryptionalgorithmandoptionallythemodeorthepadding.Youcanseebothexamplesinthefollowingcodesnippets:

Cipherc=Cipher.getInstance("AES");

Cipherc=Cipher.getInstance("AES/CBC/PKCS5Padding");

ThenextstepistoinitializetheinstanceusingtheinitmethodoftheCipherclass.Thismethodreceivestheoperation—encryptordecrypt—andthekeytousefortheencryption,asshowninthefollowingcodesnippets:

c.init(Cipher.ENCRYPT_MODE,key);

c.init(Cipher.DECRYPT_MODE,key);

Toperformtheoperation,usethedoFinalmethod,asshowninthefollowingcode

Page 131: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

snippet:

byte[]finalBytes=c.doFinal(initialBytes);

Bothmethods—initanddoFinal—admitmoreparametersthatcanbeconsultedintheAndroidreferenceathttp://developer.android.com/reference/javax/crypto/Cipher.html.

Page 132: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TheencryptionmethodsThefollowingcodeshowsthecompletemethodtoencryptatextusingtheencryptionmethodsdiscussedintheprecedingsection:

publicbyte[]encrypt(Stringtext,Keykey)

throwsNoSuchPaddingException,NoSuchAlgorithmException,

InvalidKeyException,BadPaddingException,IllegalBlockSizeException

{

Cipherc=Cipher.getInstance("AES/CBC/PKCS5Padding");

c.init(Cipher.ENCRYPT_MODE,key);

byte[]encodedBytes=c.doFinal(text.getBytes());

returnencodedBytes;

}

Thefollowingcodeshowsthecompletemethodtodecryptatextusingthedecryptionmethodsdiscussedintheprecedingsection:

publicStringdecrypt(byte[]text,Keykey)

throwsNoSuchPaddingException,NoSuchAlgorithmException,

InvalidKeyException,BadPaddingException,IllegalBlockSizeException

{

Cipherc=Cipher.getInstance("AES/CBC/PKCS5Padding");

c.init(Cipher.DECRYPT_MODE,key);

byte[]decodedBytes=c.doFinal(text);

returnnewString(decodedBytes);

}

Page 133: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

GeneratingakeyTogenerateakeyinordertoencryptordecryptyourdata,youcanjustwritedownyourownkeyasaStringdatatype.Forexample,youcanusethefollowinglineofcodebutwithadifferentkey:

privatefinalStringkey="12345678901234567890123456789012";

ToobtainaKeyobjectsothatitcanbepassedasaparametertoyourencryptionanddecryptionmethods,youcanusetheSecretKeySpecclass.Thesimplestconstructorofthisclassreceivesthekeybytesandalgorithmname,asshowninthefollowinglineofcode:

SecretKeySpecsks=newSecretKeySpec(key.getBytes(),"AES");

Althoughwritingyourownkeyissimple,keepingitvisibleinyourcodeisnotsecure.Anyattackerthatgainsaccesstoyourcodecangetthekey.TherightwaytogenerateyourkeyisbyusingtheSecureRandomandKeyGeneratorclasses.Theobjectiveistoobfuscatethekey.

TheSecureRandomclass,asspecifiedintheAndroidreference,generatescryptographicallysecurepseudorandomnumbers.Usingthedefaultconstructorisrecommendedsothataninstanceofthestrongestproviderisreturned.Settingaseedmayalsobeinsecurebecauseitmayreplacethestrongdefaultseed.TheKeyGeneratorclassgeneratessymmetriccryptographickeys.Youshouldremembertosavethegeneratedkeyssothatyoucanusethemlater,evenwhentheapplicationisclosedandrestarted.

NoteYoushouldinvoketheSecureRandomclassusingthedefaultconstructorandwithoutsettinganyseed.

Thefollowingcodeshowsthecompletemethodtogenerateakeyforbothencryptionanddecryption:

publicSecretKeySpecgenerateKey()throwsNoSuchAlgorithmException

{

SecureRandomsecureRandom=newSecureRandom();

KeyGeneratorkeyGenerator=KeyGenerator.getInstance("AES");

keyGenerator.init(256,secureRandom);

SecretKeySpecsks=newSecretKeySpec(key.getEncoded(),"AES");

returnsks;

}

Page 134: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 135: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

UsingencryptiontostoredataUsingallthemethodsdiscussedintheearliersections,youcannowencryptanyinformationinyourapplication,asshowninthefollowingcode:

StringmyData="Mysecretinformation";

SecretKeySpecsks=generateKey();

byte[]encoded=encrypt(myData,sks);

Stringdecoded=decrypt(encoded,sks);

Log.d("MAIN-Encoded:",

Base64.encodeToString(encoded,Base64.DEFAULT));

Log.d("MAIN-Decoded:",decoded);

TheresultsgeneratedinLogCatareshowninthefollowingscreenshot:

Thepreviousexamplecanbeadaptedtoencryptthecontentofafileontheinternalstorageofyourapplication,asshowninthefollowingcode:

StringmyData="Mysecretinformationinmyinternalfile";

SecretKeySpecsks=generateKey();

byte[]encoded=encrypt(myData,sks);

FileOutputStreamfos=

openFileOutput("MyEncryptedFile.txt",Context.MODE_PRIVATE);

fos.write(encoded);

fos.close();

Onexecutingthecodeinyourmainactivity,theMyEncryptedFile.txtfilewillbecreatedintheinternalstorage,asseeninthefollowingscreenshot.Downloadthefileandopenitinanytexteditor.Noticethatthecontentisnotunderstandablebecauseitisencoded.

Itismandatoryforyoutostorethepersistentdataencryptedretainingthekeythathasbeenusedforencoding.Thekeycannotbesavedintheinternalstorageasitisconsideredtobesensitivedata.InAndroid4.3,theKeyStorefacilitywasprovidedbutKeyStoreonlystorespublicorprivatekeys.SymmetrickeyscannotbestoredinKeyStore.Toprovideadditionalprotection,thekeyshouldnotbedirectlyaccessibletotheapplication.

Page 136: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

NoteThekeyusedtoencryptyourdatashouldbekeptinasafeplace.Ifyoulosethekey,thedatacannotbedecoded.

Thebestsolutiontokeepyourkeysafeistosendittoyourserversothatthekeyisneverallocatedinthedeviceitself.Theuseroranyattackerthatgainsphysicalaccesstothedevicecannotobtainthekey.InChapter6,SecuringCommunications,youwilllearnhowtoprotectyourexternalcommunications.

Analternativesolutionistogeneratethekeyfromapasswordthattheuserhastointroducewhenstartinghis/herapplication.Thekeyisthereforenotstoredinthedeviceandisrememberedbytheuser.Thissolutionisverysecurebutitrequirestheusertointroduceapasswordeverytimetheapplicationisstarted,affectingtheusabilityofyourapplication.InChapter7,AuthenticationMethods,youwilllearnmoreabouttheauthenticationmethods.Togenerateakeyfromapassword,youcanusethePBKDF2algorithmimplementedintheSecretKeyFactoryclass,asshowninthefollowingcodesnippet:

SecretKeyFactoryskf=SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

ThekeyisgeneratedcreatingaPBEKeySpecobject,whichreceivesthepassword,abytearrayassalt,theiterationcountofthealgorithm,andthederivedkeylength.Themethodtogenerateakeyofthistypeisasshowninthefollowingcode:

privatestaticbyte[]salt="3r4ghe69".getBytes();

publicSecretKeySpecgeneratePassKey(Stringpassword)

throwsNoSuchAlgorithmException,InvalidKeySpecException{

KeySpeckeySpec=

newPBEKeySpec(password.toCharArray(),salt,500,256);

SecretKeyFactoryskf=

SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

SecretKeykey=skf.generateSecret(keySpec);

SecretKeySpecsks=newSecretKeySpec(key.getEncoded(),"AES");

returnsks;

}

Thesaltbytearraycanalsobestoredintheinternalstorage.

Page 137: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 138: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SummaryInthischapter,youlearnedmoreaboutthedifferenttypesofstorageforourdataapplicationinAndroid.Youalsolearnedaboutthecharacteristicsandrisksofeachtypeofstorage.Youalsoknowhowtoencrypttheuserdataandmanagethelocalstorage.Youhavecreatedthenecessarymethodstoencryptyoursensitivedataanduseitinyourapplication.

Inthenextchapter,youwilllearnhowtopreservetheprivacyofyourdatawhenitissentorreceivedoveranetworkfromaninternalorexternaldevice.YouwillalsolearnhowtosecurethenetworkusingprotocolssuchasHTTPS.

Page 139: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 140: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Chapter6.SecuringCommunicationsThischapterpresentsthemechanismsofferedbyAndroidtosecurecommunicationsbetweenanAndroidapplicationandanexternalentity.Bytheendofthischapter,youwillknowhowtosecureconnections.YouwillseesomeimplementationsthroughcodeexamplesusingAndroidStudio.

Mostapplicationsneedtosharesomesortofdata.Youshouldlearnhowtoprotectthisdataespeciallywhensensitiveinformationsuchaspersonaldataorauthenticationinformationisbeingtransferred.

Thetopicsthatwillbecoveredinthischapterare:

HTTPSSSLandTSLServerandclientcertificatesAndroidStudioCodeexamplesusingHTTPS

Page 141: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

HTTPSHypertextTransferProtocolSecure(HTTPS)isconsideredanapplicationlayerprotocolbasedonHTTP.Itisdesignedtotransferthehypertextdatasecurely.HTTPSislargelyusedbybankentities,onlineshops,andingeneral,anyonlineservicethatrequiressendingprotecteddata.

Firstofall,youneedtounderstandwhatHTTPSbeinganapplicationlayerprotocolmeans.Therearetwoimportantconceptualmodelsthatstandardizetheinternalfunctionsofacommunicationsystem.ThesemodelsaretheOpenSystemsInterconnection(OSI)modelandtheTransmissionControlProtocol/Internetprotocolsuite(TCP/IP)model.TheOSImodelconsistsofsevenabstractionlayerswhiletheTCP/IPmodelissimplifiedintoonlyfivelayers.Eachlayerdoesnotrepresentaprotocolbutalevelinwhichaprotocolisencapsulated.Forsimplicityandasitsuseismorecommon,wewillfocusontheTCP/IPmodel,discussedasfollows:

Thephysicallayer:Thislayerdefinesthemostbasicformofcommunication—theelectricalandphysicalspecifications.Theconnectionisdefinedbetweentwodirectlyconnectedelementsoveraphysicallyestablishedcommunicationmedium(cable,air,andsoon.).TheIEEE802.11specificationsoverwhichWi-Fi,Bluetooth,andevenUSBworkaresomeexamplesoftheprotocolsthatoperateinthephysicallayer.Thelinklayer:Thislayerdefinesthecommunicationestablishedbetweentwoelementsthatareinthesamelocalnetwork.Noticethattheremightbeseveralphysicalelements(routers,switches,andfurthermore)betweenthesetwoelements.TheMediaAccessControl(MAC)protocols,suchasEthernet,ISDN,orDSLworkinthislayer.Theinternetlayer:Thislayerisresponsibleforestablishingcommunicationbetweentwoelementsacrossmultiplenetworks.Therearetwomainfunctionscarriedoutinthislayer:hostidentificationandpacketrouting.ThemostknownexampleofaprotocolworkinginthislayerisIP,withIPv4andIPv6beingthemostextendedversionsofIP.Thetransportlayer:Thislayerdefinesthecommunicationbetweentwoprocessesindifferenthoststhatcanpotentiallybeseveralnetworksapart.Thislayerusesportsforthepurposeofprovidingcommunicationchannelsneededbytheapplications.ThemostcommonprotocolsthatworkonthetransportlayerareTCPandUDP.WhileTCPisconnection-orientedandisinchargeofidentifyinglostpackagesandresendingthem,UDPisconnectionlessanddoesnotperformthesechecks.Theapplicationlayer:Thisisthelayerthatapplicationsuseinordertoprovideuserservices.Thislayeristhemostimportantfordevelopers,sinceitisusuallytheonewewillbeworkingwith.Themodelofthislayerenablesyoutotreatthetransportlayerandlowerlayersasablackbox;theyprovideaserviceandyoudonotneedtoworryaboutthem.Therearehundredsofprotocolsthatworkovertheapplicationlayer,forexampleHTTPanditssecureversionHTTPS,FileTransferProtocol(FTP),SimpleMailTransferProtocol(SMTP),andsoon.TheapplicationlayerintheTCP/IPmodelcanbecomparedtoacombinationoftheapplicationlayer,

Page 142: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

presentationlayer,andsessionlayerintheOSImodel,asshowninthefollowingfigure:

HTTPSisconsideredtobeanapplicationlayerprotocolthatusescryptographicmethodsbasedonSecureSocketsLayer(SSL)orhiselderbrotherTransportLayerSecurity(TLS)toensurethesecurityofsensitivehypertextdata.However,technically,itisnotaprotocolitselfbuttheresultofcombiningHTTPintheapplicationlayerwithSSLorTLSinthetransportlayer.Thesecurityisthereforenotprovidedintheapplicationlayerbutinthetransportlayer.HTTPSalsospecifiesthatthetransportlayershouldusetheTCPprotocoltoensurethateverypackageisreceivedcorrectly,asshowninthefollowingfigure:

AlthoughHTTPSisbasedontheapplicationlayerprotocolHTTP,therearesomedifferencesbetweenthetwoofthem.Themostimportantare:

URLsstartwithhttp://whenusingtheHTTPprotocolandwithhttps://whenusingtheHTTPSprotocolBydefault,HTTPusestheTCPport80.Ontheotherhand,HTTPSusesport443bydefaultHTTPisvulnerabletoman-in-the-middleattacksandeavesdropping,andisdesigned

Page 143: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

tosolvethesevulnerabilitiesandminimizetherisks

IfyouwanttolearnmoreaboutthedifferencesbetweenHTTPandHTTPS,youcanuseapacketanalyzertoseehowtheexchangeofhypertextisperformedwitheachprotocol,asshowninthefollowingscreenshot.Todothis,werecommendWireshark(http://www.wireshark.org/),afreeandopensourcesoftware(OSS).YouwilllearnmoreaboutthistoolinChapter10,SupportingTools.

Page 144: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SSLandTLSSSLisacryptographicprotocolthatsupportssecureconnectionsoveranetwork.SSLwasoriginallydesignedbyNetscape.TherearethreemainversionsofSSLandbeingthelatestone,SSL3.0isthemostcommonlyusedovertheInternet.SSL3.0issupportedby99.5percentofthewebsitesontheInternet.

TLSisanupdateofSSL3.0.ItiscompatiblewithSSL3.0butitweakensthesecuritylevel.ThemostextendedversionofTLSisTLS1.0althoughtherearetwoupdates:TLS1.1andTLS1.2.TLS1.0issupportedby99.3percentofthewebsitesontheInternet.

AnSSLorTSLconnectionisalwaysinitiatedbytheclient.DatatransferredundertheSSLprotocolisencryptedusingasymmetricalalgorithmlikeDataEncryptionStandard(DES).Anasymmetricalalgorithmisusedtoexchangethekeysforthesymmetricalalgorithm.ThebasicstepstoestablishanSSLconnectionareasfollows:

1. Client->server:Theclientinitiatesthecommunicationwiththeserversendinga“Hello”message.Thismessagecontainsdifferentcryptographicoptionsavailabletotheclientsortedbypreferenceofuse.

2. Server->client:TheserverrespondsbysendingaHellomessage.Inthiscase,themessagecontainsthecryptographicmethodandthecompressionmethodchosen.

3. Server->client:Theserversendstheirdigitalcertificate.ThestandardistouseanX.509certificate.Iftheserverrequiresacertificatefromtheclient,aCertificateRequestmessageissent.

4. Client->server:Theclientcross-checksthecertificatereceivedfromtheserverwithalistofknownauthorities.Iftheauthorityisnotrecognized,theclientcanasktheuserforpermissiontomanuallyacceptthecertificate.Theclientalsoassessesiftheconnectionparametersareadequate.Ifeverythingisacceptable,theclientgeneratesasymmetricrandomkey,whichiscypheredwiththeserverpublickeyreceivedinstep3.Thecypheredsymmetrickeyisthensenttotheserver.

5. Client->server:Theserverreceivestheencryptedsymmetrickeyandproceedstodecryptitusinghisprivatekey.

6. Client<->server:Nowboththeclientandtheserverknowthesymmetrickeyandcanstartasecureconnection.

Page 145: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ServerandclientcertificatesInthissection,youwilllearnmoreabouthowcertificatesareusedandgenerated.Acertificateisadigitallysignedstatementfromanauthoritythatgrantsacertainvaluetothepublickeyofthesubject.Theyareusedinasymmetricencryptionmethods.

X.509certificateisastandardformatandmusthavethefollowinginformation:

Version:ThisistheX.509versionnumberSerialnumber:ThisisthesequencenumberofthecertificateSignaturealgorithm:ThisistheidentifierofthealgorithmusedtosignthecertificateIssuer:ThisisthenameoftheauthoritythatsignsthecertificateValidity:ThisistheperiodoftimeduringwhichthecertificateshouldbeconsideredvalidSubject:ThisisthenameofthesubjectofthepublickeySubjectpublickey:Thisisthepublickeyitselfanditsrelatedinformation

Youwillnowlearnhowtocreateaself-signedX.509certificatewithnoadditionalinstallationnecessarywhatsoever.Youwillseetwoeasywaystogenerateacertificate:usingatoolavailableineveryJavaDevelopmentKit(JDK)calledKeytoolfromtheterminalandusingthesametoolfromAndroidStudioinamorevisualway.TherearemanyotheroptionstocreatecertificatesliketheOpenSSLclient.

Page 146: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

KeytoolintheterminalOpenyouroperatingsystemterminalorgotoTools|OpenTerminalinAndroidStudio,andwritethefollowingcommand:

keytool-genkey-keyalgRSA-aliasselfsigned-keystoremy_keystore.jks-

storepasspassword-validity360-keysize2048

Theparameter–genkeyistheactionthetoolandisgoingtoperform.Inthiscase,itwillgenerateakey.Theparameter–keyalgspecifiesthealgorithmtobeused;inthiscase,wewanttouseRSA.Theparameter–aliasisforthenameoraliasofthekeysbeinggenerated.Theparameter–keystoreindicateswhichJKSfileisgoingtobeusedtostorethekeys.Theparameter–storepassindicatesthemasterpasswordusedtoaccesstheJKSfile.Ifthefileisbeingcreatedjustliketheonecreatedinthisexample,youcansetthepassword,butifthekeystorealreadyexists,youshouldintroduceitspassword.Theparameter–validityspecifiesthenumberofdaysthecertificateisvalid.Finally,withtheparameter–keysize,youcanindicatethesizeofthekeyinbits.Inthisexample,theparameter–keysizehasavalueof2048becausewehaveusedanRSAalgorithmwhosekeysarenormallybetween1024and2048bits.

Theexecutionofthepreviouscommandwillpromptasequenceofquestions.Makesurethatwhenaskedforyourfirstnameandlastname,youanswerwiththedomainnameoftheserveryouwanttogetthecertificatefrom.Ifyouhaveproblemsexecutingthis,youcanaddthekeytooltothepathofthesystem.Theapplicationisavailableinthe/binfolderofyourJDKinstallationfolderandcanalsobeexecuteddirectlyfromthere:

Whatisyourfirstandlastname?

[Unknown]:www.mydomain.com

Whatisthenameofyourorganizationalunit?

[Unknown]:MyApplication

Whatisthenameofyourorganization?

[Unknown]:MyCompany

WhatisthenameofyourCityorLocality?

[Unknown]:Murcia

WhatisthenameofyourStateorProvince?

[Unknown]:Murcia

Whatisthetwo-lettercountrycodeforthisunit?

[Unknown]:ES

Is<CN=www.mydomain.com,OU=MyApplication,O=MyCompany,L=Murcia,

ST=Murcia,C=ES>correct?

[no]:y

Enterkeypasswordfor<my_keystore>

(RETURNifsameaskeystorepassword):

Thisprocesswillgenerateamy_keystore.jksfileinaJKSformat.Thisfilecontainsbothprivatekeyandpublickeycertificatessomakesurenottoshareitasyourprivatekeyiswhatshouldbekeptfromotherentities.Inordertoextractthecertificate,youcanexecutethefollowingcommand:

keytool–export–aliasselfsigned–filecertificate.crt–keystore

my_keystore.jks–storepasspassword

Page 147: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Thiswillgenerateafilecalledcertificate.crt,whichcontainsthecertificate.Usingtheverysametool,wecanprintitscontentsusingthefollowingcommand:

keytool–printcert–filecertificate.crt

Thiswillprinttheinformationofourself-signedcertificate:

Owner:CN=www.mydomain.com,OU=MyApplication,O=MyCompany,L=Murcia,

ST=Murcia,C=ES

Issuer:CN=www.mydomain.com,OU=MyApplication,O=MyCompany,L=Murcia,

ST=Murcia,C=ES

Serialnumber:71e760d8

Validfrom:TueJun0317:42:47BST2014until:FriMay2917:42:47BST

2015

Certificatefingerprints:

MD5:63:34:55:9F:11:74:3A:02:EB:D3:8F:E2:7B:A3:1B:25

SHA1:CA:CF:6E:75:83:F9:01:D9:13:45:A5:DE:D2:95:EB:2E:31:BA:2D:B4

SHA256:

5A:A8:68:87:3D:89:B2:26:60:0F:55:DB:68:F1:24:6E:81:33:8B:3B:B2:57:07:36:D4:

06:B2:1A:C3:03:DE:F0

Algorithm:SHA256withRSA

Version:3

YoucanseehowOwnerandIssuerarethesamesincethecertificateisself-signed.IfitwassignedbyadifferentCA,IssuerwouldbethatCA.

Page 148: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

AndroidStudioAndroidStudiohasatooltosignyourAPK.ThisoptioninternallymakesuseofkeytooltocreateacertificatewithwhichtheAPKislatersigned.Youcanusethefirststepofthisprocesstogenerateyourcertificate.NavigatetoBuild|GenerateSignedAPK.Awizardwillappearaskingyoutoselectanalreadyexistingcertificateorcreateanewone.ClickonCreateNewandthefollowingwindowwillappear:

Asyoucansee,itasksfortheexactsameinformationwefilledinusingthekeytool.Youcanfollowthesameinstructionsasintheprevioussectiontofilltheinformationrequiredinthisform.

Ifyouwanttolearnmoreaboutcertificatesandcertificateauthorities,youcancheckthesectiononAppSigningintheAndroiddevelopmentdocumentationsincethesignatureofappsalsousesthecertificatesandcertificateauthoritiesathttp://developer.android.com/tools/publishing/app-signing.html.

Page 149: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 150: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

CodeexamplesusingHTTPSYoualreadyunderstandhowHTTPSworkstheoretically,buthowcananAndroiddeveloperusesecureconnectionsusingHTTPS?

ToestablishanHTTPconnection,allyouneedtodoisrunthefollowingthreelinesofcode:

URLurl=newURL("http://wikipedia.org");

HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();

InputStreamin=connection.getInputStream();

Wikipediasupportssecurecommunications,solet’schangethecodetomakeituseHTTPSinsteadofHTTP,asshowninthefollowingcode:

URLurl=newURL("https://wikipedia.org");

HttpsURLConnectionconnection=(HttpsURLConnection)url.openConnection();

InputStreamin=connection.getInputStream();

Canyouseethedifference?Well,ifyoucanseethedifference,congratulations!Youhaveaverysharpeye.Ifyoucan’t,hereisalittlehint:checktheprotocolintheURLagainandtheHttpURLConnectionclass.NowyouseethelittlesafterhttpintheURLandintheclassname,andyes,thatisallyouneedtodotostartasecurecommunicationwithaserverthatsupportsHTTPS.

Easyright?Well,thatisnotentirelytrue.YoumayworkwithcertificatesthataresignedbyatrustedCertificateAuthority(CA)oryoumaynotworkwithcertificatessignedbyatrustedCA.Therearethreedifferentcaseswherethiscanhappen:

TheCAthatissuedthecertificateisunknownThecertificatewasself-signedTheserverismissinganintermediateCA

IftheissuerofthecertificateisanunknownCA,anSSLHandshakExceptionwilloccur.Ifyouknowthisisgoingtohappen,youcancreateHttpsURLConnection,whichtrustscertainCAsthatarenotinthelistofthesystem-trustedCAs.TheclassTrustManagerisusedbythesysteminordertovalidateunknowncertificates.Inthefollowingexample,wewillcreateKeyStore,whichcontainsourtrustedCAs.WithKeyStore,wewillinitiateTrustManager,whichtruststheCAsincludedinKeyStore.WithTrustManagercreated,wewillinitiateanSSLconnection,shownasfollows:

//Firstwereadthecertificatefromafile

CertificateFactorycf=CertificateFactory.getInstance("X.509");

InputStreamcertificate=newBufferedInputStream(new

FileInputStream("my_keystore.jks"));

Certificateca=cf.generateCertificate(certificate);

//NowwecreatetheKeyStorecontainingthecertificate

Stringtype=KeyStore.getDefaultType();

KeyStorekeyStore=KeyStore.getInstance(type);

keyStore.load(null,null);

keyStore.setCertificateEntry("CA",ca);

Page 151: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

//NowwecaninitiatetheTrustManagerwithourKeyStore

Stringalgorithm=TrustManagerFactory.getDefaultAlgorithm();

TrustManagerFactorytmf=TrustManagerFactory.getInstance(algorithm);

tmf.init(keyStore);

//WiththeTrustManagerweinitiateaSSLContext

SSLContextcontext=SSLContext.getInstance("TLS");

context.init(null,tmf.getTrustManagers(),null);

//NowwecaninitiatetheconnectionusingtheSSLContext

URLurl=newURL("https://www.mydomain.com");

HttpsURLConnectionconnection=(HttpsURLConnection)url.openConnection();

connection.setSSLSocketFactory(context.getSocketFactory());

InputStreamin=urlConnection.getInputStream();

Asyoucansee,thelastfourlinesofthecodearesimilartowhatweweredoingbeforeworryingaboutthecertificateauthorities.Wehaveremovedsometryclausesforthesakeofcleancode,butifyoucopythecodetoAndroidStudio,justfollowitssuggestionstotreatexceptions.

Inthisexample,weusedthecertificatethatwegeneratedusingtheJavatool—keytool.Ifyouremember,thecertificatewegeneratedwasself-signed,whichisthesecondcaseandnotthefirst.Fromacodingperspective,bothsituationsaresimilar.Inthefirstone,CAisnotrecognizedsowecreateTrustManagerinordertoacknowledgeit.Inthesecondcase,itisexactlythesame,buttheissuerofthecertificateisalsothesubject.

IftheserverismissinganintermediateCA,therewillalsobeanSSLHandshakeExceptionsincethereisamissingCAinthetrustchain.Therearetwowaysyoucansolvethissituation:

Fromtheserverside:YoucanreconfiguretheservertoincludethemissingCAinthetrustchain.Thisisobviouslypossibleonlyifyouadministratetheserver.Fromtheclientside:TheonlyproblemyouhaveisthatthereisamissingCA,therefore,thatCAisanunknownCA.YoucanthereforeusetheclassTrustManageraswedidinthefirsttwocasestotrustthemissingCAdirectly.

Page 152: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 153: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SummaryInthischapter,youlearnedaboutnetworkcommunicationsinyourAndroidapplication.Nowyouunderstandhowthemostcommonprotocolstosecureconnectionswork.YoualsolearnedhowtousetheAPIsthatAndroidofferstosecureyourapplication’scommunications.Finally,youlearnedaboutcertificategeneration.

Inthenextchapter,youwilllearnaboutauthenticationmethods.Youwillseehowtwo-keyandthree-keyauthenticationmethodswork.Youwillalsolearnaboutusingbiometricauthenticationinyourapplication.

Page 154: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 155: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Chapter7.AuthenticationMethodsThischapterpresentsdifferenttypesofauthenticationmethodsusedinAndroidmobiledevices.Thischapterwillhelpreaderschoosetheproperauthenticationmethodfortheirmobileapplication.

First,youwilllearnaboutmultifactorauthenticationandthedifferentauthenticationfactors,suchastheknowledgefactor,thepossessionfactor,andtheinherencefactor.YouwillthenlearnhowtomakeyourownimplementationofaloginsystemforyourAndroidapplication.YouwillalsolearnaboutauthenticatingdifferentservicesusingAccountManager.

Thetopicsthatwillbecoveredinthischapterare:

MultifactorauthenticationLoginimplementationsAccountManager

Page 156: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

MultifactorauthenticationIfyouthinkofanauthenticationmethod,thefirstmethodthatwillcometoyourmindwillalwaysbethecombinationofausernameandapassword.Whileitssimplicitymakesitoneofthemostextendedauthenticationmethodsinallkindsofsoftware,itisnotthesafestmethod.Themultifactorauthenticationapproachcombinesasetofauthenticationmethods.Accessisgrantedonlyifeachmethodderivesapositiveresult.Two-factorauthenticationandthree-factorauthenticationinvolvetwoandthreeauthenticationfactors,respectively.Althoughtwo-factorauthenticationandaboveareoftenconsideredtobestrongauthenticationmethodsandareinfactmoresecure,youcanalsoachievestrongauthenticationforyourserviceusingonlyoneauthenticationfactor.Therearethreekindsofauthenticationfactorsthatserveasataxonomyforauthenticationtechniques:theknowledgefactor,thepossessionfactor,andtheinherencefactor.

Page 157: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TheknowledgefactorThecombinationofausernameandpasswordisanexampleofaknowledgefactor.Whenusingaknowledgefactor,theuserisrequiredtoprovideinformationhe/sheknowsinordertograntaccess:somethingtheuserknows.

Themostwidelyusedmethodsare:

Username/password:Thecombinationofacertainkindofidentifierfortheuser,generallyausernameorane-mailaddress,andapasswordisthemostextendedauthenticationtechnique.Whiletheusernameore-mailaddressmaybepublic,thepasswordshouldalwaysremainasecret.Pattern:Patternsareusedasauthenticationmethodssincethehumanbrainismorelikelytoremembergraphicalpatternsthanstringsofcharactersornumbers.Thereareseveraltypesofpatternsthatofteninvolvea3x3gridalthoughbiggergridsarealsoused.PIN:ThePINisaverybasicpasswordthathasbeentraditionallyusedinthebankingsystemforATMs,creditcards,andsoon.Itconsistsofanarrayofdigits.Itistechnicallyanimplementationofthepasswordtechniques,whereonlydigitsareallowed.

ThepatternandPINtechniquesareavailablebydefaultastheaccesscontroltoyourAndroidsystem,asshowninthefollowingscreenshot:

Page 158: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ThepossessionfactorThemostbasicandwell-knownexampleofapossessionfactorisakeythatopensadoor.Inordertoauthenticateausertryingtoaccessaresource,theyarerequiredtoprovideaphysicalobjecttheypossess:somethingtheuserhas.

Thereareseveralexamplesofpossessionfactors.Themosttypicaltechniquesbasedonapossessionfactorarephysicaltokenssuchassmartcardsormagneticcards.ThetechniquemostcommonlyusedinAndroidisprobablythecryptographickeys.Wealreadylearnedaboutcryptographickeysintheearlierchapters,andalthoughthesekeysaredigitalandtheuserdoesnothavematerialaccesstothem,theyareconsideredassomethingtheuserpossesses.ThereareotheralgorithmslikeTime-basedOne-TimePassword(TOTP).TOTPconsistsofcombiningasecretkeywiththecurrenttimestamptogenerateapasswordthatistemporarilyvalid.

Page 159: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TheinherencefactorTheinherencefactorisbasedonsomethingtheuseris.Thetechniquesbasedonthisfactoraretheonesthatareusedfrequently,buttheoneswiththebrightestfuture.Biometricauthenticationmeasuresthedistinctivecharacteristicsofindividualstoidentifytheuser.

Therearetwotypesofbiometricidentifiers:

Physiologicalcharacteristics:Thisiswhentheshapeofthebodyismeasured.Themostcommonlyknownexamplesarethefingerprintanalysis,facerecognition,andirisorretinarecognition.InAndroid,thereareseveralimplementationsoffacerecognition,andsomesmartphonescomewithahardwaresupportforfingerprintscanliketheHTCOneMax.Behavioralcharacteristics:Thisiswhenthebehaviorofapersonismeasured.Physiologicalcharacteristicsaremoreconsolidatedthanbehavioralcharacteristics.Themostextendedbehavioralcharacteristicisvoicerecognition.TherearedifferentimplementationsofvoicerecognitionforAndroid.

Page 160: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 161: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

LoginimplementationsWewillnowseeasmallexampleonhowtoperformauthenticationusingAndroid.Theexamplewearegoingtoseehereusestheloginandpasswordcombinationtechnique.Wearegoingtostartwithaverysimpleexampleandincreasethefunctionalitiesaswellasthecomplexitiesineveryiteration.

Firstofall,wewilldefineEditTextandButton,shownasfollows:

<EditText

android:id="@+id/etUsername"

android:layout_width="wrap_content"

android:layout_height="wrap_content"/>

<EditText

android:id="@+id/etPassword"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:inputType="textPassword"/>

<Button

android:id="@+id/bLogin"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="login"

android:text="Login"/>

Now,wearegoingtocheckwhetherthecombinationofausernameandpasswordisgoodornot.Tostart,wewillsimplycheckwhetherboththeusernameandpasswordareadmin,shownasfollows:

EditTextusername=(EditText)findViewById(R.id.etUsername);

EditTextpassword=(EditText)findViewById(R.id.etPassword);

StringsUsername=username.getText().toString();

StringsPassword=password.getText().toString();

if(sUsername.equals("admin")&&sPassword.equals("admin")){

//Grantaccess

}else{

Toast.makeText(getApplicationContext(),"Wrongpassword",

Toast.LENGTH_SHORT).show();

}

Thisisobviouslynotagoodexampleofasecureauthenticationmethodbutfromtheexample,wecanlearnsomeusefulthings.Forexample,theinputTypeparameterofEditTextcanbesettotextPasswordwhenusingapasswordfield.

Youarenormallygoingtomakearequesttoyourserverinordertoauthenticatetheuser.Forexample,inthiscase,weuseSimpleHTTPClienttomaketherequest,shownasfollows:

EditTextusername=(EditText)findViewById(R.id.etUsername);

EditTextpassword=(EditText)findViewById(R.id.etPassword);

StringsUsername=username.getText().toString();

Page 162: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

StringsPassword=password.getText().toString();

ArrayList<NameValuePair>params=newArrayList<NameValuePair>();

params.add(newBasicNameValuePair("username",sUsername);

params.add(newBasicNameValuePair("password",sPassword);

Stringresponse=SimpleHttpClient.executeHttpPost(

"http://www.mydomain.com/login",

params);

//Analyzeresponsewithwhattheserverissupposedtoanswer

Youhavetorealizethatthisimplementationalsohasbigproblems,evenbiggerthanthepreviousone.Inthiscase,theusernameandpasswordarebeingtransferredonlineandanyattackercouldseetheminplaintext.Inordertoavoidthis,wecanuseanHTTPSconnectionaswehaveseeninthepreviouschapter.

Therearesomeloginimplementationsthathashtheusernameandpasswordbeforesendingthemtotheserverinordertoincreasethesecurity,forexample,usingtheSHA1hashshownasfollows:

EditTextusername=(EditText)findViewById(R.id.editText1);

EditTextpassword=(EditText)findViewById(R.id.editText2);

StringsUsername=SHA1.Sha1Hash(username.getText().toString());

StringsPassword=SHA1.Sha1Hash(password.getText().toString());

ArrayList<NameValuePair>params=newArrayList<NameValuePair>();

params.add(newBasicNameValuePair("username",sUsername);

params.add(newBasicNameValuePair("password",sPassword);

Stringresponse=SimpleHttpClient.executeHttpPost(

"http://www.mydomain.com/login",

params);

//Analyzeresponsewithwhattheserverissupposedtoanswer

Theproblemwiththisimplementationisthatthehashedusernameandpasswordcanstillbesniffedbyanattackerastheyarestillbeingtransferredinplaintext.Thisisacommonmistake.Sowhenyoustorepasswords,youwanttomakesureyoustoretheirhashedversions.Thecorrectsolutionwouldbetosendthepasswordusingasecureconnection.Later,whenyouwanttocheckifthepasswordisright,youapplythehashfunctiontothepasswordprovidedbytheuserandcompareittothestoredhashedpasswordtoseewhethertheymatch.

InChapter6,SecuringCommunications,wesawhowtoestablishanHTTPSconnectionbetweenyourapplicationandaserver.Youcanusethatinformationandtheprecedingexampletocreateasecureloginimplementationforyourapplication.

Page 163: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 164: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

AccountManagerTheAccountManagerclassprovidesaccesstoalltheregisteredusers’onlineaccounts.Thisway,theuseronlyneedstoprovidehis/hercredentialsonceforeachaccountandthenhe/shecangrantaccesstotheseapplicationsinasimplerway.UsingtheAccountManagerclass,youcangetatokenthatcanbeusedasaformofauthenticationindifferentservices.

Thestepsthatyouneedtotakeinordertomakeuseofthisfeatureareasfollows:

1. First,youneedtomodifythemanifestfileandaddpermissiontousecredentials:

<uses-permission

android:name="android.permission.USE_CREDENTIALS">

</uses-permission>

2. Onceyourapplicationcanusecredentials,youcangetaninstanceofAccountManagerusingtheget(Contextc)method:

AccountManageram=AccountManager.get(this);

3. Now,youhaveaninstanceofAccountManager,butyouneedtoknowwhichaccountsareavailable.Todothis,youcanusethegetAccountsByType(Strings)method.TheStringparameteristhenameoftheaccounttype.Inthiscase,wewilllookfortheFacebookaccounts:

Account[]accounts=am.getAccountsByType("com.facebook.auth.login");

4. Youcanalsousenullastheparametertoobtainalltheavailableaccounts:

Account[]accounts=am.getAccountsByType(null);

5. ThegetAccountsByNamemethodshouldalsobecallediftheapplicationisusingapreviouslysavedaccountselectioninordertomakesurethatthisaccountstillexistsinthedevice.YoucancheckthisbylookinguptheaccountinthearrayofaccountsreturnedbygetAccountsByName.

6. Onceyouhavealistoftheavailableaccounts,youshouldasktheuserwhichaccountistobeused.Whentheselectionisdone,youcancallthemethod,shownasfollows:

getAuthToken(Accountaccount,StringauthTokenType,Bundleoptions,

Activityactivity,AccountManagerCallback<Bundle>callback,Handler

handler).

7. YouwillgetanauthenticationtokenintheAccountManagerFuture<Bundle>objectforaparticularaccount,whichwillautomaticallyprompttheuserforacceptanceifitisrequired.

8. Incasethetokenrequestreturnsanerror,therecouldbeacachedinstanceofanauthenticationtokenthatmaybebeingused.YoucancalltheinvalidateAuthToken(StringaccountType,StringauthToken)methodtoremoveanobsoletetoken.Oncetheobsoletetokenisremoved,youcanagainrequestanewtokenusingthegetAuthTokenmethod.

Page 165: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 166: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 167: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SummaryInthischapter,youlearnedaboutmultifactorauthenticationandthedifferenttechniquesavailableineachauthenticationfactor.Youalsolearnedhowtomakeyourownimplementationofasimpleloginsystem.Finally,youlearnedhowyoucangetauthenticationtokenstoaccessdifferentservicesbyusingAccountManager.

Inthenextchapter,youwilllearnhowtostarttestingyourapplication,testyouruserinterface,andusethetestenvironmentinAndroidStudio.

Page 168: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 169: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Chapter8.TestingYourApplicationYouhavelearnedhowtocreatesecureapplications.Now,youwanttoensurethequalityofyourAndroidapplication.WhatelementscanbetestedinAndroid?Howtestcasesaredeveloped?DoesAndroidStudiosupporttesting?

ThischapterintroducesthewaysoftestinganapplicationinAndroid.InAndroid,wecandesignteststoevaluatetheuserinterface(UI),activities,services,andcontentproviders.Inthischapter,wewilllearnaboutUItesting.

Thetopicsthatwillbecoveredinthechapterareasfollows:

TestinginAndroidTheuiautomatorAPITheuiautomatorviewertoolTheUItestprojectRunningUItestcases

Page 170: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TestinginAndroidThesecurityandqualityofAndroidapplicationsarethekeyfactorstoitssuccess.Testinghelpsyoudiscoverbugsanderrorsinyourapplication,measureitsaccuracy,andalsoimprovesecurity.

AndroidtestingisbasedonJUnit.JUnitisaframeworktowriterepeatabletestsinJava.Itevaluateswhethertheclassthatistobetestedisworkingasexpected.TherearetwotypesofteststobecreatedinanAndroidapplication:

TeststhatcanrunontheJavaVirtualMachine(JVM):IfyouwanttoteststandardJavaclassesthatdonotcalltheAndroidAPI,youcanuseplainJUnittests.TheexecutionofthistypeoftestisfasterbecauseitdoesnotrequireanytimefordeploymentonanAndroiddevice,especiallywhenrunningonanemulator.TeststhatrequiretheAndroidSDK:IfyouneedtoevaluateclassesthatuseAndroidAPI,testshavetoberunonanAndroiddeviceusingtheAndroidJUnitextensions.Fromnowon,wewillbeusingthiskindoftestsincewewanttolearnhowtocheckAndroidclassessuchasactivitiesortheUIcomponents.

Testsareimplementedinmethodscontainedintestclasses.Thesetestsareorganizedintestpackages.Byconvention,thetestpackagenameisthesameasyourapplicationpackagesuffixedwith.test.TestclassnamesarethesameastheelementtobetestedsuffixedwithTest.Forexample,thetestclassthatevaluatesyourMainActivityfileshouldbenamedMainActivityTest.Testmethodnamesareprefixedwithtest.SomeexamplesofmethodnamesaretestLayout()andtestOnClick().

Page 171: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 172: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TestingtheUITheUIcanbeevaluatedusingthewhite-boxtestingorblack-boxtesting.Inthewhite-boxtesting,UIcomponentsarecheckedintheactivitiesthatmanagethem.Activitytestingwillbeexplainedinthenextchapter,thatis,Chapter9,UnitandFunctionalTests.Theblack-boxtestingisbasedontheuiautomatorAPI.ThisAPIincludesclassestocaptureandmanipulatecomponentsintheapplicationundertest.Thistypeoftestdoesnotrequireyoutoknowtheinternalimplementationoftheapplication.

AndroidStudiodoesnotdirectlysupporttheuiautomatorframework,butsinceitisavailableintheAndroidSDK,wecanuseitanyway.Thestepstocompletethetestingprocessareasfollows:

1. Installtheapplicationundertestonadevice(realdeviceoranemulator).2. AnalyzetheUIcomponentsoftheapplicationundertest,employingthe

uiautomatorviewertool.3. CreateaJavatestprojecttoimplementyourtestcasesusingtheuiautomatorAPI.4. CompilethetestprojectintoaJARfileandinstallitonthedevice.5. Runtheimplementedtests.

WearegoingtoproceedwithacompleteUItestingexampleinthesuccessivesections,butfirstlet’slearnabouttheuiautomatorAPI.

Page 173: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TheuiautomatorAPITheuiautomatorAPIisincludedintheuiautomator.jarlibrary,whichcanbefoundinyourAndroidSDKinstallationfolder,underthe<android-sdk>/platforms/directory.TheAPIincludesaTestCaseclassthatextendstheJUnitTestCaseclass:UiAutomatorTestCase.TomanipulatetheUIcomponents,theUiDevice,UiSelector,UiObject,UiCollection,andUiScrollableclassesarealsosuppliedtotheAPI.

TheUiDeviceclassTheUiDeviceclassrepresentsthedevice.WecangettheUiDeviceinstancebycallingthegetUiDevice()method.Withthisinstanceobject,youcancheckpropertiessuchastheorientationorthedisplaysize.Youcanalsoperformdevice-levelactionssuchasclickingontheHomebuttonortakingascreenshot.Someexamplesoftheavailablemethodsareasfollows:

click(intx,inty):ThismethodperformsaclickatthespecifiedcoordinatesgetDisplaySizeDp():Thismethodreturnsthedisplaysizeindevice-independentpixelspressBack():ThismethodsimulatesapressonthebackbuttonpressHome():Thismethodsimulatesapressonthehomebuttonsleep():ThismethodsimulatesapressonthepowerbuttontosetthescreenofftakeScreenshot(Filestorepath):ThismethodtakesascreenshotofthecurrentscreenwakeUp():Thismethodsimulatesapressonthepowerbuttontosetthescreenon

TheUiSelectorclassTheUiSelectorclassrepresentsthesearchcriteriatoqueryanyUIelementonthescreen.Ifnocomponentisfound,UiAutomatorObjectNotFoundExceptionisthrown.Ifmorethanonecomponentisfound,thefirstoneinthelayouthierarchyisreturned.TheUiSelectorclassoffersmethodstorefinethesearch.Someofthemethodsareasfollows:

checked(booleanval):Thismethodmatcheselementsthatarechecked.childSelector(UiSelectorselector):Thismethodaddsachildselectorcriteriatothecurrentselector.className(StringclassName):Thismethodmatcheselementsofthespecifiedclass.Forexample,youcansearchforbuttonsusingthefollowingcode:

newUiSelector().className("android.widget.Button")

resourceID(Stringid):ThismethodmatchestheelementwiththespecifiedID.text(Stringtext):Thismethodmatcheselementscontainingtheindicatedvisibletext.Forexample,youcanrefinetheprevioussearchforbuttonsbyaddingasecondfilter,asshowninthefollowingcode:

newUiSelector().className("android.widget.Button").text("Continue")

TheUiObjectclass

Page 174: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TheUiObjectclassrepresentsaUIelement.TheUiObjectinstancesareobtainedfromtheUiSelectorinstances.TheclassUiObjectprovidesmethodstoperformactionsontheUIelements.Someexamplesofthemethodsareasfollows:

click():ThismethodperformsaclickatthecenteroftheUIelementexists():ThismethodcheckswhethertheelementexistsgetText():ThismethodreturnsthetextoftheelementisChecked():ThismethodreturnswhethertheelementiscurrentlycheckedornotsetText(Stringtext):Thismethodsetsthetextwhethertheelementallowsit(whetherit’saneditablefield)

TheUiCollectionclassTheUiCollectionclassrepresentsacollectionofitems.TheUiCollectioninstancesareobtainedfromtheUiSelectorinstancesthatreturnacontainerofotherchildUIelements.Themethodsprovidedbythisclassareallrelatedtotheselectionofchildren,shownasfollows:

getChildByDescription(UiSelectorchildPattern,Stringtext):ThismethodsearchesforachildbyitsdescriptionandreturnsaUiObjectobjectgetChildByInstance(UiSelectorchildPattern,intinstance):ThismethodsearchesforachildbyitsinstancenumberandreturnsaUiObjectobjectgetChildByText(UiSelectorchildPattern,Stringtext):ThismethodsearchesforachildbyitsvisibletextandreturnsaUiObjectobjectgetChildCount(UiSelectorchildPattern):Thismethodreturnsthechildcount

TheUiScrollableclassTheUiScrollableclassrepresentsascrollablecollectionofitems.Thisclassisusefultosimulatescrollingandbringshiddenelementsintoview.TheUiScrollableinstancesareobtainedfromtheUiSelectorinstances.ThisclasspresentsmethodssimilartothemethodsoftheUiCollectionclassandalsoprovidesmethodstosimulatescrolling:

scrollBackward():ThismethodperformsabackwardscrollscrollForward():ThismethodperformsaforwardscrollscrollToBeginning():ThismethodscrollstothebeginningscrollToEnd():Thismethodscrollstotheend

Page 175: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TheuiautomatorviewertoolTheuiautomatorviewertoolservestotakeasnapshotofthecurrentscreenonanAndroiddevicethatisconnectedtothedevelopmentmachine.Thesnapshotallowsyoutoexaminethelayoutcomponentsthatareincludedinthescreen.YoucanlearnabouthowtheyarestructuredandtheirpropertiessuchasIDs,texts,classes,andfurthermore.TheuiautomatorviewertoolisincludedinthetoolsdirectoryoftheAndroidSDKinstallation:<android-sdk>/tools/.

Let’slookatanexampletoshowhowthistoolworks.Sinceweareperformingblack-boxtesting,theuiautomatorviewertoolcanbeappliedtoanyapplicationalthoughitisnotdevelopedbyus,nordowehaveitssourcecode.WearegoingtousethedefaultAndroidclockapplicationbyfollowingthisprocedure:

1. OpenAndroidStudioandlaunchanAndroidVirtualDevice(AVD)intheemulator.Youcanalsousearealdeviceconnectedtoyourcomputer.

2. Whenthedeviceiscompletelyloaded,opentheapplicationdrawerandselecttheClockapplication.

3. BackintheAndroidStudioIDE,clickontheToolsmenuandselecttheOpenTerminaloptiontoopentheterminalpanel.

4. Usingtheterminal,navigatetotheAndroidtoolsfolderwheretheuiautomatorviewerexecutableisfound.InUnix-basedsystems,youcanfinditbyusingthecommand:

$cdandroidSDK/tools/

5. Launchuiautomatorviewerbyusingthecommand:

$./uiautomatorviewer

6. Theuiautomatorviewertoolisnowopenandshowsanemptywindow.Clickonthebuttoniconfromthetopbar,whichhintsattheDeviceScreenshot(uiautomatordump).Thisbuttonismarkedinredinthefollowingscreenshot.Thisoptionwilltakeasnapshotoftheclockapplicationthatisbeingdisplayedintheforegroundintheemulator.

Intheuiautomatorviewer,wecaninspectthelayoutelementsofthescreen.Thefollowingscreenshotshowstheuiautomatorvieweraftercapturingthescreenfromtheclockapplication.Ontheleftsideoftheviewer,thesnapshotisdisplayed.YoucanhoverthemouseoverittonavigateandselecttheUIcomponents.Onthetop-rightpartoftheviewer,thelayouthierarchyislisted.Wecanexpandandcollapsethelayoutsandselectindividualelements.Inthefollowingscreenshotofourexample,thelayoutcontainingthehourisselected.Onthebottom-rightpartoftheviewer,thepropertiesoftheselectedcomponentaredetailed.

Page 176: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 177: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 178: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TheUItestprojectThetestcodetoevaluatetheUIofanapplicationhastobeincludedinanormalJavaproject.ThisJavaprojectwillbebuiltintoaJARfile,whichwillbecopiedintheAndroiddevicetoevaluatetheapplicationundertest.SinceAndroidStudiodoesnotsupporttheuiautomatorframework,forthissectionyoucanuseanyothertoolthatallowsyoucreateaJavaproject.Therequiredstepsareasfollows:

1. CreateastandardJavaproject.ThisisthetestprojectwherethetestcodewillbeimplementedusingtheuiautomatorAPI.YoucancallthisprojectUITestProject.

2. ImporttheJUnitlibraryintoyourtestproject.Currently,JUnit3.8isthesupportedversion.

3. ImporttheAndroidlibraryasanexternalJARintoyourtestproject.ThisJARisnamedandroid.jarandisstoredinyourAndroidSDKinstallationfolderunder<android-sdk>/platforms/<sdk>/.

4. ImporttheuiautomatorlibraryasanexternalJARintoyourtestproject.ThisJARisnameduiautomator.jarandisstoredinyourAndroidSDKinstallationfolderunder<android-sdk>/platforms/<sdk>/.

5. Createanewclassinthesourcefolderofyourtestproject.YoucannametheclassClockTest.java.Thisclassisusedtoimplementyourtestcaseandtherefore,hastoextendtheUiAutomatorTestCaseclass.

6. AddyourtestcodeintheClockTestclass.

YourUItestcodeisnowready.Forourexample,let’saddsomesimplecodejusttodemonstratehowUItestingworks.CreateatestmethodnamedtestOpenAlarmstoevaluatethealarmbuttonintheclockapplication.Toperformaclickonthealarmbutton,weneedtoindicateitsID,whichcanbeextractedfromuiautomatorviewer,asshowninthefollowingscreenshot:

TheresourceIdmethodoftheUiSelectorclasscanbeusedtofindtheUIcomponentwhoseIDiscom.android.deskclock:id/alarms_button.Theobjectcreatedcanbecheckedandifeverythingisfine,aclickissimulatedonit:

publicclassClockTestextendsUiAutomatorTestCase{

publicvoidtestOpenAlarms()throwsUiObjectNotFoundException{

UiObjectalarmButton=newUiObject(newUiSelector().

resourceId("com.android.deskclock:id/alarms_button"));

Page 179: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

if(alarmButton.exists()&&alarmButton.isEnabled()){

alarmButton.click();

}

}

}

Page 180: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 181: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

RunningUItestcasesTheJavatestprojectcreatedintheprevioussectionhastobecompiledintoaJARfiletorunyourtestcases.TheJARfilehastobecopiedontothesameAndroiddeviceinwhichtheapplicationundertestisrunning.Followthenextstepstorunyourtestcase:

1. OpentheterminalpanelinAndroidStudio(Tools|OpenTerminal).2. NavigatetotheAndroidStudiostoolsfolderwheretheandroidexecutableisfound:

$cdandroidSDK/tools/

3. GettheIDoftheAndroidtargetthatyouwanttouseinyourproject.Executetheandroidexecutablewiththelistofthetargetactions.ThiscommandwilllisttheavailableAndroidtargetsalongwiththeirIDs:

$./androidlisttargets

4. Executetheandroidexecutablewiththecreateuitest-projectaction.Thiscommandreceivesthenameoftheoutputproject(-n),theIDoftheAndroidtarget(-t),andthepathofyourJavatestproject(-p)asparameters.Thisstepistogeneratetheproject’sbuildfileasatestproject:

$./androidcreateuitest-project–nUITest-t1

-p/Users/myUser/workspace/UITestProject

NoteTheUItestprojectscanonlytargetAPI16andabove;otherwise,anerrorwillbeprompted.

Asaresult,theUITestProject/build.xmlfileisgeneratedandthe/Users/myUser/workspace/UITestProject/build.xmlfileisadded.

5. BuildtheJARfilefromtheprojectusingthebuild.xmlfileobtainedbefore.6. CopytheJARfileintothedeviceusingtheadbutility:

$cdandroidSDK/platform-tools/

$./adbpush/Users/myUser/workspace/UITestProject/bin/UITest.jar

/data/local/tmp

7. Finally,executethenextcommandtoruntheUItestcaseontheconnecteddevice:

$./adbshelluiautomatorruntestUITest.jar-ccom.example.ClockTest

IfyouobservethedevicewhiletheUItestisbeingexecuted,youwillseehowtheactionsimplementedinthetestOpenAlarmstestmethodaresimulated.Theresultsareshownintheterminalpanelasyoucanseeinthefollowingscreenshot,inwhichthetestcaseexecutionhasbeensuccessful:

Page 182: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 183: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 184: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SummaryInthischapter,youlearnedabouttestinginAndroid.Youdevelopedblack-boxtestingforyouruserinterface.YoualsolearnedhowtocreateatestcaseforyourapplicationUIandhowyoucanrunitonadevice.

Inthenextchapter,youwilllearnmoreabouttestinginAndroid.Youwilldeveloptestcasestoevaluatetheactivitiesofyourapplication.YouwilluseunitandfunctionaltestsandsetupthetestingenvironmentusingAndroidStudio.

Page 185: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 186: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Chapter9.UnitandFunctionalTestsYoualreadylearnedaboutAndroidtestinginthepreviouschapter.Youknowhowtodevelopablack-boxtestoftheUIofyourapplication.Nowyouwanttolearnhowtoimplementthewhite-boxtestingforyourapplication.Aretheredifferenttypesofactivitytesting?DoesAndroidStudiosupportactivitytesting?Howcanyougettheresultsofyourtestcases?Wewillbecoveringthesepointsinthischapter.

Inthischapter,youwilllearnhowtouseunitteststhatallowdeveloperstoquicklyverifythestateandbehaviorofanactivityonitsown.Thechapterwillalsocoverfunctionaltests;theirmainpurposeistochecktheinteractionbetweencomponents.

Thetopicsthatwillbecoveredinthischapterareasfollows:

DifferencesbetweenunitandfunctionaltestsAndroidtestingAPICreatingasimpleunittestcaseCreatingasimplefunctionaltestGettingthetestresults

Page 187: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TestingactivitiesTherearetwopossiblemodesoftestingactivities:

Functionaltesting:Infunctionaltesting,theactivitybeingtestediscreatedusingthesysteminfrastructure.ThetestcodecancommunicatewiththeAndroidsystem,sendeventstotheUI,orlaunchanotheractivity.Unittesting:Inunittesting,theactivitybeingtestediscreatedwithminimalconnectiontothesysteminfrastructure.Theactivityistestedinisolation.

Inthischapter,wewillexploretheAndroidtestingAPItolearnabouttheclassesandmethodsthatwillhelpyoutesttheactivitiesofyourapplication.

Page 188: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ThetestcaseclassesTheAndroidtestingAPIisbasedonJUnit.AndroidJUnitextensionsareincludedintheandroid.testpackage.Thefollowingfigurepresentsthemainclassesthatareinvolvedwhentestingactivities:

Let’slearnmoreabouttheseclasses:

TestCase:ThisJUnitclassbelongstothejunit.framework.TheTestCasepackagerepresentsageneraltestcase.ThisclassisextendedbytheAndroidAPI.InstrumentationTestCase:Thisclassanditssubclassesbelongtotheandroid.testpackage.Itrepresentsatestcasethathasaccesstoinstrumentation.ActivityTestCase:Thisclassisusedtotestactivities,butformoreusefulclasses,youshoulduseoneofitssubclassesinsteadofthemainclass.ActivityInstrumentationTestCase2:Thisclassprovidesfunctionaltestingofanactivityandisparameterizedwiththeactivityundertest.Forexample,toevaluateyourMainActivity,youhavetocreateatestclassnamedMainActivityTestthatextendstheActivityInstrumentationTestCase2class,shownasfollows:

publicclassMainActivityTestextends

ActivityInstrumentationTestCase2<MainActivity>

ActivityUnitTestCase:Thisclassprovidesunittestingofanactivityandisparameterizedwiththeactivityundertest.Forexample,toevaluateyourMainActivity,youcancreateatestclassnamedMainActivityUnitTestthatextendstheActivityUnitTestCaseclass,shownasfollows:

publicclassMainActivityUnitTestextends

ActivityUnitTestCase<MainActivity>

ThereisanewtermthathasemergedfromthepreviousclassescalledInstrumentation.

Page 189: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

InstrumentationTheexecutionofanapplicationisruledbythelifecycle,whichisdeterminedbytheAndroidsystem.Forexample,thelifecycleofanactivityiscontrolledbytheinvocationofsomemethods:onCreate(),onResume(),onDestroy(),andsoon.ThesemethodsarecalledbytheAndroidsystemandyourcodecannotinvokethem,exceptwhiletesting.ThemechanismtoallowyourtestcodetoinvokecallbackmethodsisknownasAndroidinstrumentation.

Androidinstrumentationisasetofmethodstocontrolacomponentindependentofitsnormallifecycle.Toinvokethecallbackmethodsfromyourtestcode,youhavetousetheclassesthatareinstrumented.Forexample,tostarttheactivityundertest,youcanusethegetActivity()methodthatreturnstheactivityinstance.Foreachtestmethodinvocation,theactivitywillnotbecreateduntilthefirsttimethismethodiscalled.Instrumentationisnecessarytotestactivitiesconsideringthelifecycleofanactivityisbasedonthecallbackmethods.ThesecallbackmethodsincludetheUIeventsaswell.

Fromaninstrumentedtestcase,youcanusethegetInstrumentation()methodtogetaccesstoanInstrumentationobject.Thisclassprovidesmethodsrelatedtothesysteminteractionwiththeapplication.Thecompletedocumentationaboutthisclasscanbefoundat:http://developer.android.com/reference/android/app/Instrumentation.html.Someofthemostimportantmethodsareasfollows:

TheaddMonitormethod:ThismethodaddsamonitortogetinformationaboutaparticulartypeofIntentandcanbeusedtolookforthecreationofanactivity.AmonitorcanbecreatedindicatingIntentFilterordisplayingthenameoftheactivitytothemonitor.Optionally,themonitorcanblocktheactivitystarttoreturnitscannedresult.Youcanusethefollowingcalldefinitionstoaddamonitor:

ActivityMonitoraddMonitor(IntentFilterfilter,ActivityResultresult,

booleanblock).

ActivityMonitoraddMonitor(Stringcls,ActivityResultresult,boolean

block).

Thefollowinglineisanexamplelinecodetoaddamonitor:

Instrumentation.ActivityMonitormonitor=

getInstrumentation().addMonitor(SecondActivity.class.getName(),null,

false);

Theactivitylifecyclemethods:Themethodstocalltheactivitylifecyclemethodsare:callActivityOnCreate,callActivityOnDestroy,callActivityOnPause,callActivityOnRestart,callActivityOnResume,callActivityOnStart,finish,andsoon.Forexample,youcanpauseanactivityusingthefollowinglinecode:

getInstrumentation().callActivityOnPause(mActivity);

ThegetTargetContextmethod:Thismethodreturnsthecontextfortheapplication.ThestartActivitySyncmethod:Thismethodstartsanewactivityandwaitsforittobeginrunning.Thefunctionreturnswhenthenewactivityhasgonethroughthefull

Page 190: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

initializationafterthecalltoitsonCreatemethod.ThewaitForIdleSyncmethod:Thismethodwaitsfortheapplicationtobeidlesynchronously.

Page 191: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ThetestcasemethodsJUnit’sTestCaseclassprovidesthefollowingprotectedmethodsthatcanbeoverriddenbythesubclasses:

setUp():Thismethodisusedtoinitializethefixturestateofthetestcase.Itisexecutedbeforeeverytestmethodisrun.Ifyouoverridethismethod,thefirstlineofcodewillcallthesuperclass.AstandardsetUpmethodshouldfollowthegivencodedefinition:

@Override

protectedvoidsetUp()throwsException{

super.setUp();

//Initializethefixturestate

}

tearDown():Thismethodisusedtoteardownthefixturestateofthetestcase.Youshouldusethismethodtoreleaseresources.Itisexecutedafterrunningeverytestmethod.Ifyouoverridethismethod,thelastlineofthecodewillcallthesuperclass,shownasfollows:

@Override

protectedvoidtearDown()throwsException{

//Teardownthefixturestate

super.tearDown();

}

Thefixturestateisusuallyimplementedasagroupofmembervariablesbutitcanalsoconsistofdatabaseornetworkconnections.IfyouopenorinitconnectionsinthesetUpmethod,theyshouldbeclosedorreleasedinthetearDownmethod.WhentestingactivitiesinAndroid,youhavetoinitializetheactivityundertestinthesetUpmethod.ThiscanbedonewiththegetActivity()method.

Page 192: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TheAssertclassandmethodJUnit’sTestCaseclassextendstheAssertclass,whichprovidesasetofassertmethodstocheckforcertainconditions.Whenanassertmethodfails,AssertionFailedExceptionisthrown.Thetestrunnerwillhandlethemultipleassertionexceptionstopresentthetestingresults.Optionally,youcanspecifytheerrormessagethatwillbeshowniftheassertfails.YoucanreadtheAndroidreferenceoftheTestCaseclasstoexaminealltheavailablemethodsathttp://developer.android.com/reference/junit/framework/Assert.html.TheassertionmethodsprovidedbytheAssertsuperclassareasfollows:

assertEquals:Thismethodcheckswhetherthetwovaluesprovidedareequal.Itreceivestheactualandexpectedvaluethatistobecomparedwitheachother.Thismethodisoverloadedtosupportvaluesofdifferenttypes,suchasshort,String,char,int,byte,boolean,float,double,long,orObject.Forexample,thefollowingassertionmethodthrowsanexceptionsincebothvaluesarenotequal:

assertEquals(true,false);

assertTrueorassertFalse:ThesemethodscheckwhetherthegivenBooleanconditionistrueorfalse.assertNullorassertNotNull:Thesemethodscheckwhetheranobjectisnullornot.assertSameorassertNotSame:Thesemethodscheckwhethertwoobjectsrefertothesameobjectornot.fail:Thismethodfailsatest.Itcanbeusedtomakesurethatapartofcodeisneverreached,forexample,ifyouwanttotestthatamethodthrowsanexceptionwhenitreceivesawrongvalue,asshowninthefollowingcodesnippet:

try{

dontAcceptNullValuesMethod(null);

fail("Noexceptionwasthrown");

}catch(NullPointerExceptionne){

//OK

}

TheAndroidtestingAPI,whichextendsJUnit,providesadditionalandmorepowerfulassertionclasses:ViewAssertsandMoreAsserts.

TheViewAssertsclassTheassertionmethodsofferedbyJUnit’sAssertclassarenotenoughifyouwanttotestsomespecialAndroidobjectssuchastheonesrelatedtotheUI.TheViewAssertsclassimplementsmoresophisticatedmethodsrelatedtotheAndroidviews,thatis,fortheViewobjects.ThewholelistwithalltheassertionmethodscanbeexploredintheAndroidreferenceaboutthisclassathttp://developer.android.com/reference/android/test/ViewAsserts.html.Someofthemaredescribedasfollows:

assertBottomAlignedorassertLeftAlignedorassertRightAlignedor

Page 193: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

assertTopAligned(Viewfirst,Viewsecond):ThesemethodscheckthatthetwospecifiedViewobjectsarebottom,left,right,ortopaligned,respectivelyassertGroupContainsorassertGroupNotContains(ViewGroupparent,Viewchild):ThesemethodscheckwhetherthespecifiedViewGroupobjectcontainsthespecifiedchildViewassertHasScreenCoordinates(Vieworigin,Viewview,intx,inty):ThismethodchecksthatthespecifiedViewobjecthasaparticularpositionontheoriginscreenassertHorizontalCenterAlignedorassertVerticalCenterAligned(ViewreferenceViewview):ThesemethodscheckthatthespecifiedViewobjectishorizontallyorverticallyalignedwithrespecttothereferenceviewassertOffScreenAboveorassertOffScreenBelow(Vieworigin,Viewview):ThesemethodscheckthatthespecifiedViewobjectisaboveorbelowthevisiblescreenassertOnScreen(Vieworigin,Viewview):ThismethodchecksthatthespecifiedViewobjectisloadedonthescreenevenifitisnotvisible

TheMoreAssertsclassTheAndroidAPIextendssomeofthebasicassertionmethodsfromtheAssertclasstopresentsomeadditionalmethods.SomeofthemethodsincludedintheMoreAssertsclassare:

assertContainsRegex(StringexpectedRegex,Stringactual):Thismethodchecksthattheexpectedregularexpression(regex)containstheactualgivenstringassertContentsInAnyOrder(Iterable<?>actual,Object…expected):ThismethodchecksthattheiterableobjectcontainsthegivenobjectsandinanyorderassertContentsInOrder(Iterable<?>actual,Object…expected):Thismethodchecksthattheiterableobjectcontainsthegivenobjects,butinthesameorderassertEmpty:ThismethodchecksifacollectionisemptyassertEquals:ThismethodextendstheassertEqualsmethodfromJUnittocovercollections:theSetobjects,intarrays,Stringarrays,Objectarrays,andsoonassertMatchesRegex(StringexpectedRegex,Stringactual):Thismethodcheckswhethertheexpectedregexmatchesthegivenactualstringexactly

OppositemethodssuchasassertNotContainsRegex,assertNotEmpty,assertNotEquals,andassertNotMatchesRegexareincludedaswell.Allthesemethodsareoverloadedtooptionallyincludeacustomerrormessage.TheAndroidreferenceabouttheMoreAssertsclasscanbeinspectedtolearnmoreabouttheseassertmethodsathttp://developer.android.com/reference/android/test/MoreAsserts.html.

Page 194: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

UItestingandTouchUtilsThetestcodeisexecutedintwodifferentthreadsastheapplicationundertest,although,boththethreadsruninthesameprocess.WhentestingtheUIofanapplication,UIobjectscanbereferencedfromthetestcode,butyoucannotchangetheirpropertiesorsendevents.TherearetwostrategiestoinvokemethodsthatshouldrunintheUIthread:

Activity.runOnUiThread():ThismethodcreatesaRunnableobjectintheUIthreadinwhichyoucanaddthecodeintherun()method.Forexample,ifyouwanttorequestthefocusofaUIcomponent:

publicvoidtestComponent(){

mActivity.runOnUiThread(

newRunnable(){

publicvoidrun(){

mComponent.requestFocus();

}

}

);

}

@UiThreadTest:ThisannotationaffectsthewholemethodbecauseitisexecutedontheUIthread.Consideringtheannotationreferstoanentiremethod,statementsthatdonotinteractwiththeUIarenotallowedinit.Forexample,considerthepreviousexampleusingthisannotation,shownasfollows:

@UiThreadTest

publicvoidtestComponent(){

mComponent.requestFocus();

}

Thereisalsoahelperclassthatprovidesmethodstoperformtouchinteractionsontheviewofyourapplication:TouchUtils.ThetoucheventsaresenttotheUIthreadsafelyfromthetestthread;therefore,themethodsoftheTouchUtilsclassshouldnotbeinvokedintheUIthread.Someofthemethodsprovidedbythishelperclassareasfollows:

TheclickViewmethod:ThismethodsimulatesaclickonthecenterofaviewThedrag,dragQuarterScreenDown,dragViewBy,dragViewTo,dragViewToTopmethods:ThesemethodssimulateaclickonanUIelementandthendragitaccordinglyThelongClickViewmethod:ThismethodsimulatesalongpressclickonthecenterofaviewThescrollToToporscrollToBottommethods:ThesemethodsscrollaViewGrouptothetoporbottom

Page 195: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ThemockobjectclassesTheAndroidtestingAPIprovidessomeclassestocreatemocksystemobjects.Mockobjectsarefakeobjectsthatsimulatethebehaviorofrealobjectsbutaretotallycontrolledbythetest.Theyallowisolationoftestsfromtherestofthesystem.Mockobjectscan,forexample,simulateapartofthesystemthathasnotbeenimplementedyet,orapartthatisnotpracticaltobetested.

InAndroid,thefollowingmockclassescanbefound:MockApplication,MockContext,MockContentProvider,MockCursor,MockDialogInterface,MockPackageManager,MockResources,andMockContentResolver.Theseclassesareundertheandroid.test.mockpackage.Themethodsoftheseobjectsarenonfunctionalandthrowanexceptioniftheyarecalled.Youhavetooverridethemethodsthatyouwanttouse.

Page 196: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 197: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

CreatinganactivitytestInthissection,wewillcreateanexampleapplicationsothatwecanlearnhowtoimplementthetestcasestoevaluateit.Someofthemethodspresentedintheprevioussectionwillbeputintopractice.Youcandownloadtheexamplecodefilesfromyouraccountathttp://www.packtpub.com.

Ourexampleisasimplealarmapplicationthatconsistsoftwoactivities:MainActivityandSecondActivity.TheMainActivityimplementsaself-builtdigitalclockusingtextviewsandbuttons.Thepurposeofcreatingaself-builtdigitalclockistohavemorecodeandelementstouseinourtests.ThelayoutofMainActivityisarelativeonethatincludestwotextviews:oneforthehour(thetvHourID)andonefortheminutes(thetvMinuteID).Therearetwobuttonsbelowtheclock:onetosubtract10minutesfromtheclock(thebMinusID)andonetoadd10minutestotheclock(thebPlusID).Thereisalsoanedittextfieldtospecifythealarmname.Finally,thereisabuttontolaunchthesecondactivity(thebValidateID).Eachbuttonhasapertinentmethodthatreceivestheclickeventwhenthebuttonispressed.Thelayoutlookslikethefollowingscreenshot:

TheSecondActivityreceivesthehourfromtheMainActivityandshowsitsvalueinatextviewsimulatingthatthealarmwassaved.Theobjectivetocreatethissecondactivityistobeabletotestthelaunchofanotheractivityinourtestcase.

OpenAndroidStudioandtheAndroidprojectundertest.Youcancreateablankprojectwithamainactivityandlayout.Laterinthischapter,wewilladdanexamplecodetorunthetestcases.Intheprojectstructure,thereisafolderandapackagewherethetestswill

Page 198: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

besaved:/src/androidTest/java/<your_package>.Ifyoudon’thavethispackage,youshouldaddit.

Page 199: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

CreatingaunittestAunittestevaluatestheactivityinisolation.Unittestsareused,forexample,tocheckamethodoftheactivityortocheckthattheactivityhasthecorrectlayout.Inthissection,wearegoingtocreateaunittestforthemainactivityofourexampleproject.

CreateanewclassinthetestpackageofyourapplicationnamedMainActivityUnitTest.ThisclassextendstheActivityUnitTestCaseclass,whichisthetestcaseclasstocreateunittests.Thetestclasshastobeparameterizedwiththeactivityundertestandyoualsoneedtoaddthetestcaseconstructor,shownasfollows:

publicclassMainActivityUnitTestextends

ActivityUnitTestCase<MainActivity>{

publicMainActivityUnitTest(){

super(MainActivity.class);

}

Forthisunittestexample,wewillcreatethesetUpmethod,andthenwewilltestthebuttonstomanagetheclock,mainlayout,andlaunchofthesecondactivity.

TheunittestsetupThefixturestateofourtestcaseincludesthereferencetotheactivityundertestandthelayoutobjectsthatwillbeusedinthetestmethods,shownasfollows:

privateMainActivitymActivity;

privateTextViewmHour,mMinute;

privateButtonmValidate,mMinus,mPlus;

ThegetActivity()methodinitializestheactivityundertest,butrememberthatinunittests,theactivityistestedinisolationandtherefore,itisnotautomaticallystartedbythesystem.TheactivityhastobestartedinyourowncodeviaanIntentobject.ThecodeforthesetUpmethodisasfollows:

@Override

protectedvoidsetUp()throwsException{

super.setUp();

Intentintent=newIntent(getInstrumentation().getTargetContext(),

MainActivity.class);

startActivity(intent,null,null);

mActivity=getActivity();

mHour=(TextView)mActivity.findViewById(R.id.tvHour);

mMinute=(TextView)mActivity.findViewById(R.id.tvMinute);

mValidate=(Button)mActivity.findViewById(R.id.bValidate);

mMinus=(Button)mActivity.findViewById(R.id.bMinus);

mPlus=(Button)mActivity.findViewById(R.id.bPlus);

}

LayoutelementsareaccessedbytheirIDasusual.Becausethetestcodeisincludedinadifferentpackage,youhavetoimporttheRclassfromtheapplicationpackage.

Page 200: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TheclocktestLet’sstartimplementingtestmethods.First,wewillcheckwhethertheclockworksproperly.Thetestmethodconsistsofclickingonboththebuttons,thatis,-10minand+10minandcheckingwhetherthevaluesforthehourandminutetextsaretheexpectedones.Sincetheactivityrunsinisolation,theTouchUtilslibrarycannotbeused,buttheperformClickmethodcanbeinvokedinstead,asfollows:

publicvoidtestClock(){

mMinus.performClick();

assertEquals("11",mHour.getText());

assertEquals("50",mMinute.getText());

mPlus.performClick();

mPlus.performClick();

mMinus.performClick();

assertEquals("00",mHour.getText());

assertEquals("00",mMinute.getText());

}

Fromthedefaultlayoutvalues,theinitialhouris00:00.Onclickingtheminusbuttononce,theresultanthouris11:50.Onclickingtheplusbuttontwiceandtheminusbuttononce,thefinalhourisagain00:00.TheconditionsarecheckedusingtheassertEqualsmethod.

TipIfyouwanttotestcomplexUIevents,donotuseunittests;youshouldcreateafunctionaltest(ActivityInstrumentationTestCase2testcase).

ThelayouttestThesecondtestmethodtobeimplementedisusedtotestwhetherthelayoutiscorrect.ThetextoftheUIelementscanbechecked,ortheassertionmethodsoftheclassViewAssertscanalsobeinvoked.AsimpleexampleofaUItestforourexampleisshownasfollows:

publicvoidtestUI(){

assertNotNull("Hourtextviewnotfound",mHour);

assertEquals("Wrongbuttonlabel","Validate",mValidate.getText());

ViewAsserts.assertBottomAligned(mHour,mMinute);

}

TheactivityIntenttestThelasttestmethodwewillimplementisgoingtocheckwhetherthesecondactivityisproperlylaunched.First,theValidatebuttonisclickedtoexecutethecodethatwillcreateIntentofthesecondactivity.ThegetStartedActivityIntentmethodwillreturnifanyIntentwaslaunched.Thecodesnippetforthetestmethodisasfollows:

publicvoidtestSecondActivityLaunch(){

mValidate.performClick();

Page 201: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

IntenttriggeredIntent=getStartedActivityIntent();

assertNotNull("Intentwasnull",triggeredIntent);

Stringpayload=triggeredIntent.getExtras().getString("hour");

assertEquals("WrongdatapassedtoSecondActivity","00",payload);

}

Inthetestmethod,Intentischeckedtoevaluatewhetheritisnull.Furthermore,thedatapassedtothesecondactivitycanbeexaminedaswell.

NoteThecreatedIntentisnotreallysenttothesystembecausetheactivityrunsinisolation.

Page 202: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

CreatingafunctionaltestAfunctionaltestevaluatestheactivityanditscommunicationwiththeAndroidsystem.TheUIeventsorchangesinthelifecycleshouldbecheckedinafunctionaltest.Inthissection,wewillcreateafunctionaltestforthemainactivityofourexampleproject.

CreateanewclassinthetestpackageofyourapplicationnamedMainActivityTest.ThisclassextendstheActivityInstrumentationTestCase2classandhastobeparameterizedwiththeactivityundertest,shownasfollows:

publicclassMainActivityTestextends

ActivityInstrumentationTestCase2<MainActivity>{

publicMainActivityTest(){

super(MainActivity.class);

}

Forthisexampleoffunctionaltests,wewillevaluatetheUI(white-boxtesting),launchofthesecondactivity,andstatemanagement.

ThefunctionaltestsetupThefixturestateofourtestcaseincludesthereferencetotheactivityundertestandthelayoutobjectsthatwillbeusedinthetestmethods,shownasfollows:

privateMainActivitymActivity;

privateTextViewmHour,mMinute;

privateButtonmValidate;

privateEditTextmName;

Unlikeunittesting,thegetActivity()methodisenoughtostarttheactivityundertest.ThesetUpmethodcodeisshownasfollows:

@Override

protectedvoidsetUp()throwsException{

super.setUp();

setActivityInitialTouchMode(false);

mActivity=getActivity();

mHour=(TextView)mActivity.findViewById(R.id.tvHour);

mMinute=(TextView)mActivity.findViewById(R.id.tvMinute);

mValidate=(Button)mActivity.findViewById(R.id.bValidate);

mName=(EditText)mActivity.findViewById(R.id.etName);

}

ThesetActivityInitialTouchModemethodsetstheinitialtouchmodefortheactivity.Settingthemodeasfalseisnecessarytosetoffthetouchmodeinthedevicesothatthekeyeventsarenotignored.ThismethodshouldbecalledbeforestartingtheactivitywiththegetActivitymethodandalsobecauseitcannotbeexecutedontheUIthread.

TheUItestInthefirsttestmethod,asanexampleofUItesting,wewillevaluateEditTextcontaining

Page 203: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

thenameofthealarm.Thestepstobeimplementedforthistestareasfollows:

1. Requestthefocusoftheedittextelement.ThisstepinteractswithViewoftheapplicationandtherefore,itshouldrunintheUIthread,thatis,themainthreadoftheapplication.TorunsomecodeintheUIthread,youcanusetherunOnUiThread()methodoftheactivityundertest.

2. Sendkeyeventstowritethealarmname.Onlyaninstrumentedclassallowstosendkeyeventstotheactivityundertest.Thankstoinstrumentation,itisnotnecessarytorunthesecallsintheUIthreadeither.

3. Testthatthetextoftheeditfieldisthesameasexpected.

TheUItestmethodisshownasfollows:

publicvoidtestEditTextName(){

mActivity.runOnUiThread(newRunnable(){

publicvoidrun(){

mName.requestFocus();

}

});

sendKeys(KeyEvent.KEYCODE_A);

sendKeys(KeyEvent.KEYCODE_L);

sendKeys(KeyEvent.KEYCODE_1);

getInstrumentation().waitForIdleSync();

assertEquals("Wrongalarmname","al1",mName.getText().toString());

}

ThewaitForIdleSyncmethodiscalledtowaitfortheapplicationtobeidle.Thus,weknowforsurethatthetexthasbeencompletelyinsertedinthefield.

TheactivityIntenttestUnlikeunittests,whenanewIntentiscreated,itissenttotheAndroidsystem.Tomonitorthelaunchedactivity,wecanregisteranActivityMonitorobjectusinginstrumentation.Anotherdifferencebetweenfunctionalandunittestsisthatinafunctionaltest,wecanusetheTouchUtilslibrarytosendaclickeventonaUIelement,shownasfollows:

publicvoidtestSecondActivityLaunch(){

Instrumentation.ActivityMonitormonitor=

getInstrumentation().addMonitor(SecondActivity.class.getName(),null,

false);

TouchUtils.clickView(this,mValidate);

SecondActivitysecondActivity=(SecondActivity)

monitor.waitForActivityWithTimeout(2000);

assertNotNull(secondActivity);

getInstrumentation().removeMonitor(monitor);

sendKeys(KeyEvent.KEYCODE_BACK);

}

Page 204: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Ourcodeperformsthefollowingstepsforthistestmethod:

1. Createstheactivitymonitor.2. SendsaclickeventtotheValidatebutton.3. Whenthemonitorreceivesthelaunchedactivity,itverifiesthattheactivitywas

launched.4. Deletesthemonitor.5. Closesthesecondactivitybysendingaclickeventtothedevice’sbackbutton.

ThestatemanagementtestThislasttestmethodcheckswhethertheactivitystateispreservedwhentheactivityis,forexample,pausedorrestarted.Forthisexample,wewillevaluatehowourmainactivitybehaveswhenitispausedandresumed.Theexpectedbehavioristhatthehoursandminutesaremaintained.Performingareliabletestisnecessarytodirectlychangethetextviewsbetweenthepausingandresumingoftheactivity.Thischangeensuresthattheactivityactuallyrestoresthepreviousstate.Thecodeofthismethodisasfollows:

@UiThreadTest

publicvoidtestStateManagement(){

mHour.setText("02");

assertEquals("02",mHour.getText());

getInstrumentation().callActivityOnPause(mActivity);

mHour.setText("11");

getInstrumentation().callActivityOnResume(mActivity);

assertEquals("02",mHour.getText());

}

Noticethe@UiThreadTestannotationbeforethemethod.Methodsannotatedwith@UiThreadTestareexecutedintheUIthread.Intheprevioustestmethod,thesetTextmethodonthetextviewhastobeexecutedontheUIthread.Ifthe@UiThreadTestannotationisnotadded,youhavetousetherunOnUiThread()methodinstead.

Page 205: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

GettingtheresultsWealreadyhaveanapplicationandtwotestcasescreatedinourAndroidproject.Thestructureoftheprojectcanbeseeninthefollowingscreenshot.Runtheapplicationoncetocheckthattherearenoerrorsandinstalltheapplicationonthedevice.Inthissection,wewillberunningthetestcasesandexaminingtheresults.

InAndroidStudio,selectthepackagecontainingthetestcases.Clickonitusingtherightmousebutton,andselecttheRun‘Testsin<your_package>’option.InthebottompartofAndroidStudio,opentheRuntabtoseethetestexecution.Ontheleftpartofthistab,youcaninspectthetestexecutionstate.Fromthebuttonsontheleftside,youcanstopthetestexecutionorrerunit.Thenextscreenshotshowstheinitialstateofthetestsbeinginitialized.Ontherightpartofthetab,thecommandsandresultsarelistedintheconsole.

Whileatestmethodisbeingexecuted,itisalsorevealedontheleftpanelalongwithitsexecutionstatesuchaswhetherthetestisstillbeingevaluated,andwhetherthetestwaspassedornotpassed.Whenthetestexecutioniscompleted,alltheresultsaredisplayed.BydeselectingtheHidePassedicon(highlightedinthepreviousscreenshot),youcanseeallthetestmethods.Overtheconsole,acolorbarisalsoshowningreenorredtoindicatewhetherallthetestswerepassedorwhethertherewereanyfails.Inourexample,allthetestswerepassedasyoucanseeinthefollowingscreenshot:

Page 206: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Trytoinsertanerrorinanytestmethod,forexample,bychangingthefollowinglineofcodefromthetestStateManagement()testmethod:

assertEquals("30",mMinute.getText());

Changetheprecedinglineofcodetothefollowing:

assertEquals("40",mMinute.getText());

Runthetestsandnoticethatnowthefailisindicatedintheresults.Thefollowingscreenshotshowshowthefailisdisplayed:

Page 207: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 208: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SummaryInthischapter,youlearnedmoreaboutAndroidtesting.YounowunderstandthestructureoftheAndroidtestingAPIandweknowitsmainclassesandmethods.YoualsolearnedabouttheimportanceofinstrumentationtotestactivitiesoftheAndroidapplications.WesetupthetestingenvironmentusingAndroidStudioandfollowedthecompleteprocessoftesting.

Inthenextchapter,youwilllearnaboutsomeexternaltoolsdifferentfromAndroidStudio.ThesetoolswillhelpussecureandtestourAndroidapplications.

Page 209: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 210: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Chapter10.SupportingToolsInthischapter,youwilllearnabouttheexternaltoolsdifferentfromthoseavailableinAndroidStudiothatwillhelpustestourAndroidapplications.Thechapterwillcovertesttoolstoperformunitandfunctionaltests.Itwillalsocovertoolsthathelpussecureourapplicationindifferentways.WewillendthischapterwithanalternativetoolthatallowsyoutoemulateanAndroiddevice.

Thetopicsthataregoingtobecoveredinthischapterare:

ToolsforunittestingAndroidapplicationsToolsforfunctionaltestingAndroidapplicationsToolsforsecuringAndroidapplicationsSomeothertools

Page 211: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ToolsforunittestingAswehaveseeninChapter9,UnitandFunctionalTests,unittestingisperformedwithminimalconnectiontothesysteminfrastructureandteststhedifferentcomponentsinisolation.WewillseedifferenttoolsthatallowustoeasilyperformunittestsonAndroidapplications.Theyareasfollows:

SpoonMockitoAndroidMockFESTAndroidRobolectric

Page 212: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SpoonSpoonisnotanewformofunittesting.Instead,itmakesuseoftheexistingunittestinginstrumentationsuchasJUnittoruntestsonmultipledevices.WithSpoon,youcantestyourapplicationonmanydevicesatthesametime.Whenthetestiscompleted,youwillreceiveasummarygeneratedbySpoonwithalltheinformationregardingthetestperformedonthedevices.YoucanalsouseSpoonforfunctionaltesting.

ForadevicetobeconsideredbySpoontoruntestson,ithastobevisibletotheAndroidDebugBridge(adb)devices.Youcanevenperformthetestsondifferenttypesofdevicesatthesametime,suchassmartphones,tablets,phablets,andsoon,andindifferentversionsofAndroid.Thegreaterthediversityofthedevices,themoreusefulthesummarywillbe.Withabigsampleofdevices,youcanfindmorepotentialissuestobeaddressed.Wecanseeanexamplewitheightdevicesinthefollowingfigure:

Ifyouwanttoaccessthesummaryofthetestingperformedonasingledevice,youcandoitwiththeDeviceView.SpoonmakesaDeviceViewavailableforeachdeviceinthesamplesothatyoucanseetheresultsofadeviceindividually.ToaccesstheDeviceView,youcansimplyclickonthenameofadevice.Wecanseethisviewinthefollowingfigure:

Page 213: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Ifyouwanttoaccessthesummaryofaspecifictestperformedonallthedevicesinthesample,youcandoitthroughtheTestView.TheTestViewdisplaystheresultofasingletestoneverydevice.Incaseofanerror,itwillshowtheinformationthatwasgeneratedbytheerror.ToaccesstheTestView,youcanclickontheiconwiththeshapeofasmartphoneontheDeviceView.Wecanseeanexampleofthisviewinthefollowingscreenshot:

Page 214: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Ifyouwanttochecktheviewoftheapplicationatanypointintime,youcanusetheScreenshotfeature.Thisfeatureallowsyoutotakeascreenshotoftheinformationbeingdisplayedtotheuseratanygivenmomentduringtheexecution.ThescreenshotsareavailableinboththeDeviceViewifyouwanttoseeallthescreenshotstakeninasingledevice,andtheTestViewifyouwanttoseethescreenshotstakenofeachtestineverydevice.

Tomakeuseofthisfeature,youneedtoincludethespoon-client.jarlibraryinyourapplication.Whenyouwanttotakeascreenshot,youcancallthestaticscreenshot(Activity,String)methodoftheSpoonclass,shownasfollows:

Spoon.screenshot(activity,"login_activity");

NoteIfyouwanttoknowmoreaboutSpoonorwanttodownloadthetool,youcanfollowthislink:

http://square.github.io/spoon/

Page 215: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

MockitoMockitoisamocktestingframeworkforJavathatcanbeusedinconjunctionwithJUnitandotherunittestingframeworks.IthasbeencompatiblewithAndroidsinceVersion1.9.5.Mockitoallowstheuseofautomaticunittestingtoenhancethequalityofourcode.Mostunittestingframeworksarebasedonanexpect-run-verifypattern.Mockitoremovesthespecificationofexpectationsreducingthepatterntorun-verify.

Wealreadyknowthatunittestsareperformedoveranisolatedclass.Thismeansthattheirinteractionwithotherclassesshouldbeeliminatedwhenpossible.AsseeninChapter9,UnitandFunctionalTests,youcanachievetheseinteractionsusingmockobjectsalsoknownasstubs.Mockitoallowsyoutocreatemockobjectsusingthemock()method.

Youcanalsoinitializeamockobjectusingthe@MockannotationandtheMockitoAnnotationsclass.YoucancalltheMockitoAnnotations.initMocks()methodtoinitiatethemockobjectsthatweredefinedwiththe@Mockannotation.

Theverify()methodcanbecalledonamockobjecttoverifythatacertainmethodwascalled.Tospecifyaconditionandareturnvaluewhentheconditionismet,youcanusethewhen()methodinconjunctionwiththethenReturn()method.

Forexample,let’ssaywewanttocheckwhetherthetestmethodwascalledinthefollowingcode:

//Createthemockobject

TestClasstestClassMock=Mockito.mock(TestClass.class);

//Callamethodonthemockobject

booleanresult=testClassMock.test("helloworld");

//Testthereturnvalue

assertTrue(result);

//Checkthatthemethodtest()wascalled

Mockito.verify(testClassMock).test("helloworld");

Mockitocannotbeusedtotestfinalclasses,anonymousclasses,andprimitivetypes.

NoteIfyouwanttolearnmoreaboutMockito,visititswebsite:https://code.google.com/p/mockito/

Page 216: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

AndroidMockAndroidMockissimilartoMockito.AndroidMockisalsoaframeworktomockclassesandinterfaces.ItworkswiththeAndroidDalvikVirtualMachine.ItisbasedontheJavamockingframeworkEasyMockandusesthesamegrammarandsyntax.

InordertolearnaboutthegrammarandsyntaxofAndroidMock,wewillrepeatthesameexampleaswedidwithMockito:

publicclassMockingTestextendsTestCase{

//Createthemockobject

@UsesMocks(TestClass.class)

TestClasstestClassMock=AndroidMock.createMock(TestClass.class);

//Tellsthemockobjectthatthemethodtestwillbecalledand

//thevaluetruewillbeexpected

AndroidMock.expect(testClassMock.test("helloworld")).andReturn(true);

//Makethemockobjectreadytobetested

AndroidMock.replay(testClassMock);

//Testthereturnvalue

assertTrue(testClassMock.test("helloworld"));

//Testthatthemethodtest()wascalled

AndroidMock.verify(testClassMock);

}

Asyoucansee,themaindifferenceinAndroidMockandMockitoisthatAndroidMockfollowsthepatternexpectation-run-verify.

NoteIfyouwanttolearnmoreaboutAndroidMock,youcanvisittheprojectwebsite:https://code.google.com/p/android-mock/.

Page 217: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

FESTAndroidFESTAndroidisalibrarythatextendstheFESTfunctionalitytoAndroid.FESTisaunittestframeworkforJava.Itisbasicallyasimplerformofmakingassertions.Inthefollowingcode,weseethedifferencesbetweenJUnit,FEST,andFESTforAndroid:

//AssertionusingJUNIT

assertEquals(View.GONE,view.getVisibility());

//AssertionusingFEST

assertThat(view.getVisibility()).isEqualTo(View.GONE);

//AssertionusingFESTforAndroid

assertThat(view).isGone();

FESTforAndroidoffersassertionsthatareexecuteddirectlyonobjectsinsteadofproperties.Thismakesitpossibletochaintogetherseveralassertions,shownasfollows:

assertThat(layout).isVisible().isVertical().hasChildCount(3);

TherearemanyavailableassertionsfortypicalAndroidobjects,suchasLinearLayout,ActionBar,Fragment,andMenuItem.

NoteIfyouwanttolearnmoreaboutFEST,youcanvisittheprojectwebsiteathttps://code.google.com/p/fest/.IfyouwanttolearnmoreaboutFESTforAndroid,youcanvisittheURLathttp://square.github.io/fest-android/.

Page 218: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

RobolectricRobolectricallowsyoutorununittestsofyourAndroidapplicationonyourworkstation’sJavaVirtualMachine.Thishasonemainadvantage,thatis,speed.RunningunittestsinAndroidmeansthattheapplicationneedstobeloadedeitherontheAndroidemulatororonyourdevice.

RobolectrictakesadifferentpaththanmockframeworkssuchasMockitoandinsteadofmockingouttheAndroidSDK,RobolectricrewritestheAndroidSDKclassesandmakesitpossibletorunthemonaregularJVM.Itcan,however,beusedinconjunctionwithmockingtestingframeworkssuchasMockitoorAndroidMock.

Robolectricmakesuseofthe@RunWithannotationfromJUnit4,shownasfollows:

@RunWith(RobolectricTestRunner.class)

publicclassTest1{

//Yourtests

}

NoteIfyouwanttolearnmoreaboutRobolectric,youcanvisittheprojectwebsiteathttp://robolectric.org/.

Page 219: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 220: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ToolsforfunctionaltestingInChapter9,UnitandFunctionalTests,youlearnedhowfunctionaltestsareperformedwithfullconnectiontothesysteminfrastructure.Inthissection,wewilllookatthedifferenttoolsthatallowustoeasilyperformfunctionaltestsinAndroidapplications:

RobotiumEspressoAppiumCalabashMonkeyTalkBot-botMonkeyWireshark

Page 221: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

RobotiumRobotiumrunsontheofficialAndroidtestingframework.ItaddsthenecessaryfeaturestorunthroughanentireAndroidapplication.Ithasfullsupportforbothnativeandhybridapplications.

Now,wewillseethestepsneededtorunatestusingRobotiumonourAndroidapplication:

1. AddtheRobotiumJARtoyourBuildPath.2. CreateatestcaseusingtheJUnitTestCaseclass.3. Writethetestcasecode.4. Runthetestcase.

TestswithRobotiumareperformedusingthecom.robotium.solo.SoloclassavailableintheRobotiumlibrary.

Wewillnowseeanexampleofthewhite-boxtestingusingRobotium.Inthisexample,wehavetwoEditTextfields:onewheretheusercaninputanumericvalueValueEditTextandanotheronethatwilldisplaythevalueoftheinputmultipliedby2,ResultEditText.ThemultiplicationismadewhentheButton1buttonisclicked:

publicclassTestMainextends

ActivityInstrumentationTestCase2<MainActivity>{

//DeclarationoftheSoloobject

privateSolomSolo;

//Constructor

publicTestMain(){

super(Main.class);

}

//SetUp

@Override

protectedvoidsetUp()throwsException{

super.setUp();

//InitiatetheinstanceofSolo

mSolo=newSolo(getInstrumentation(),getActivity());

}

//White-BoxTestCode

publicvoidtestWhiteBox(){

EditTextvalueEditText=(EditText)solo.getView(R.id.ValueEditText);

EditTextresultEditText=(EditText)solo.getView(R.id.ResultEditText);

//ClearstheEditText

mSolo.clearEditText(valueEditText);

//SetsthevalueoftheEditTextto10

mSolo.enterText(valueEditText,String.valueOf(10));

//ClicksonButton1

Page 222: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

mSolo.clickOnButton("Button1");

//Asserttocheckifitworked

assertEquals(String.valueOf(20),

resultEditText.getText().toString());

}

}

NoteIfyouwanttolearnmoreaboutRobotium,youcanvisittheprojectwebsiteathttps://code.google.com/p/robotium/.IfyouwanttolearnhowtouseRobotium,werecommendtheofficialgettingstartedguide:https://code.google.com/p/robotium/wiki/Getting_Started.

Page 223: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

EspressoEspressoisanAPIthatletsyouteststateexpectations,assertions,andinteractions.TherearemanyactionsthatcanbeperformedwithEspressousingasimplesyntax.Let’sseehowtheexampleweusedforRobotiumwillbeexecutedwithEspresso:

publicvoidtestWhiteBox(){

//Typethetext"10"intheValueEditText

onView(withId(R.id.ValueEditText)).perform(typeText("10"));

//ClickthebuttonButton1

onView(withId(R.id.Button1)).perform(click());

//Checkifthevaluedisplayedis"20"

onView(withText("20").check(matches(isDisplayed()));

}

TomakeuseoftheEspressolibraryinAndroidStudio,youneedtofollowthesesteps:

1. AddtheEspressoJARasalibrarydependency.2. AddthisinstrumentationtoyourprojectAndroidManifest.xml:

<instrumentation

android:name="com.google.android.apps.common.testing.testrunner.GoogleI

nstrumentationTestRunner"android:targetPackage="YOUR_PACKAGE"/>

3. ConfigureteststorunwithGoogleInstrumentationTestRunner.

NoteIfyouwanttolearnmoreaboutEspresso,youcanvisittheprojectwebsiteathttps://code.google.com/p/android-test-kit/wiki/Espresso.Ifyouhave15minutestospare,werecommendtheirGoogleTestAutomationConference2013presentationathttps://www.youtube.com/watch?v=T7ugmCuNxDU.

Page 224: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

AppiumAppiumisanopensourceframeworkthatallowsautomatedtesting.AppiumworkswithbothnativeandhybridAndroidapplications.ItevenworkswithiOS.AppiumisagoodsolutionifyouneedtotestinbothAndroidandiOS.

NoteTodownloadorjustlearnmoreaboutAppium,youcanvisittheirwebsiteathttp://appium.io/.IfyouwanttoseeexamplesforAppium,visittheirGitHubathttps://github.com/appium/appium/tree/master/sample-code/examples.

Page 225: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

CalabashJustlikeAppium,Calabashisalsoamultiplatformframeworkthatperformsautomatedtests.ItworkswithAndroidnativeapplications,hybridapplications,andiOSnativeapplications.Calabashallowsyoutotakescreenshotsofthecurrentviewinadeterminedinstant.OneofthethingsthatseparateCalabashfromtheothertestingframeworksisthatitsupportsCucumber.Cucumberallowspeoplewithlessexpertiseinthismattertoeasilydefinethebehavioroftheapplicationusingnaturallanguage,forexample:

WhenItouchthe"addition"button

ThenIshouldsee"20"

TheCalabashtoolisbasedonActivityInstrumentationTestCase2fromtheAndroidSDK.

NoteIfyouwanttoknowmoreaboutCalabash,youcanvisittheprojectwebsite:http://calaba.sh/.TolearnmoreabouttheCucumberproject,visittheirwebsite:http://cukes.info/.

Page 226: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

MonkeyTalkMonkeyTalkisyetanothermultiplatformautomatedtestframework.MonkeyTalksupportsmorefeaturesthanAppiumandCalabash.However,theversionwitheveryfeatureavailableisasubscription-licensedproductthatiscurrentlyofferedinafreebetaversionbutwillbechargedwhenthebetaisover.

NoteIfyouwanttodownloadMonkeyTalkorjustlearnmoreaboutit,youcanvisittheprojectwebsiteathttp://www.cloudmonkeymobile.com/monkeytalk.ToseeanexampleusingtheMonkeyTalkframeworkwithanAndroidapplication,watchthefollowingYouTubevideo:https://www.youtube.com/watch?v=pjDGctTnThQ.

Page 227: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Bot-botBot-botisanAndroidautomationtestingtoolwithtwointerestingfeatures:recordandreplay.Youdonotneedtoaddanykindoflibraryordependencytoyourproject,sincetheonlythingbot-botneedsisanAPKoftheapplicationyouwanttotest.Therecordfeatureallowsyoutostorethesequenceofeventsthatweretriggered.Itworksbothonasimulatorandarealdevice.TherecordedtestcasescanbeexportedintheCSVformatandreplayedusingthebot-bottool.

Bot-botconsistsofthreeelements:

Thebot-botserver:ThisserverisusedtostoreandmodifytheactionstakenontheAndroidapplication.ItincludesasimpleHTMLinterfacethatallowsyoutoviewrecordedsessions,viewrecordedentriesofasession,modifyorcreateassertions,exportrecordedsessionsinCSV,anddeleterecordedsessions.Thebot-botrecorder:ThisrecordertrackstheuseractionsontheAndroidapplicationthatarebeingtested,andsendsthesetaskstothebot-botserver.ItsupportsrecordingofactionsonTextBoxes,Adapters,andSpinners.Italsorecordsclicksonelementsandviews.ItdoesnotsupportactionsonWebViews.Thebot-botrunner:ThisrunnertakestheexportedsessionsintheCSVformatandinterpretsthem.Thebot-botrunnerthenexecutestheactionsontheAndroidapplicationandgeneratesanHTMLreportthatshowstheexecutionofthetestcasesdefined.

ThefollowingscreenshotshowsanexampleofageneratedHTMLreportbythebot-botrunner:

Bot-botisperfectlyintegratedwithRobotium.

NoteIfyouwanttodownloadthebot-botapplication,youcanvisittheirwebsite:http://imaginea.github.io/bot-bot/.Tolearnhowtousethebot-bottool,werecommendtheofficialGetStartedguide:http://imaginea.github.io/bot-bot/pages/get_started.html.

Page 228: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

MonkeyMonkeyisacommand-linetoolthatrunsonyourAndroidemulatorordevice.Itgeneratesrandomusereventsandsystem-leveleventstostresstestyourapplication.Althoughtheinteractionsarerandom,theyarebasedonaseedingsystemandthereforeyoucanrepeatthesamesequenceofactionsusingthesameseed.Thisisimportantsinceotherwise,youwouldnotbeabletorepeatthesequencethatproducedanerrortocheckwhetheritwasfixed.

TherearefourmaincategoriesofoptionsinMonkey:

Basicconfigurationoptions:AnexampleofthiscanbethehelporverbositylevelOperationalconstraints:AnexampleofthiscanbethepackagesinwhichthestresstestwillbeperformedEventtypes:Anexampleofthiscanbethenumberofevents,randomseed,anddelaybetweeneventsDebuggingoptions:Anexampleofthiscanbekillingtheprocessafteranerrororignoringthesecurityexceptions

TolaunchtheMonkey,youneedtouseacommandlineonyourdevelopmentmachineshownasfollows:

adbshellmonkey–pcom.packt.package–v100

The–pargumentstatesthepackagewheretheMonkeywillsendrandomevents.The–vparameterstatesthenumberofrandomeventsthatwillbesent.

NoteTherearemanyotherparametersforMonkey.Ifyouwanttolearnabouttheseparameters,youcanvisittheofficialAndroidguide:http://developer.android.com/tools/help/monkey.html.

Page 229: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

WiresharkWireshark,formerlyknownasEthereal,isaprotocolanalyzerusedtoperformanalysisandsolveproblemsrelatedtonetworkconnectivity.Itsfunctionalityissimilartothetooltcpdump,butWiresharkprovidesamoreintuitiveGUI.

YoucanuseWiresharkincombinationwithyourAndroidemulatortocheckwhatinformationisbeingtransferredtoandfromyourAndroidapplication.Themainissuewiththistoolisthatyouneedtoknowwhatpackagestoexpect,sinceotherwisethetaskoffilteringcanbecomereallydifficult.Thebestadvicewecangiveistoclosethebrowserandotherprogramsinyourcomputerthatmaygeneratenetworktraffictokeepittoaminimum.

Inthisbook,wealreadydiscussedWiresharkinChapter6,SecuringCommunications.OneofthetopicswediscussedwasthatwecanuseWiresharktotestwhetherthedatawearesendingisbeingencryptedproperlyornot.OtheralternativestoWiresharkareFiddlerforWindowsandCharlesproxyforOSX.AscreenshotofWiresharkisshowninthefollowingfigure:

NoteIfyouwanttodownloadorlearnmoreaboutWireshark,visittheirwebsite:http://www.wireshark.org/.

Page 230: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 231: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

OthertoolsInthislastsection,wewillseeatoolthatisnotdirectlyrelatedtoapplicationtestingorsecuritytesting.However,itcansignificantlyimproveourtestingexperience.

Page 232: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

GenymotionGenymotionisanalternativeandunofficialAndroidemulator.ItisbasicallyavirtualemulatorthatcreatesavirtualimageofAndroidandisoftenconsideredmuchfasterthantheofficialAndroidemulator.ItisavailableforWindows,Linux,andMacOS.IfyouareusingWindowsorLinux,youonlyneedtoinstalltheGenymotiondistributionpackage.However,ifyouareusingMacOS,youneedtodownloadandinstallVirtualBoxmanually.Thefollowingisascreenshotcapturedfromthevirtualdevicemanagerthatlistsallthevirtualdevicesavailable:

NoteIfyouwanttogetstartedwithusingGenymotion,youcanvisitourblog:http://belencruz.com/2014/01/first-look-at-genymotion-android-emulator/.TodownloadandlearnmoreaboutGenymotion,visittheprojectwebsite:http://www.genymotion.com/.IfyouareusingMacOSandneedtodownloadVirtualBox,followthislink:https://www.virtualbox.org/.

Page 233: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 234: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SummaryInthischapter,youlearnedabouttheexternaltoolsthathelpusperformtestsonourAndroidapplications.Thechaptercoveredseveralautomatedunittestingtoolsandseveralautomatedfunctionaltestingtools.YoualsolearnedhowtostresstestourapplicationsusingMonkeyandwhattoolswewillneedifwewanttocheckthenetworkconnectivityofourapplication.AnalternativeAndroidemulatorthatisinmostcasesfasterthantheofficialonewasreviewedtoo.

Inthenextchapter,whichisthelastchapter,youwilllearnaboutsometipsthatareveryusefulfordevelopers.Youwillalsolearnhowtogethelpincaseyouneedit.

Page 235: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 236: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Chapter11.FurtherConsiderationsThischapterprovidessomefurtherconsiderationsthatareusefulfordevelopers.Wewillreviewwhatarethemostimportantpartsofourapplicationthatweneedtotest.Thischapteralsocontainsinformationabouthowtogethelpformoreadvancedtopics.

Thetopicsthatwillbecoveredinthischapterare:

WhattotestDeveloperoptionsGettinghelp

Page 237: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

WhattotestInthepreviouschapters,youlearnedabouttheAndroidtestingAPIworkingwithAndroidStudio.ApartfromknowingaboutactivityandUItesting,consideringwhatpartsofyourapplicationshouldbeevaluatedisalsoimportant.

Page 238: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

NetworkaccessIfyourapplicationdependsonthenetworkaccess,youshouldexaminethebehaviorofyourapplicationwhendifferentnetworkstatesaregiven.Considerthefollowingsuggestions:

Ifyourapplicationcompletelydependsonthenetworkwhenitislaunchedandthereisnonetworkaccess,itshouldatleastshowadefaulthomescreen.Yourapplicationshouldnotshowablankscreenwithanyinformationonit.Lettheuserknowthathe/sheshouldreviewthedeviceconnectivity.ThenetworkstatecanbecheckedusingtheConnectivityManagerclassinthefollowingcode:

ConnectivityManagerconnManager=(ConnectivityManager)

getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfonetInfo=connManager.getActiveNetworkInfo();

if(netInfo!=null&&netInfo.isConnected()){

//Connect

}else{

//displaydefaultscreen

}

Whenthereareproblemsaccessingthenetworkthataffectthenormalbehaviorofyourapplication,lettheuserknowthisbydisplayingamessage.Whenperforminglongnetworkoperations,theusershouldalsobeabletouseyourapplication.Checkthatyourapplicationcontinuesworkingproperlyevenwhileperforminglongnetworkoperations.Yourapplication’sdatashouldmaintainitsconsistency.Ifyourapplicationsendsorreceivesanykindofinformationtoorfromyourserver,thisinformationshouldbecorrectlysynchronized.Checkthatyourapplicationandservercanrecoverfromanetworkfailureandmaintaintheconsistencyofyourapplication’sdata.Tomitigatenetworkfailures,yourapplicationcancachesomeoftheinformation.Checkthemanagementofthecachedinformationanditsusagewhenthereisnonetworkaccess.Agoodpolicyistochangethebehaviorofyourapplicationdependingonthetypeofnetworkaccess,forexample,itshouldbeabletodetectwhetherthedeviceisconnectedtoaWi-Fior3Gnetworkandworkaccordingly.Youshouldtestwhetheryourapplicationfollowsthedefinedpolicyandwhetheritisabletoreacttochangesintheconnectiontype.Theconnectiontypecanbecheckedusingthefollowingcode:

booleanwifiConnected=netInfo.getType()==

ConnectivityManager.TYPE_WIFI;

booleanmobileConnected=netInfo.getType()==

ConnectivityManager.TYPE_MOBILE;

Ifthereisanetworkfailure,yourapplicationshouldretryafterawhile.Youshouldcheckwhichbehaviorisappropriateforyourapplicationandwhetheritiscapableofrecoveringfromfailures.

Page 239: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

MediaavailabilityIfyourapplicationdependsonexternalmedia,yourcodeshouldchecktheavailabilityofthatmedia.Whiledesigningyourtests,youshouldevaluatewhetheryourapplicationbehavescorrectlyifthemediaisnotavailable.

Forexample,ifyourapplicationworkswithanexternalstorage,youcancheckitsstatebyusingtheEnvironment.getExternalStorageStatemethod,asitwasshowninChapter5,PreservingDataPrivacy.Totesttheexternalstorageavailability,youcanconfiguretheAVDtorunontheemulatorfromAndroidStudio,asitisshowninthefollowingscreenshot:

Page 240: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ChangeinorientationIfadevicesupportsmultipleorientations,yourapplicationshouldbepreparedforthesame.Youhavetodecidewhetheryourapplicationwillblocktheorientationchangesornot.Ifyourapplicationsupportsorientationchanges,considerthefollowingsuggestions:

Whenthereisanorientationchange,thecurrentactivityisdestroyedandrestarted.Checkthattheactivitystateismaintained.Forexample,ifyouractivitycontainsaninputfieldthattheusercanedit,itscontenthastobepreservedwhenthedeviceorientationchanges.YourUIshouldalsoadapttothedevice’scurrentorientation.ThepositionanddistributionofyourUIelementsaredifferentonaportraitorientationthanonalandscapeone.YoushouldcheckthatthedesignofyourUIisperfectlydisplayedinboththeorientations.

YoucanchangetheemulatororientationbypressingCtrl+F11inWindowsorLinux,orFn+Ctrl+F11inMacOS.Tochecktheorientationchanges,youcanoverridetheonConfigurationChangedmethodofyouractivities,shownasfollows:

@Override

publicvoidonConfigurationChanged(ConfigurationnewConfig){

super.onConfigurationChanged(newConfig);

if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){

}elseif(newConfig.orientation==Configuration.ORIENTATION_PORTRAIT){

}

}

Page 241: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

ServiceandcontentprovidertestingInAndroid,wecantesttheUI,activities,services,andcontentproviders.InChapter9,UnitandFunctionalTests,activitytestingwasexplained.Butyoushouldnotforgetaboutservicestestingandcontentproviderstesting.TheclassesintheAndroidtestingAPIusedtoevaluateservicesandcontentprovidersarelistedinthefollowingfigure:

TheAndroidTestCaseclassanditssubclassesbelongtotheandroid.testpackage.ItrepresentsatestcasetobeusedintheAndroidenvironment.Sincethisclassisgeneric,youshoulduseoneofitssubclasses.TheProviderTestCase2classisusedtotestcontentproviders.TheServiceTestCaseclassisusedtotestservices.

Page 242: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 243: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

DeveloperoptionsTheAndroidsystemprovidesasetofon-devicedeveloperoptionsthatwillhelpyoutestyourapplication.TheseoptionsareavailableintheSettingsmenuofanyAndroiddevice.OnAndroid4.2andhigher,thedeveloperoptionsarehidden.ClickontheAboutphoneoptionintheSettingsmenuandclickontheBuildnumberseventimestomakethemavailable.ThefollowingscreenshotshowstheDeveloperoptionsinAndroid’sSettingsmenu:

TheDeveloperoptionsareorganizedintosevencategories,describedasfollows:

General:Thisoptionisnotpresentinanycategory.Forexample,youcangetabugreportbyselectingtheTakebugreportoption.Debugging:Thiscategoryincludesusefultoolstodebugyourapplication.Forexample,whenyouwanttotestyourapplicationonarealdevice,youshouldchecktheUSBdebuggingoptioncontainedinthiscategory.Youcanalsoselectadebugapp(Selectdebugapp)orallowmocklocations(Allowmocklocations).Input:Thiscategorycontainstwotools.TheseareShowtouchestoprovideavisualfeedbackfortouchesonthescreen,andPointerlocationtooverlaythetouchdataonthescreen.Drawing:Thiscategoryincludesoptionstochangethegraphicalbehavioroftheapplicationandthesystemitself,suchasShowsurfaceupdates,Showlayoutbounds,ForceRTLlayoutdirection,andSimulatesecondarydisplays.Youmaywanttodisableanimationsthattakeplacewhenanapplicationisopened.Todoso,youcansettoAnimationoffthefollowingoptions:Windowanimationscale,Transitionanimationscale,andAnimatordurationscale.Hardwareacceleratedrendering:Inthissection,youcanchangethebehavioroftheGraphicsProcessingUnit(GPU).TheoptionsavailableareForceGPUrendering,ShowGPUviewupdates,Showhardwarelayersupdates,DebugGPUoverdraw,Debugnon-rectangularclipoperation,Force4xMSAA,andDisableHWoverlays.Monitoring:Thiscategorycontainsoptionsthatallowyoutotrackpossible

Page 244: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

problemsormalfunctions.TheoptionsavailableareStrictmodeenabled,ShowCPUusage,ProfileGPUrendering,andEnableOpenGLtraces.Apps:Thiscategoryincludesoptionstomanagethebehaviorofapplicationswhentheyarerunninginthebackground.ActivatingDon’tkeepactivitieswilldestroyeveryactivitywhentheuserleavesit.Thebackgroundprocesslimitallowsyoutocontrolthenumberofprocessesthatcanbeexecutedinthebackground.IfyouactivatetheoptionShowallANRs,applicationswilldisplayadialogwhentheydon’trespond.

Page 245: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 246: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

GettinghelpIfyouwanttoaccesstheAndroidStudiodocumentation,youcandoitthroughtheIntelliJIDEAwebhelp.YoucangotoHelp|OnlineDocumentation,oraccessthewebpagehttp://www.jetbrains.com/idea/documentation/.YoucanalsogotoHelp|HelpTopicstodirectlyopenthedocumentationcontentstree,orvisitthewebpagehttp://www.jetbrains.com/idea/webhelp/intellij-idea.html.

Android’sofficialdocumentationisprovidedbyGoogleandisavailableathttp://developer.android.com/.TheAndroiddocumentationincludeseverykindofguidetolearnhowtoprogramAndroidapplications.Italsoincludesdesignguidelinesandeventipsondistributingandpromotingyourapplication.

Someoftheimportantreferencesofallthepreviouschaptersarelistedasfollows:

Chapter1,IntroductiontoSoftwareSecurity:

Glossaryoftermsathttp://www.sans.org/security-resources/glossary-of-terms/

Chapter2,SecurityinAndroidApplications:

Contentprovidersathttp://developer.android.com/guide/topics/providers/content-providers.htmlIntentfiltersathttp://developer.android.com/guide/components/intents-filters.html

Chapter3,MonitoringYourApplication:

DDMSathttp://developer.android.com/tools/debugging/ddms.html

Chapter4,MitigatingVulnerabilities:

ThePatternclassathttp://developer.android.com/reference/java/util/regex/Pattern.htmlStoringdataathttp://developer.android.com/training/articles/security-tips.html#StoringData

Chapter5,PreservingDataPrivacy:

Cipherathttp://developer.android.com/reference/javax/crypto/Cipher.htmlStorageoptionsathttp://developer.android.com/guide/topics/data/data-storage.html#filesInternal

Chapter6,SecuringCommunications:

Usingcryptographyathttp://developer.android.com/training/articles/security-tips.html#CryptoSecuritywithHTTPSandSSLathttp://developer.android.com/training/articles/security-ssl.html

Chapter7,AuthenticationMethods:

AccountManagerat

Page 247: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

http://developer.android.com/reference/android/accounts/AccountManager.html

Chapter8,TestingYourApplication:

UItestingathttp://developer.android.com/tools/testing/testing_ui.htmluiautomatorathttp://developer.android.com/tools/help/uiautomator/index.html

Chapter9,UnitandFunctionalTests:

Creatingunittestsathttp://developer.android.com/training/activity-testing/activity-unit-testing.htmlCreatingfunctionaltestsathttp://developer.android.com/training/activity-testing/activity-functional-testing.htmlViewAssertsathttp://developer.android.com/reference/android/test/ViewAsserts.htmlMoreAssertsathttp://developer.android.com/reference/android/test/MoreAsserts.html

Chapter10,SupportingTools:

Spoonathttp://square.github.io/spoon/Mockitoathttps://code.google.com/p/mockito/AndroidMockathttps://code.google.com/p/android-mock/FESTAndroidathttp://square.github.io/fest-android/Robolectricathttp://robolectric.org/Robotiumathttps://code.google.com/p/robotium/Espressoathttps://code.google.com/p/android-test-kit/wiki/EspressoAppiumathttp://appium.io/Calabashathttp://calaba.sh/MonkeyTalkathttp://www.cloudmonkeymobile.com/monkeytalkBot-botathttp://imaginea.github.io/bot-bot/Monkeyathttp://developer.android.com/tools/help/monkey.htmlWiresharkathttp://www.wireshark.org/Genymotionathttp://www.genymotion.com/

Page 248: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers
Page 249: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SummaryInthischapter,youlearnedaboutwhichpartsofourapplicationaremoreimportanttoevaluateandtest.WereviewedthedeveloperoptionsavailableinAndroidandhowtoaccessthem.Wealsolearnedhowtogetadditionalhelpusingtheofficialdocumentationandothersources.

Page 250: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

IndexA

acceptancetests/Testingthebasicsaccesscontrol,softwaresecurity/SoftwaresecuritytermsAccountManagerclass

about/AccountManagerusing/AccountManager

activityabout/Intents

Activity.runOnUiThread()methodabout/UItestingandTouchUtils

ActivityInstrumentationTestCase2classabout/Thetestcaseclasses

activitylifecyclemethods/Instrumentationactivitytest

creating/Creatinganactivitytestunittest,creating/Creatingaunittestfunctionaltest,creating/Creatingafunctionaltestexecuting/Gettingtheresults

ActivityTestCaseclassabout/Thetestcaseclasses

ActivityUnitTestCaseclassabout/Thetestcaseclasses

addMonitormethod/InstrumentationAllocationTrackertab

displaying/AllocationTrackerAllpairstestingtechnique/TestingthebasicsAndroid

about/ThemobileenvironmentAndroidapplication

testing/TestinginAndroidAndroidapplicationpackage(APK)/PermissionsAndroidApplicationSandbox/AnoverviewofAndroidsecurityAndroidDebugBridge(adb)/SpoonAndroidinstrumentation

about/InstrumentationAndroidMock

about/AndroidMockURL/AndroidMock

AndroidSDKused,fortestingAndroidapplication/TestinginAndroid

Androidsecurity

Page 251: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

overview/AnoverviewofAndroidsecurityfeatures/AnoverviewofAndroidsecurity

AndroidStudioabout/AndroidStudioURL,fordocumentation/Gettinghelphelp,obtaining/Gettinghelp

AndroidVirtualDevice(AVD)about/Theuiautomatorviewertool

APIabout/Permissions

appabout/Themobileenvironment

Appiumabout/AppiumURL,fordownloading/Appium,Calabash

applicationlayerabout/HTTPS

applicationsandboxing/AnoverviewofAndroidsecurityAssertclass

about/TheAssertclassandmethodViewAssertsclass/TheViewAssertsclassMoreAssertsclass/TheMoreAssertsclass

assertEqualsmethod/TheAssertclassandmethodassertFalsemethod/TheAssertclassandmethodassertmethod

about/TheAssertclassandmethodassertEqualsmethod/TheAssertclassandmethodassertTruemethod/TheAssertclassandmethodassertFalsemethod/TheAssertclassandmethodassertNullmethod/TheAssertclassandmethodassertNotNullmethod/TheAssertclassandmethodassertSamemethod/TheAssertclassandmethodassertNotSamemethod/TheAssertclassandmethodfailmethod/TheAssertclassandmethod

assertNotNullmethod/TheAssertclassandmethodassertNotSamemethod/TheAssertclassandmethodassertNullmethod/TheAssertclassandmethodassertSamemethod/TheAssertclassandmethodassertTruemethod/TheAssertclassandmethodasymmetriccryptography,softwaresecurity/Softwaresecuritytermsasymmetricencryption

about/Encryptionauthentication,softwaresecurity/Softwaresecuritytermsauthenticationfactors

Page 252: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

knowledgefactor/Theknowledgefactorpossessionfactor/Thepossessionfactorinherencefactor/Theinherencefactor

availability,softwaresecurity/Softwaresecurityterms

Page 253: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Bbasispathtesting/Testingthebasicsbiometricauthentication

about/Theinherencefactorbiometricidentifiers

physiologicalcharacteristics/Theinherencefactorbehavioralcharacteristics/Theinherencefactor

black-boxtestingabout/TestingtheUI

black-boxtestsabout/Testingthebasics

black-boxtests,techniquesequivalencepartitioning/Testingthebasicsboundaryvalueanalysis/Testingthebasicsstatetransitiontesting/Testingthebasicsallpairstesting/Testingthebasicssyntaxtesting/Testingthebasics

bot-botabout/Bot-botserver/Bot-botrecorder/Bot-botrunner/Bot-botURL,fordownloading/Bot-bot

bot-botrecorderabout/Bot-bot

bot-botrunnerabout/Bot-bot

bot-botserverabout/Bot-bot

boundaryvalueanalysistechnique/Testingthebasicsbroadcastmessages,types

normal/Intentsordered/Intentssticky/Intents

broadcastreceiversabout/Intents

bruteforce,softwaresecurity/Softwaresecurityterms

Page 254: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

CCalabash

about/Calabashcategories,developeroptions

General/DeveloperoptionsDebugging/DeveloperoptionsInput/DeveloperoptionsDrawing/DeveloperoptionsHardwareacceleratedrendering/DeveloperoptionsMonitoring/DeveloperoptionsApps/Developeroptions

Cause-effectgraphingtechnique/Testingthebasicscertificate

about/Serverandclientcertificatescreating/Serverandclientcertificatesusing/Serverandclientcertificates

certificate.crtfile/KeytoolintheterminalCertificateAuthority(CA)/CodeexamplesusingHTTPScertificates

about/AnoverviewofAndroidsecurityCipher,softwaresecurity/Softwaresecuritytermscodeinjection,softwaresecurity/Softwaresecuritytermsconfidentiality,softwaresecurity/SoftwaresecuritytermsConsole

about/DebuggingandDDMScontentprovider

testing/Serviceandcontentprovidertestingcontentproviders

about/ContentprovidersURL,forofficialdocumentation/Contentproviderssecuring/Securingthecontentproviderssecuring,precautions/Securingthecontentproviders

controlflowtesting/Testingthebasicscrack,softwaresecurity/Softwaresecuritytermscryptographickeys

about/Thepossessionfactor

Page 255: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

D.dbfile

about/Thedatabasestoragedangerouspermissionlevel

about/Permissionsdata

storing,encryptionused/Usingencryptiontostoredatadatabasestorage

about/ThedatabasestorageDataEncryptionStandard(DES)

about/SSLandTLSdataflowtesting/Testingthebasicsdataprivacy

about/DataprivacyDDMS

about/DebuggingandDDMSdebugger

about/DebuggingandDDMSdebugging

about/DebuggingandDDMSdecryption,softwaresecurity/SoftwaresecuritytermsDenial-of-service(DoS)/Softwaresecuritytermsdeveloperoptions

about/Developeroptionscategories/Developeroptions

DeviceViewabout/Spoon

Dictionaryattack/SoftwaresecuritytermsDistributeddenial-of-service(DDoS)/SoftwaresecuritytermsdoFinalmethod

about/Encryption

Page 256: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Eelectroniccommerce(e-commerce)/SoftwaresecuritytermsEmulatorControltab

about/EmulatorControlTelephonyStatus/EmulatorControlTelephonyActions/EmulatorControlLocationControls/EmulatorControl

encryption/Softwaresecuritytermsabout/Encryptionsymmetricencryption/Encryptionasymmetricencryption/Encryptionkey,generating/Generatingakeyused,forstoringdata/Usingencryptiontostoredata

encryptionmethodsusing/Theencryptionmethods

Equivalencepartitioningtechnique/TestingthebasicsEspresso

about/Espressoreferencelink/Espresso

exclusivetime/Methodprofilingexpect-run-verifypattern/Mockitoexternalstorage

about/Filesintheexternalstoragepublicfiles/Filesintheexternalstorageprivatefiles/Filesintheexternalstorage

Page 257: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Ffabrication,threat/Threatfailmethod/TheAssertclassandmethodfeatures,Androidsecurity

application-definedpermissions/AnoverviewofAndroidsecurityinterprocesscommunication/AnoverviewofAndroidsecuritysupportforsecurenetworking/AnoverviewofAndroidsecuritysupportforcryptography/AnoverviewofAndroidsecurityencryptedfilesystem/AnoverviewofAndroidsecurityapplicationsigning/AnoverviewofAndroidsecurity

FESTreferencelink/FESTAndroid

FESTAndroidabout/FESTAndroidURL/FESTAndroid

FileExplorertababout/FileExplorer

FTPabout/HTTPS

functionaltestcreating/Creatingafunctionaltestsettingup/ThefunctionaltestsetupUItestmethod,implementing/TheUItestactivityIntenttestmethod,implementing/TheactivityIntentteststatemanagementtestmethod,implementing/Thestatemanagementtest

functionaltestingabout/Testingactivitiestools,using/Toolsforfunctionaltesting

Page 258: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Ggarbagecollector(GC)

about/HeapGenymotion

about/GenymotionURL/Genymotion

getAccountsByNamemethodabout/AccountManager

getActivity()methodabout/Instrumentation,Theunittestsetup

getContentResolver().query()methodabout/Contentproviders

getContentResolver().query()method,parameterscontentURI/Contentprovidersprojection/Contentprovidersselection/Contentprovidersselectionarguments/Contentproviderssortorder/Contentproviders

getInstrumentation()methodabout/Instrumentation

getPreferences()methodabout/Sharedpreferences

getSharedPreferences()methodabout/Sharedpreferences

getTargetContextmethod/InstrumentationgetUiDevice()method

about/TheUiDeviceclassGraphicsProcessingUnit(GPU)/Developeroptions

Page 259: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Hhashfunction/SoftwaresecuritytermsHeaptab

displaying/Heaphelp,AndroidStudio

obtaining/GettinghelpHijackattack/SoftwaresecuritytermsHTTP

versus,HTTPS/HTTPSHTTPS

about/HTTPSversus,HTTP/HTTPSSSL/SSLandTLSTLS/SSLandTLScertificate,creating/ServerandclientcertificatesKeytool/KeytoolintheterminalAndroidStudio/AndroidStudioexamples/CodeexamplesusingHTTPS

HypertextTransferProtocolSecure(HTTPS)/Softwaresecurityterms

Page 260: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Iinclusivetime/Methodprofilinginherencefactor

about/Theknowledgefactor,Theinherencefactorinitmethod/Encryptioninputvalidation

about/InputvalidationSQLinjection/SQLinjection

instrumentationabout/Instrumentation

InstrumentationclassURL,fordocumentation/InstrumentationaddMonitormethod/Instrumentationactivitylifecyclemethods/InstrumentationgetTargetContextmethod/InstrumentationstartActivitySyncmethod/InstrumentationwaitForIdleSyncmethod/Instrumentation

InstrumentationTestCaseclassabout/Thetestcaseclasses

integrationtests/Testingthebasicsintegrity,softwaresecurity/Softwaresecuritytermsintents

about/IntentsURL,forofficialdocumentation/Intents

Intentssecuring/SecuringIntentsvulnerabilities/SecuringIntents

Intentspoofingabout/SecuringIntents

interapplicationcommunicationabout/Interapplicationcommunication,Interapplicationcommunicationintents/Intentscontentproviders/ContentprovidersIntents,securing/SecuringIntentscontentproviders,securing/Securingthecontentproviders

interception,threat/Threatinternalstorage

about/FilesintheinternalstorageInternationalMobileStationEquipmentIdentity(IMEI)

about/DataprivacyInternetAssignedNumbersAuthority(IANA)

about/Inputvalidationinternetlayer

Page 261: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

about/HTTPSinterruption,threat/Threat

Page 262: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

JJavaDevelopmentKit(JDK)

about/ServerandclientcertificatesJUnit

about/TestinginAndroidJVM

about/TestinginAndroidAndroidapplication,testingon/TestinginAndroid

Page 263: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Kkey

generating,forencryption/GeneratingakeyKeyGeneratorclass/GeneratingakeyKeytool

about/Serverandclientcertificates,Keytoolintheterminalkeytoolcommand

-genkeyparameter/Keytoolintheterminal-keyalgparameter/Keytoolintheterminal-aliasparameter/Keytoolintheterminal-keystoreparameter/Keytoolintheterminal-storepassparameter/Keytoolintheterminal-validityparameter/Keytoolintheterminal-keysizeparameter/Keytoolintheterminal

knowledgefactorusername/password/Theknowledgefactorpattern/TheknowledgefactorPIN/Theknowledgefactor

Page 264: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Llinklayer

about/HTTPSLogCat

about/DebuggingandDDMSloginimplementations

about/Loginimplementations

Page 265: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

MMan-in-the-middleattack/SoftwaresecuritytermsMD5,softwaresecurity/SoftwaresecuritytermsMediaAccessControl(MAC)/HTTPSmediaavailability

testing/Mediaavailabilitymethodprofilingtool

about/Methodprofilingmobileenvironment

about/Themobileenvironmentmock()method/MockitoMockito

about/MockitoURL/Mockito

mockobjectclassesabout/ThemockobjectclassesMockApplicationclass/ThemockobjectclassesMockContextclass/ThemockobjectclassesMockContentProviderclass/ThemockobjectclassesMockCursorclass/ThemockobjectclassesMockDialogInterfaceclass/ThemockobjectclassesMockPackageManagerclass/ThemockobjectclassesMockResourcesclass/ThemockobjectclassesMockContentResolverclass/Themockobjectclasses

modeflag,internalstorageMODE_PRIVATE/FilesintheinternalstorageMODE_APPEND/FilesintheinternalstorageMODE_WORLD_READABLE/FilesintheinternalstorageMODE_WORLD_WRITEABLE/Filesintheinternalstorage

modification,threat/ThreatMonkey

about/Monkeybasicconfigurationoptions/Monkeyoperationalconstraints/Monkeyeventtypes/Monkeydebuggingoptions/MonkeyURL,forparameters/Monkey

MonkeyTalkabout/MonkeyTalkURL,fordownloading/MonkeyTalk

MoreAssertsclass/TheAssertclassandmethodabout/TheMoreAssertsclassassertContainsRegex()method/TheMoreAssertsclass

Page 266: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

assertContentsInAnyOrder()method/TheMoreAssertsclassassertContentsInOrder()method/TheMoreAssertsclassassertEmpty()method/TheMoreAssertsclassassertEquals()method/TheMoreAssertsclassassertMatchesRegex()method/TheMoreAssertsclassURL/TheMoreAssertsclass

multifactorauthenticationabout/Multifactorauthentication

MyPrefsFilefile/SharedpreferencesMyReadablePrefsFilefile/SharedpreferencesMyWriteablePrefsFilefile/Sharedpreferencesmy_keystore.jksfile/Keytoolintheterminal

Page 267: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Nnetworkaccess

testing/NetworkaccessNetworkStatisticstab

displaying/NetworkStatisticsnormalbroadcast

about/Intentsnormalpermissionlevel

about/Permissions

Page 268: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

OonCreatemethod/InstrumentationopenFileOutput()method

about/Filesintheinternalstorageopensourcesoftware(OSS)

about/HTTPSoperatingmode,sharedpreferences

MODE_PRIVATE/SharedpreferencesMODE_WORLD_READABLE/Sharedpreferences

operatingsystem(OS)about/Themobileenvironment

orderedbroadcastabout/Intents

orientationchangestesting/Changeinorientation

OSImodelabout/HTTPSversus,TCP/IPmodel/HTTPS

Page 269: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

P-pparameter/Monkeypassword,softwaresecurity/Softwaresecuritytermspattern

about/TheknowledgefactorPatternclass

DOMAIN_NAMEpattern/InputvalidationEMAIL_ADDRESSpattern/InputvalidationIP_ADDRESSpattern/InputvalidationPHONEpattern/InputvalidationTOP_LEVEL_DOMAINpattern/InputvalidationWEB_URLpattern/Inputvalidation

PBKDF2algorithm/Usingencryptiontostoredatapermissionlevel

normal/Permissionsdangerous/Permissionssignature/PermissionssignatureOrSystem/Permissions

permissionsabout/Permissions,Permissions

phishing,softwaresecurity/Softwaresecuritytermsphysicallayer

about/HTTPSPIN

about/Theknowledgefactorpossessionfactor

about/Thepossessionfactorprivatefiles

about/Filesintheexternalstoragepublicfiles

about/Filesintheexternalstorage

Page 270: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

Rregularexpressions

URL,fordocumentation/InputvalidationresourceIdmethod/TheUItestprojectrisk,softwaresecurity

about/Softwaresecurityterms,RiskRobolectric

about/RobolectricURL/Robolectric

Robotiumabout/Robotiumreferencelink/Robotium

Page 271: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

SScreenshotfeature

about/SpoonSecretKeySpecclass/Generatingakeysecurecode-design,principles

securedefaults/Securecode-designprinciplesleastprivileges/Securecode-designprinciplesclarity/Securecode-designprinciplessmallsurfacearea/Securecode-designprinciplesstrongdefense/Securecode-designprinciplesfailingsecurely/Securecode-designprinciplesthird-partycompanies,nottrusting/Securecode-designprinciplessimplicity/Securecode-designprinciplesAddressvulnerabilities/Securecode-designprinciples

SecureRandomclass/Generatingakeysecuritytesting

about/Testingthebasicswhite-boxtests/Testingthebasicsblack-boxtests/Testingthebasics

sensitivedataabout/Dataprivacy

serviceabout/Intents

servicestesting/Serviceandcontentprovidertesting

setUp()methodabout/Thetestcasemethods

SHA1,softwaresecurity/Softwaresecuritytermssharedpreferences

about/SharedpreferencessignatureOrSystempermissionlevel

about/Permissionssignaturepermissionlevel

about/Permissionssmartphone

about/Themobileenvironmentvulnerabilities/Themobileenvironment

SMTPabout/HTTPS

sniffingattack,softwaresecurity/Softwaresecuritytermsspoofingattack/SoftwaresecuritytermsSpoon

about/Spoon

Page 272: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

URL,fordownloading/Spoonspoon-client.jarlibrary

about/SpoonSQL

about/ContentprovidersSQLinjection

about/SQLinjectionSSL

about/HTTPS,SSLandTLSSSL3.0

about/SSLandTLSSSLconnection

establishing/SSLandTLSSSLHandshakeException

about/CodeexamplesusingHTTPSstartActivitySyncmethod/InstrumentationStatementcoverage/TestingthebasicsStatetransitiontestingtechnique/Testingthebasicsstickybroadcast

about/Intentsstorageoptions

sharedpreferences/Dataprivacy,Sharedpreferencesinternalstorage/Dataprivacy,Filesintheinternalstorageexternalstorage/Dataprivacy,Filesintheexternalstoragedatabasestorage/Dataprivacy,Thedatabasestorage

symmetriccryptography/Softwaresecuritytermssymmetricencryption

about/EncryptionSyntaxtestingtechnique/TestingthebasicsSystemInformationtab

about/SystemInformationsystemtests/Testingthebasics

Page 273: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TTCP/IPmodel

about/HTTPSphysicallayer/HTTPSlinklayer/HTTPSinternetlayer/HTTPStransportlayer/HTTPSapplicationlayer/HTTPSversus,OSImodel/HTTPS

tcpdump/WiresharktearDown()method

about/Thetestcasemethodsterms,softwaresecurity

accesscontrol/Softwaresecuritytermsasymmetriccryptography/Softwaresecuritytermsauthentication/Softwaresecuritytermsauthorization/Softwaresecuritytermsavailability/Softwaresecuritytermsbruteforce/SoftwaresecuritytermsCipher/Softwaresecuritytermscodeinjection/Softwaresecuritytermsconfidentiality/Softwaresecuritytermscrack/Softwaresecuritytermsdecryption/SoftwaresecuritytermsDenial-of-service(DoS)/SoftwaresecuritytermsDistributeddenial-of-service(DDoS)/SoftwaresecuritytermsDictionaryattack/Softwaresecuritytermsencryption/Softwaresecuritytermshashfunction/SoftwaresecuritytermsHijackattack/SoftwaresecuritytermsHypertextTransferProtocolSecure(HTTPS)/SoftwaresecuritytermsIntegrity/SoftwaresecuritytermsMD5/SoftwaresecuritytermsMan-in-the-middleattack/Softwaresecuritytermspasswords/Softwaresecuritytermsphishing/Softwaresecuritytermsrisk/SoftwaresecuritytermsSHA1/SoftwaresecuritytermsSniffingattack/Softwaresecuritytermsspoofingattack/Softwaresecuritytermssymmetriccryptography/Softwaresecuritytermsthreat/Softwaresecuritytermsvulnerability/Softwaresecurityterms

Page 274: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

TestCaseclassabout/ThetestcaseclassessetUp()method/ThetestcasemethodstearDown()method/Thetestcasemethods

testcaseclassesabout/ThetestcaseclassesTestCaseclass/ThetestcaseclassesInstrumentationTestCaseclass/ThetestcaseclassesActivityTestCaseclass/ThetestcaseclassesActivityInstrumentationTestCase2class/ThetestcaseclassesActivityUnitTestCaseclass/Thetestcaseclasses

testcasemethodsabout/Thetestcasemethods

testing,AndroidapplicationonJVM/TestinginAndroidAndroidSDK,using/TestinginAndroid

testing,contentproviderabout/Serviceandcontentprovidertesting

testing,mediaavailabilityabout/Mediaavailability

testing,networkaccessabout/Networkaccess

testing,orientationchangesabout/Changeinorientation

testing,servicesabout/Serviceandcontentprovidertesting

testingactivitiesfunctionaltesting/Testingactivitiesunittesting/Testingactivitiestestcaseclasses/Thetestcaseclassesinstrumentation/Instrumentationtestcasemethods/ThetestcasemethodsAssertclass/TheAssertclassandmethodassertmethod/TheAssertclassandmethodUItesting/UItestingandTouchUtilsTouchUtils/UItestingandTouchUtilsmockobjectclasses/Themockobjectclasses

testinglevelsunittests/Testingthebasicsintegrationtests/Testingthebasicsvalidationtests/Testingthebasicssystemtests/Testingthebasicsacceptancetests/Testingthebasics

TestView

Page 275: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

about/SpoonThreadstab

about/Threadsthreat

about/Softwaresecurityterms,Threatinterception/Threatinterruption/Threatmodification/Threatfabrication/Threat

three-factorauthenticationabout/Multifactorauthentication

Time-basedOne-TimePassword(TOTP)about/Thepossessionfactor

TLSabout/HTTPS,SSLandTLS

toolsGenymotion/Genymotion

tools,functionaltestingRobotium/Toolsforfunctionaltesting,RobotiumEspresso/Toolsforfunctionaltesting,EspressoAppium/Toolsforfunctionaltesting,AppiumCalabash/Toolsforfunctionaltesting,CalabashMonkeyTalk/Toolsforfunctionaltesting,MonkeyTalkBot-bot/ToolsforfunctionaltestingMonkey/Toolsforfunctionaltesting,MonkeyWireshark/Toolsforfunctionaltesting,Wiresharkbot-bot/Bot-bot

tools,unittestingSpoon/Toolsforunittesting,SpoonMockito/Toolsforunittesting,MockitoAndroidMock/Toolsforunittesting,AndroidMockFESTAndroid/Toolsforunittesting,FESTAndroidRobolectric/Toolsforunittesting,Robolectric

TouchUtilsabout/UItestingandTouchUtils

TouchUtilsclassclickViewmethod/UItestingandTouchUtilsdragmethod/UItestingandTouchUtilsdragQuarterScreenDownmethod/UItestingandTouchUtilsdragViewBymethod/UItestingandTouchUtilsdragViewTomethod/UItestingandTouchUtilsdragViewToTopmethod/UItestingandTouchUtilslongClickViewmethod/UItestingandTouchUtilsscrollToTopmethod/UItestingandTouchUtils

Page 276: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

scrollToBottommethod/UItestingandTouchUtilsTrafficStatsclass

about/NetworkStatisticstransportlayer

about/HTTPSTrustManagerclass/CodeexamplesusingHTTPStwo-factorauthentication

about/Multifactorauthentication

Page 277: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

U@UiThreadTest()method

about/UItestingandTouchUtilsuiautomator.jarlibrary

about/TheuiautomatorAPIuiautomatorAPI

about/TestingtheUI,TheuiautomatorAPIUiDeviceclass/TheUiDeviceclassUiSelectorclass/TheUiSelectorclassUiObjectclass/TheUiObjectclassUiCollectionclass/TheUiCollectionclassUiScrollableclass/TheUiScrollableclass

uiautomatorviewertoolabout/Theuiautomatorviewertool

UiCollectionclassabout/TheUiCollectionclassgetChildByDescription(UiSelectorchildPattern,Stringtext)method/TheUiCollectionclassgetChildByInstance(UiSelectorchildPattern,intinstance)method/TheUiCollectionclassgetChildByText(UiSelectorchildPattern,Stringtext)method/TheUiCollectionclassgetChildCount(UiSelectorchildPattern)method/TheUiCollectionclass

UiDeviceclassabout/TheUiDeviceclassclick(intx,inty)method/TheUiDeviceclassgetDisplaySizeDp()method/TheUiDeviceclasspressBack()method/TheUiDeviceclasspressHome()method/TheUiDeviceclasssleep()method/TheUiDeviceclasstakeScreenshot(Filestorepath)method/TheUiDeviceclasswakeUp()method/TheUiDeviceclass

UiObjectclassabout/TheUiObjectclassclick()method/TheUiObjectclassexists()method/TheUiObjectclassgetText()method/TheUiObjectclassisChecked()method/TheUiObjectclasssetText(Stringtext)method/TheUiObjectclass

UiScrollableclassabout/TheUiScrollableclassscrollBackward()method/TheUiScrollableclassscrollForward()method/TheUiScrollableclass

Page 278: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

scrollToBeginning()method/TheUiScrollableclassscrollToEnd()method/TheUiScrollableclass

UiSelectorclassabout/TheUiSelectorclasschecked(booleanval)method/TheUiSelectorclasschildSelector(UiSelectorselector)method/TheUiSelectorclassclassName(StringclassName)method/TheUiSelectorclassresourceID(Stringid)method/TheUiSelectorclasstext(Stringtext)method/TheUiSelectorclass

UItestcasesexecuting/RunningUItestcases

UItestingabout/TestingtheUI,UItestingandTouchUtilswhite-boxtesting/TestingtheUIblack-boxtesting/TestingtheUIuiautomatorAPI/TheuiautomatorAPIuiautomatorviewertool/Theuiautomatorviewertool

UItestprojectcreating/TheUItestproject

UIthreadabout/Threads

unauthorizedIntentreceiptabout/SecuringIntents

unittestcreating/Creatingaunittestsettingup/Theunittestsetupclocktestmethod,implementing/Theclocktestlayouttestmethod,implementing/ThelayouttestactivityIntenttestmethod,implementing/TheactivityIntenttest

unittestingabout/Testingactivitiestools,using/Toolsforunittesting

unittests/TestingthebasicsunknownCA

solving/CodeexamplesusingHTTPSuser’sdataandcredentials

handling/Handlingauser’sdataandcredentialshandling,considerations/Handlingauser’sdataandcredentials

userID(UID)/AnoverviewofAndroidsecurityuserinterface(UI)

about/Threadsusername/password

about/Theknowledgefactor

Page 279: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

V-vparameter/Monkeyvalidationtests/Testingthebasicsvalues,methodprofilingtool

exclusivetime/Methodprofilinginclusivetime/Methodprofiling

verify()method/MockitoViewAssertsclass/TheAssertclassandmethod

about/TheViewAssertsclassURL/TheViewAssertsclassassertBottomAligned()method/TheViewAssertsclassassertLeftAligned()method/TheViewAssertsclassassertRightAligned()method/TheViewAssertsclassassertTopAligned()method/TheViewAssertsclassassertGroupContains()method/TheViewAssertsclassassertGroupNotContains()method/TheViewAssertsclassassertHasScreenCoordinates()method/TheViewAssertsclassassertHorizontalCenterAligned()method/TheViewAssertsclassassertVerticalCenterAligned()method/TheViewAssertsclassassertOffScreenAbove()method/TheViewAssertsclassassertOffScreenBelow()method/TheViewAssertsclassassertOnScreen()method/TheViewAssertsclass

VirtualBoxURL,fordownloading/Genymotion

vulnerabilities,IntentsunauthorizedIntentreceipt/SecuringIntentsIntentspoofing/SecuringIntents

vulnerabilities,smartphone/Themobileenvironmentvulnerability

about/Softwaresecurityterms,Vulnerabilityimproperauthentication/Vulnerabilitybufferoverflow/Vulnerabilitycross-sitescripting(XSS)/VulnerabilityInputvalidation/VulnerabilitySQLinjection/Vulnerability

Page 280: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

WwaitForIdleSyncmethod/Instrumentationwhen()method/Mockitowhite-boxtesting

about/TestingtheUIwhite-boxtests

about/Testingthebasicswhite-boxtests,techniques

controlflowtesting/Testingthebasicsdataflowtesting/Testingthebasicsbasispathtesting/Testingthebasicsstatementcoverage/Testingthebasics

WiresharkURL/HTTPSabout/WiresharkURL,fordownloading/Wireshark

Page 281: Testing and Securing Android Studio Applications and Securing... · Table of Contents Testing and Securing Android Studio Applications Credits About the Authors About the Reviewers

XX.509certificate

version/Serverandclientcertificatesserialnumber/Serverandclientcertificatessignaturealgorithm/Serverandclientcertificatesissuer/Serverandclientcertificatesvalidity/Serverandclientcertificatessubject/Serverandclientcertificatessubjectpublickey/Serverandclientcertificates