TableofContents
ExploringSEforAndroid
Credits
Foreword
AbouttheAuthors
AbouttheReviewers
www.PacktPub.com
Supportfiles,eBooks,discountoffers,andmore
Whysubscribe?
FreeaccessforPacktaccountholders
Preface
Whatthisbookcovers
Whatyouneedforthisbook
Whothisbookisfor
Conventions
Readerfeedback
Customersupport
Downloadingtheexamplecode
Errata
Piracy
Questions
1.LinuxAccessControls
Changingpermissionbits
Changingownersandgroups
Thecaseformore
Capabilitiesmodel
Android’suseofDAC
GlancingatAndroidvulnerabilities
Skypevulnerability
GingerBreak
www.it-ebooks.info
Rageagainstthecage
MotoChopper
Summary
2.MandatoryAccessControlsandSELinux
Gettingbacktothebasics
Labels
Users
Roles
Types
Accessvectors
Multilevelsecurity
Puttingittogether
Complexitiesandbestpractices
Summary
3.AndroidIsWeird
Android’ssecuritymodel
Binder
Binder’sarchitecture
Binderandsecurity
Zygote–applicationspawn
Thepropertyservice
Summary
4.InstallationontheUDOO
Retrievingthesource
FlashingimageonanSDcard
UDOOserialandAndroidDebugBridge
Flippingtheswitch
It’salive
Summary
5.BootingtheSystem
Policyload
www.it-ebooks.info
Fixingthepolicyversion
Summary
6.ExploringSELinuxFS
Locatingthefilesystem
Interrogatingthefilesystem
Theenforcenode
Thedisablefileinterface
Thepolicyfile
Thenullfile
Themlsfile
Thestatusfile
AccessVectorCache
Thebooleansdirectory
Theclassdirectory
Theinitial_contextsdirectory
Thepolicy_capabilitiesdirectory
ProcFS
JavaSELinuxAPI
Summary
7.UtilizingAuditLogs
Upgrades–patchesgalore
Theauditsystem
Theauditddaemon
Auditdinternals
InterpretingSELinuxdeniallogs
Contexts
Summary
8.ApplyingContextstoFiles
Labelingfilesystems
fs_use
fs_task_use
www.it-ebooks.info
fs_use_trans
genfscon
Mountoptions
Labelingwithextendedattributes
Thefile_contextsfile
Dynamictypetransitions
Examplesandtools
Fixingup/data
Asidenoteonsecurity
Summary
9.AddingServicestoDomains
Init–thekingofdaemons
Dynamicdomaintransitions
Explicitcontextsviaseclabel
Relabelingprocesses
Limitationsonapplabeling
Summary
10.PlacingApplicationsinDomains
Thecasetosecurethezygote
Fortifyingthezygote
Plumbingthezygotesocket
Themac_permissions.xmlfile
keys.conf
seapp_contexts
Summary
11.LabelingProperties
Labelingviaproperty_contexts
Permissionsonproperties
Relabelingexistingproperties
Creatingandlabelingnewproperties
Specialproperties
www.it-ebooks.info
Controlproperties
Persistentproperties
SELinuxproperties
Summary
12.MasteringtheToolChain
Buildingsubcomponents–targetsandprojects
Exploringsepolicy’sAndroid.mk
Buildingsepolicy
Controllingthepolicybuild
Diggingdeeperintobuild_policy
Buildingmac_permissions.xml
Buildingseapp_contexts
Buildingfile_contexts
Buildingproperty_contexts
CurrentNSAresearchfiles
Standalonetools
sepolicy-check
sepolicy-analyze
Summary
13.GettingtoEnforcingMode
UpdatingtoSEPolicymaster
Purgingthedevice
SettingupCTS
RunningCTS
Gatheringtheresults
CTStestresults
Auditlogs
Authoringdevicepolicy
adbd
bootanim
debuggerd
www.it-ebooks.info
drmserver
dumpstate
installd
keystore
mediaserver
netd
rild
servicemanager
surfaceflinger
system_server
toolbox
untrusted_app
vold
watchdogd
wpa
Secondpolicypass
init
shell
init_shell.te
Fieldtrials
Goingenforcing
Summary
A.TheDevelopmentEnvironment
VirtualBox
UbuntuLinux12.04(precisepangolin)
VirtualBoxextensionpackandguestadditions
VirtualBoxextensionpack
VirtualBoxguestadditions
Savetimewithsharedfolders
Thebuildenvironment
OracleJava6
www.it-ebooks.info
ExploringSEforAndroidCopyright©2015PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthors,norPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.
Firstpublished:February2015
Productionreference:1190215
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
BirminghamB32PB,UK.
ISBN978-1-78439-059-4
www.packtpub.com
www.it-ebooks.info
CreditsAuthors
WilliamConfer
WilliamRoberts
Reviewers
JoshuaBrindle
HiromuYakura
CommissioningEditor
UshaIyer
AcquisitionEditor
ReshmaRaman
ContentDevelopmentEditor
ArvindKoul
TechnicalEditor
ShinyPoojary
CopyEditors
ShivangiChaturvedi
VikrantPhadke
NehaVyas
ProjectCoordinator
NehaBhatnagar
Proofreaders
PaulHindle
StephenSilk
Indexer
PriyaSane
ProductionCoordinator
ConidonMiranda
CoverWork
ConidonMiranda
www.it-ebooks.info
ForewordThefirsttalkofSELinuxonAndroidstartedalmostassoonasAndroidwasannounced.TheinterestatthattimewasmainlyshownbyacademiccirclesanddevelopersofSELinuxitself.AsalongtimeuserofSELinuxinserverdeployments,IknewitsbenefitsfromasecuritypointofviewandalsoknewhowmuchAndroidcouldbenefitfromthem.
Atthattime,ImayhavebeencoyaboutthereasonsIwantedtocommitsomeoftheinitialpatchestotheSELinuxproject.LookingbackatthecodereviewsforthoseAndroidOpenSourceProject(AOSP)changes,Inowrememberhowmuchresistancetherewasinthebeginning.Spaceondeviceswasatapremium,anditwasconsideredavictoryifwecouldsaveafewkilobytes.AndhereweretheSELinuxlibrariesandpoliciesthatincreasedthesystemsizebythirtykilobytes!Theperformanceimpacthadnotevenbeenmeasuredatthattime.
TheworkcontinuedunabatedwithSELinuxcontributors,suchasStephenSmalley,RobertCraig,JoshuaBrindle,andanauthorofthisbook,WilliamRoberts,aswellaswiththehelpofmycoworkersGeremyCondraandNickKralevichatGoogle.Slowly,throughtheherculeaneffortsofeveryoneinvolved,theprojectmaterializedandbecamemoreandmorecomplete.SinceAndroid4.4KitKat,SELinuxisshippedinenforcingmode,andallAndroiduserscanbenefitfromtheaddedprotectionthatitaffords.
Thetaledoesn’tendthere!Now,it’syourturntolearn.ThisbookisthefirstreferenceavailableforthespecificflavorofSELinuxfoundinAndroid.It’smysincerehopethatthisbookimpartstheknowledgeyouneedtounderstandandcontributetoitscontinueddevelopment.WilliamRobertshasbeensubmittingcodetoAOSPsincethebeginningofSELinuxforAndroid,andhisandDr.Confer’sknowledgeiscontainedinthesepages.It’suptoyoutoreaditandhelpwritethenextchapterofthissaga.
KennyRoot
MountainView,CA
www.it-ebooks.info
AbouttheAuthorsWilliamConferhasbeenengineeringembeddedandmobilesystemssince1997.HehasworkedforSamsungMobileasamanagingstaffengineerandcurrentlyteachescomputerscienceatSUNYPolytechnicInstitute.Heholdsapatentinlow-costcharacterrecognitionforextremelyresource-limiteddevicesandhasmultipleotherpatentspendingformobiletechnologies.
Mywife,Ása,sacrificedendlesslytohelpgivemethespaceandtimeneededforthiswork,andIowehermorethanIcansay.MythreedaughtersalsoensuredIcouldn’talwaysbeworkingonthisbookanddistractedmeinthebestpossibleways.Icouldn’trestifIdidn’tthankallmyfall2014studentsfromSUNYPolytechnicInstitutewhoputupwithmewhenIwassidetrackedbythisbook.Finally,andmostimportantly,mygreatestthanksgoestomycoauthor(andfriend,student,andteacher),WilliamRoberts,withoutwhomIwouldhavetohavefoundanother.
WilliamRobertsisasoftwareengineerwhoisfocusedonOS-levelsecurityandplatformenhancements.HeisoneoftheengineerswhofoundedtheSamsungKNOXproductandanearlyadopterofSEforAndroid.Hehasmadecontributionstoseveralopensourceprojects,suchasSEforAndroid,theAndroidOpenSourceProject,theLinuxKernel,CyanogenMod,andOpenSC.HisrecentinterestshavetakenhimtoSmartCardtechnologiesandthevirtualizationofsmartcards.Inhissparetime,heworkswithDr.ConferontheMiniatproject(http://www.miniat.org),avirtual,embeddedarchitecturesimulator.
IwouldliketothankDr.WilliamConfer,thecoauthor,forhelpingmewritethisbook;hiscontributionswereinvaluable.Also,Iwouldliketothankmywifeforsupportingmeandgivingmethetimetodothis,eventhoughwewererenovatingthehouse.Also,Iwouldliketothankmyfamilyandfriendsfortheirencouragementalongtheway.
www.it-ebooks.info
AbouttheReviewersJoshuaBrindleistheCTOandcofounderofQuarkSecurityInc.,acompanyfocusedonsolvingmobileandcross-domainsecurityproblems.Joshuahas12yearsofprofessionalexperienceintheareaofdevelopmentforgovernment,academic,andopensourcesoftwarethatfocusesonsecurityinLinux.Joshuahascontributedtonumerousopensourceprojects,bothasaprojectmaintainerandasadeveloper.HisworkcanbefoundonallSELinuxsystemsandnearlyallLinuxsystems.Joshua’srecentexperiencefocusesonbuildingsecuremobiledevicesusingtechnologiessuchasSecurityEnhancementsforAndroid,mobiledevice,andapplicationmanagement.
HiromuYakuraisastudentatNadaHighSchool,Japan.HeistheyoungestpersontoholdthenationalinformationsecurityqualificationfromJapan.HehasgivenlecturesaboutSEforAndroidatmanyconferences.Heisalsofamiliarwiththesecuritycompetition,CapturetheFlag(CTF),andhasparticipatedinDEFCONCTF2014asateambinja.
Iwouldliketoexpressmygratitudetomyfamilyfortheirunderstandingandsupport.
www.it-ebooks.info
Supportfiles,eBooks,discountoffers,andmoreForsupportfilesanddownloadsrelatedtoyourbook,pleasevisitwww.PacktPub.com.
DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusat<[email protected]>formoredetails.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooksandeBooks.
https://www2.packtpub.com/books/subscription/packtlib
DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt’sonlinedigitalbooklibrary.Here,youcansearch,access,andreadPackt’sentirelibraryofbooks.
www.it-ebooks.info
Whysubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviaawebbrowser
www.it-ebooks.info
FreeaccessforPacktaccountholdersIfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccessPacktLibtodayandview9entirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess.
www.it-ebooks.info
PrefaceThisbookintroducestheSecurityEnhancements(SE)forAndroidopensourceprojectandwalksyouthroughtheprocessofsecuringnewembeddedsystemswithSEforAndroid.Toourknowledge,thisbookisthefirstsourcetodocumentsuchaprocessinitsentiretysothatstudents,DIYhobbyists,andengineerscancreatecustomsystemssecuredbySEforAndroid.Generally,onlyoriginalequipmentmanufacturers(OEMs)dothis,andquitecommonly,thetargetdeviceisaphoneortablet.Wetrulyhopeourbookwillchangethat,engagingawideaudienceindevelopmentsotheycanuseandunderstandthesemodernsecuritytools.
Weworkedveryhardtoensurethistextisnotjustastep-by-steptechnologybook.Specifically,we’vechosenamodelthatdirectsyoutofailyourwaytosuccess.Youwillfirstgainappropriatetheoreticalunderstandingofhowsecurityisgainedandenforced.Thenwewillintroduceasystemthathasneverbeensecuredthatway(notevenbyus,priortowritingthisbook).Next,we’llguideyouthroughallourintelligentguesswork,embracingunexpectedfailuresforthenewlyfoundidiosyncrasiestheyexpose,andeventuallyenforcingourcustomsecuritypolicies.ItrequiresyoutolearntoresolvedifferencesbetweenmajoropensourceprojectssuchasSELinux,SEforAndroid,andGoogleAndroid,eachofwhichhasindependentgoalsanddeploymentschedules.Thispreparesyoutosecureotherdevices,theprocessforwhichisalwaysdifferent,buthopefully,willnowbemoreaccessible.
www.it-ebooks.info
WhatthisbookcoversChapter1,LinuxAccessControls,discussesthebasicsofDiscretionaryAccessControl(DAC),howsomeAndroidexploitsleverageDACproblems,anddemonstratetheneedformorerobustsolutions.
Chapter2,MandatoryAccessControlsandSELinux,examinesMandatoryAccessControl(MAC)anditsmanifestationinSELinux.ThischapteralsoexplorestangiblepolicytocontrolSELinuxobjectinteraction.
Chapter3,AndroidIsWeird,introducestheAndroidsecuritymodelandinvestigatesbinder,zygote,andthepropertyservice.
Chapter4,InstallationontheUDOO,walksthroughbuildinganddeployingAndroidfromsourcetotheUDOO-embeddedboardandturnsonSELinuxsupport.
Chapter5,BootingtheSystem,followsthebootprocessfromthepolicyloadingperspectiveandcorrectsissuestogetSELinuxtoausablestateontheUDOO.
Chapter6,ExploringSELinuxFS,examinestheSELinuxFSfilesystemandhowitprovidesthekernel-to-userspaceinterfaceforhigher-levelidioms.
Chapter7,UtilizingAuditLogs,investigatestheauditsubsystem,revealinghowtointerpretSELinuxauditlogsforthebenefitofpolicywriting.
Chapter8,ApplyingContextstoFiles,teachesyouhowfilesystemsandfilesystemobjectsgettheirlabelsandcontexts,demonstratingtechniquestochangethem,includingdynamictypetransitions.
Chapter9,AddingServicestoDomains,emphasizesprocesslabeling,notablytheAndroidservicesrunandmanagedbyinit.
Chapter10,PlacingApplicationsinDomains,showsyouhowtoproperlylabeltheprivatedatadirectoriesofapplications,aswellasapplicationruntimecontextsviaconfigurationfilesandSELinuxpolicy.
Chapter11,LabelingProperties,demonstrateshowtocreateandlabelnewandexistingproperties,andsomeoftheanomaliesthatoccurwhendoingso.
Chapter12,MasteringtheToolChain,covershowthevariouscomponentsthatcontrolpolicyonthedeviceareactuallybuiltandcreated.ThischapterreviewstheAndroid.mkcomponents,detailinghowtheheartofthebuildandconfigurationmanagementworks.
Chapter13,GettingtoEnforcingMode,utilizesalltheskillsyoulearnedintheearlierchapterstorespondtoauditlogsfromCTSandgettheUDOOinenforcingmode.
Appendix,TheDevelopmentEnvironment,walksyouthroughthenecessarystepsofsettingupaLinuxenvironmentsuitableforyoutofollowalltheactivitiesinthisbook.
www.it-ebooks.info
WhatyouneedforthisbookHardwarerequirementsinclude:
AUDOO-embeddeddevelopmentboardAn8GBMiniSDcard(whileyoucanuseacardwithgreatercapacity,wedonotrecommendedit)Aminimumof16GBofRAMAtleast80GBoffreeharddrivespace
Softwarerequirementsinclude:
AnUbuntu12.04LTSdesktopsystemOracleJDK6.0version6u45SomeadditionalmiscellaneousLinuxsoftwareisrequired,butthesearedescribedinthebookandareavailableforfree.
www.it-ebooks.info
WhothisbookisforThisbookisintendedfordevelopersandengineerswhoaresomewhatfamiliarwithoperatingsystemconceptsasimplementedbyLinux.TheycouldbehobbyistswantingtosecuretheirAndroid-poweredcreations,OEMengineersbuildinghandsets,orengineersfromemergingareaswhereAndroidisseeinggrowth.AbasicbackgroundinCprogrammingwillbehelpful.
www.it-ebooks.info
ConventionsInthisbook,youwillfindanumberoftextstylesthatdistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestylesandexplanationsoftheirmeanings.
Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,dummyURLs,userinput,andTwitterhandlesareshownasfollows:“Nowlet’sattempttoexecutethehello.txtfileandseewhathappens.”
Ablockofcodeissetasfollows:
caseINTERFACE_TRANSACTION:
{
reply.writeString(DESCRIPTOR);
returntrue;
}
Anycommand-lineinputoroutputiswrittenasfollows:
$sutestuser
Password:
testuser@ubuntu:/home/bookuser$
Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen,forexample,inmenusordialogboxes,appearinthetextlikethis:“ExittheconfigurationmenusbyselectingExituntilyouareaskedtosaveyournewconfiguration.”
NoteWarningsorimportantnotesappearinaboxlikethis.
TipTipsandtricksappearlikethis.
www.it-ebooks.info
ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook—whatyoulikedordisliked.Readerfeedbackisimportantforusasithelpsusdeveloptitlesthatyouwillreallygetthemostoutof.
Tosendusgeneralfeedback,simplye-mail<[email protected]>,andmentionthebook’stitleinthesubjectofyourmessage.
Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideatwww.packtpub.com/authors.
www.it-ebooks.info
CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.
www.it-ebooks.info
DownloadingtheexamplecodeYoucandownloadtheexamplecodefilesfromyouraccountathttp://www.packtpub.comforallthePacktPublishingbooksyouhavepurchased.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.
www.it-ebooks.info
ErrataAlthoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdohappen.Ifyoufindamistakeinoneofourbooks—maybeamistakeinthetextorthecode—wewouldbegratefulifyoucouldreportthistous.Bydoingso,youcansaveotherreadersfromfrustrationandhelpusimprovesubsequentversionsofthisbook.Ifyoufindanyerrata,pleasereportthembyvisitinghttp://www.packtpub.com/submit-errata,selectingyourbook,clickingontheErrataSubmissionFormlink,andenteringthedetailsofyourerrata.Onceyourerrataareverified,yoursubmissionwillbeacceptedandtheerratawillbeuploadedtoourwebsiteoraddedtoanylistofexistingerrataundertheErratasectionofthattitle.
Toviewthepreviouslysubmittederrata,gotohttps://www.packtpub.com/books/content/supportandenterthenameofthebookinthesearchfield.TherequiredinformationwillappearundertheErratasection.
www.it-ebooks.info
PiracyPiracyofcopyrightedmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.IfyoucomeacrossanyillegalcopiesofourworksinanyformontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.
Pleasecontactusat<[email protected]>withalinktothesuspectedpiratedmaterial.
Weappreciateyourhelpinprotectingourauthorsandourabilitytobringyouvaluablecontent.
www.it-ebooks.info
QuestionsIfyouhaveaproblemwithanyaspectofthisbook,youcancontactusat<[email protected]>,andwewilldoourbesttoaddresstheproblem.
www.it-ebooks.info
Chapter1.LinuxAccessControlsAndroidisanoperatingsystemcomposedoftwodistinctcomponents.ThefirstcomponentisaforkedmainlineLinuxkernelandsharesalmosteverythingincommonwithLinux.Thesecondcomponent,whichwillbediscussedlater,istheuserspaceportion,whichisverycustomandAndroidspecific.SincetheLinuxkernelunderpinsthissystemandisresponsibleforthemajorityofaccesscontroldecisions,itisthelogicalplacetobeginadetailedlookatAndroid.
Inthischapterwewill:
ExaminethebasicsofDiscretionaryAccessControlIntroduceLinuxpermissionsflagsandcapabilitiesTracesyscallsaswevalidateaccesspoliciesMakethecaseformorerobustaccesscontroltechnologyDiscussAndroidexploitsthatleverageproblemswithDiscretionaryAccessControl
Linux’sdefaultandfamiliaraccesscontrolmechanismiscalledDiscretionaryAccessControl(DAC).Thisisjustatermthatmeanspermissionsregardingaccesstoanobjectareatthediscretionofitscreator/owner.
InLinux,whenaprocessinvokesmostsystemcalls,apermissioncheckisperformed.Asanexample,aprocesswishingtoopenafilewouldinvoketheopen()syscall.Whenthissyscallisinvoked,acontextswitchisperformed,andtheoperatingsystemcodeisexecuted.TheOShastheabilitytodeterminewhetherafiledescriptorshouldbereturnedtotherequestingprocessornot.Duringthisdecision-makingprocess,theOScheckstheaccesspermissionsofboththerequestingprocessandthetargetfileitwishestoobtainthefiledescriptorto.EitherthefiledescriptororEPERMisreturned,dependentonwhetherthepermissioncheckspassorfailrespectively.
Linuxmaintainsdatastructuresinthekernelformanagingthesepermissionfields,whichareaccessiblefromuserspace,andonesthatshouldbefamiliartoLinuxand*NIXusersalike.Thefirstsetofaccesscontrolmetadatabelongstotheprocess,andformsaportionofitscredentialset.Thecommoncredentialsareuserandgroup.Ingeneral,weusethetermgrouptomeanbothprimarygroupandpossiblesecondarygroup(s).Youcanviewthesepermissionsbyrunningthepscommand:
$ps-eopid,comm,user,group,supgrp
PIDCOMMANDUSERGROUPSUPGRP
1initrootroot-
...
2993system-service-rootrootroot
3276chromium-browsebookusersudofusebookuser
...
Asyoucansee,wehaveprocessesrunningastheusersrootandbookuser.Youcanalsoseethattheirprimarygroupisonlyonepartoftheequation.Processesalsohaveasecondarysetofgroupscalledsupplementarygroups.Thissetmightbeempty,indicatedbythedashintheSUPGRPfield.
www.it-ebooks.info
Thefilewewishtoopen,referredtoasthetargetobject,target,orobjectalsomaintainsasetofpermissions.TheobjectmaintainsUSERandGROUP,aswellasasetofpermissionbits.Inthecontextofthetargetobject,USERcanbereferredtoasownerorcreator.
$ls-la
total296
drwxr-xr-x38bookuserbookuser4096Aug2311:08.
drwxr-xr-x3rootroot4096Jun818:50..
-rw-rw-r--1bookuserbookuser116Jul2213:13a.c
drwxrwxr-x4bookuserbookuser4096Aug416:20.android
-rw-rw-r--1bookuserbookuser130Jun1917:51.apport-ignore.xml
-rw-rw-r--1bookuserbookuser365Jun2319:44hello.txt
-rw-------1bookuserbookuser19276Aug416:36.bash_history
...
Ifwelookattheprecedingcommand’soutput,wecanseethathello.txthasaUSERofbookuserandGROUPasbookuser.Wecanalsoseethepermissionbitsorflagsontheleft-handsideoftheoutput.Therearesevenfieldstoconsideraswell.Eachemptyfieldisdenotedwithadash.Whenprintedwithls,thefirstfieldscangetconvolutedbysemantics.Forthisreason,let’susestattoinvestigatethefilepermissions:
$stathello.txt
File:`hello.txt'
Size:365Blocks:8IOBlock:4096regularfile
Device:801h/2049dInode:1587858Links:1
Access:(0664/-rw-rw-r--)Uid:(1000/bookuser)Gid:(1000/bookuser)
Access:2014-08-0415:53:01.951024557-0700
Modify:2014-06-2319:44:14.308741592-0700
Change:2014-06-2319:44:14.308741592-0700
Birth:-
Thefirstaccesslineisthemostcompelling.Itcontainsalltheimportantinformationfortheaccesscontrols.Thesecondlineisjustatimestamplettingusknowwhenthefilewaslastaccessed.Aswecansee,USERorUIDoftheobjectisbookuser,andGROUPisbookuseraswell.Thepermissionflags,(0664/-rw-rw-r--),identifythetwowaysthatpermissionflagsarerepresented.Thefirst,theoctalform0664,condenseseachthree-flagfieldintooneofthethreebase-8(octal)digits.Thesecondisthefriendlyform,-rw-rw-r--,equivalenttotheoctalformbuteasiertointerpretvisually.Ineithercase,wecanseetheleftmostfieldis0,andtherestofourdiscussionswillignoreit.Thatfieldisforsetuidandsetgidcapabilities,whichisnotimportantforthisdiscussion.Ifweconverttheremainingoctaldigits,664,tobinary,weget110110100.Thisbinaryrepresentationdirectlyrelatestothefriendlyform.Eachtriplemapstoread,write,andexecutepermissions.OftenyouwillseethispermissiontriplerepresentedasRWX.ThefirsttriplearethepermissionsgiventoUSER,thesecondarethepermissionsgiventoGROUP,andthethirdiswhatisgiventoOTHERS.TranslatingtoconventionalEnglishwouldyield,“Theuser,bookuser,haspermissiontoreadfromandwritetohello.txt.Thegroup,bookuser,haspermissiontoreadfromandwritetohello.txt,andeveryoneelsehaspermissiononlytoreadfromhello.txt.”Let’stestthiswithsomereal-worldexamples.
www.it-ebooks.info
ChangingpermissionbitsLet’stesttheaccesscontrolsintheexamplerunningprocessesasuserbookuser.Mostprocessesruninthecontextoftheuserthatinvokedthem(excludingsetuidandgetuidprograms),soanycommandweinvokeshouldinheritouruser’spermissions.Wecanviewitbyissuing:
$groupsbookuser
bookuser:bookusersudofuse
Myuser,bookuser,isUSERbookuser,GROUPbookuserandSUPGRPsudoandfuse.
Totestforreadaccess,wecanusethecatcommand,whichopensthefileandprintsitscontenttostdout:
$cathello.txt
Hello,"ExploringSEforAndroid"
Hereisasimpletextfilefor
yourenjoyment.
...
Wecanintrospectthesyscallsexecutedbyrunningthestracecommandandviewingtheoutput:
$stracecathello.txt
...
open("hello.txt",O_RDONLY)=3
...
read(3,"Hello,\"ExploringSEforAndroid\"\n"...,32768)=365
...
Theoutputcanbequiteverbose,soIamonlyshowingtherelevantparts.Wecanseethatcatinvokedtheopensyscallandobtainedthefiledescriptor3.Wecanusethatdescriptortofindotheraccessesviaothersyscalls.Laterwewillseeareadoccurringonfiledescriptor3,whichreturns365,thenumberofbytesread.Ifwedidn’thavepermissiontoreadfromhello.txt,theopenwouldfail,andwewouldneverhaveavalidfiledescriptorforthefile.Wewouldadditionallyseethefailureinthestraceoutput.
Nowthatreadpermissionisverified,let’strywrite.Onesimplewaytodothisistowriteasimpleprogramthatwritessomethingtotheexistingfile.Inthiscase,wewillwritethelinemynewtext\n(refertowrite.c.)
Compiletheprogramusingthefollowingcommand:
$gcc-omywritewrite.c
Nowrunusingthenewlycompiledprogram:
$strace./mywritehello.txt
Onverification,youwillsee:
...
open("hello.txt",O_WRONLY)=3
www.it-ebooks.info
write(3,"mynewtext\n",12)=12
...
Asyoucansee,thewritesucceededandreturned12,thenumberofbyteswrittentohello.txt.Noerrorswerereported,sothepermissionsseeminchecksofar.
Nowlet’sattempttoexecutehello.txtandseewhathappens.Weareexpectingtoseeanerror.Let’sexecuteitlikeanormalcommand:
$./hello.txt
bash:./hello.txt:Permissiondenied
Thisisexactlywhatweexpected,butlet’sinvokeitwithstracetogainadeeperunderstandingofwhatfailed:
$strace./hello.txt
...
execve("./hello.txt",["./hello.txt"],[/*39vars*/])=-1EACCES
(Permissiondenied)
...
Theexecvesystemcall,whichlaunchesprocesses,failedwithEACCESS.Thisisjustthesortofthingonewouldhopeforwhennoexecutepermissionisgiven.TheLinuxaccesscontrolsworkedasexpected!
Let’stesttheaccesscontrolsinthecontextofanotheruser.First,we’llcreateanewusercalledtestuserusingtheaddusercommand:
$sudoaddusertestuser
[sudo]passwordforbookuser:
Addinguser`testuser'...
Addingnewgroup`testuser'(1001)...
Addingnewuser`testuser'(1001)withgroup`testuser'...
Creatinghomedirectory`/home/testuser'...
...
VerifytheUSER,GROUP,andSUPGRPoftestuser:
$groupstestuser
testuser:testuser
SincetheUSERandGROUPdonotmatchanyofthepermissionsona.S,allaccesseswillbesubjecttotheOTHERSpermissionschecks,whichifyourecall,isreadonly(0664).
Startbytemporarilyworkingastestuser:
$sutestuser
Password:
testuser@ubuntu:/home/bookuser$
Asyoucansee,wearestillinbookuser’shomedirectory,butthecurrentuserhasbeenchangedtotestuser.
Wewillstartbytestingreadwiththecatcommand:
$stracecathello.txt
...
www.it-ebooks.info
open("hello.txt",O_RDONLY)=3
...
read(3,"mynewtext\n",32768)=12
...
Similartotheearlierexample,testusercanreadthedatajustfine,asexpected.
Nowlet’smoveontowrite.Theexpectationisthatthiswillfailwithoutappropriateaccess:
$strace./mywritehello.txt
...
open("hello.txt",O_WRONLY)=-1EACCES(Permission
denied)
...
Asexpected,thesyscalloperationfailed.Whenweattempttoexecutehello.txtastestuser,thisshouldfailaswell:
$strace./hello.txt
...
execve("./hello.txt",["./hello.txt"],[/*40vars*/])=-1EACCES
(Permissiondenied)
...
Nowweneedtotestthegroupaccesspermissions.Wecandothisbyaddingasupplementarygrouptotestuser.Todothis,weneedtoexittobookuser,whohaspermissionstoexecutethesudocommand:
$exit
exit
$sudousermod-Gbookusertestuser
Nowlet’scheckthegroupsoftestuser:
$groupstestuser
testuser:testuserbookuser
Asaresultoftheprevioususermodcommandtestusernowbelongstotwogroups:testuserandbookuser.Thatmeanswhentestuseraccessesafileorotherobject(suchasasocket)withthegroupbookuser,theGROUPpermissions,ratherthanOTHERS,willapplytoit.Inthecontextofhello.txt,testusercannowreadfromandwritetothefile,butnotexecuteit.
Switchtotestuserbyexecutingthefollowingcommand:
$sutestuser
Testreadbyexecutingthefollowingcommand:
$stracecat./hello.txt
...
open("./hello.txt",O_RDONLY)=3
...
read(3,"mynewtext\n",32768)=12
...
www.it-ebooks.info
Asbefore,testuserisabletoreadthefile.TheonlydifferenceisthatitcannowreadthefilethroughtheaccesspermissionsofOTHERSandGROUP.
Testwritebyexecutingthefollowingcommand:
$strace./mywritehello.txt
...
open("hello.txt",O_WRONLY)=3
write(3,"mynewtext\n",12)=12
...
Thistime,testuserwasabletowritethefileaswell,insteadoffailingwiththeEACCESSpermissionerrorshownbefore.
Attemptingtoexecutethefileshouldstillfail:
$strace./hello.txt
execve("./hello.txt",["./hello.txt"],[/*40vars*/])=-1EACCES
(Permissiondenied)
...
TheseconceptsarethefoundationofLinuxaccesscontrolpermissionbits,usersandgroups.
www.it-ebooks.info
ChangingownersandgroupsUsinghello.txtforexploratoryworkintheprevioussections,wehaveshownhowtheownerofanobjectcanallowvariousformsofaccessbymanagingthepermissionbitsoftheobject.Changingthepermissionsisaccomplishedusingthechmodsyscall.Changingtheuserand/orgroupisdonewiththechownsyscall.Inthissection,wewillinvestigatethedetailsoftheseoperationsinaction.
Let’sstartbygrantingreadandwritepermissionsonlytotheownerofhello.txtfile,bookuser.
$chmod0600hello.txt
$stathello.txt
File:`hello.txt'
Size:12Blocks:8IOBlock:4096regularfile
Device:801h/2049dInode:1587858Links:1
Access:(0600/-rw-------)Uid:(1000/bookuser)Gid:(1000/bookuser)
Access:2014-08-2312:34:30.147146826-0700
Modify:2014-08-2312:47:19.123113845-0700
Change:2014-08-2312:59:04.275083602-0700
Birth:-
Aswecansee,thefilepermissionsarenowsettoonlyallowreadandwriteaccessforbookuser.Athoroughreadercouldexecutethecommandsfromearliersectionsinthischaptertoverifythatpermissionsworkasexpected.
Changingthegroupcanbedoneinasimilarfashionwithchown.Let’schangethegrouptotestuser:
$chownbookuser:testuserhello.txt
chown:changingownershipof`hello.txt':Operationnotpermitted
Thisdidnotworkasweintended,butwhatistheissue?InLinux,onlyprivilegedprocessescanchangetheUSERandGROUPfieldsofobjects.TheinitialUSERandGROUPfieldsaresetduringobjectcreationfromtheeffectiveUSERandGROUP,whicharecheckedwhenattemptingtoexecutethatprocess.Onlyprocessescreateobjects.Privilegedprocessescomeintwoforms:thoserunningasthealmightyrootandthosethathavetheircapabilitiesset.Wewilldiveintothedetailsofcapabilitieslater.Fornow,let’sfocusontheroot.
Let’schangetheusertoroottoensureexecutingthechowncommandwillchangethegroupofthatobject:
$sudosu
#chownbookuser:testuserhello.txt
Now,wecanverifythechangeoccurredsuccessfully:
#stathello.txt
File:`hello.txt'
Size:12Blocks:8IOBlock:4096regularfile
Device:801h/2049dInode:1587858Links:1
Access:(0600/-rw-------)Uid:(1000/bookuser)Gid:(1001/testuser)
Access:2014-08-2312:34:30.147146826-0700
www.it-ebooks.info
Modify:2014-08-2312:47:19.123113845-0700
Change:2014-08-2313:08:46.059058649-0700
Birth:-
www.it-ebooks.info
ThecaseformoreYoucanseetheGROUP(GID)isnowtestuser,andthingsseemreasonablysecurebecauseinordertochangetheuserandgroupofanobject,youneedtobeprivileged.Youcanonlychangethepermissionbitsonanobjectifyouownit,withtheexceptionoftherootuser.Thismeansthatifyou’rerunningasroot,youcandowhateveryouliketothesystem,evenwithoutpermission.Thisabsoluteauthorityiswhyasuccessfulattackoranerroronarootrunningprocesscancausegravedamagetothesystem.Also,asuccessfulattackonanon-rootprocesscouldalsocausedamagebyinadvertentlychangingthepermissionsbits.Forexample,supposethereisanunintendedchmod0666commandonyourSSHprivatekey.Thiswouldexposeyoursecretkeytoallusersonthesystem,whichisalmostcertainlysomethingyouwouldneverwanttohappen.Therootlimitationispartiallyaddressedbythecapabilitiesmodel.
www.it-ebooks.info
CapabilitiesmodelFormanyoperationsonLinux,theobjectpermissionmodeldoesn’tquitefit.Forinstance,changingUIDandGIDrequiressomemagicalUSERknownasroot.Supposeyouhavealongrunningservicethatneedstoutilizesomeofthesecapabilities.Perhapsthisservicelistenstokerneleventsandcreatesthedevicenodesforyou?Suchaserviceexists,andit’scalledueventdorusereventdaemon.Thisdaemontraditionallyrunsasroot,whichmeansifitiscompromised,itcouldpotentiallyreadyourprivatekeysfromyourhomedirectoryandsendthembacktotheattacker.Thismightbeanextraordinaryexample,butit’smeanttoshowcasethatrunningprocessesasrootcanbedangerous.SupposeyoucouldstartaserviceastherootuserandhavetheprocesschangeitsUIDandGIDtosomethingnotprivileged,butretainsomesmallersetofprivilegedcapabilitiestodoitsjob?ThisisexactlywhatthecapabilitiesmodelinLinuxis.
ThecapabilitiesmodelinLinuxisanattempttobreakdownthesetofpermissionsthatroothasintosmallersubsets.Thisway,processescanbeconfinedtothesetofminimumprivilegestheyneedtoperformtheirintendedfunction.Thisisknownasleastprivilege,akeyideologywhensecuringsystemsthatminimizestheamountofdamageasuccessfulattackcando.Insomeinstances,itcanevenpreventasuccessfulattackfromoccurringbyblockinganotherwiseopenattackvector.
Therearemanycapabilities.Themanpageforcapabilitiesisthedefactodocumentation.Let’stakealookattheCAP_SYS_BOOTcapability:
$mancapabilities
...
CAP_SYS_BOOT
Usereboot(2)andkexec_load(2).
Thismeansaprocessrunningwiththiscapabilitycanrebootthesystem.However,thatprocesscan’tarbitrarilychangeUSERSandGROUPasitcouldifitwasrunningasrootorwithCAP_DAC_READ_SEARCH.Thislimitswhatanattackercando:
<FROMMANPAGE>
CAP_DAC_READ_SEARCH
Bypassfilereadpermissionchecksanddirectoryreadandexecute
permissionchecks.
NowsupposethecasewhereourrestartprocessrunswithCAP_CHOWN.Let’ssayitusesthiscapabilitytoensurethatwhenarestartrequestisreceived,itbacksupafilefromeachuser’shomedirectorytoaserverbeforerestarting.Let’ssaythisfileis~/backup,thepermissionsare0600,andUSERandGROUParetherespectiveuserofthathomedirectory.Inthiscase,wehaveminimizedthepermissionsasbestwecan,buttheprocesscouldstillaccesstheusersSSHkeysanduploadthoseeitherbyerrororattack.AnotherapproachtothiswouldbetosetthegrouptobackupandruntheprocesswithGROUPbackup.However,thishaslimitations.Supposeyouwanttosharethisfilewithanotheruser.Thatuserwouldrequireasupplementarygroupofbackup,butnowtheusercanreadallofthebackupfiles,notjusttheonesintended.Anastutereadermightthinkaboutthebind
www.it-ebooks.info
mounts,howevertheprocessdoingthebindmountsandfilepermissionsalsorunswithsomecapability,andthussuffersfromthisgranularityproblemaswell.
Themajorissue,andthecaseforanotheraccesscontrolsystemcanbesummarizedbyoneword,granularity.TheDACmodeldoesn’thavethegranularityrequiredtosafelyhandlecomplexaccesscontrolmodelsortominimizetheamountofdamageaprocesscando.ThisisparticularlyimportantonAndroid,wheretheentireisolationsystemisdependentonthiscontrol,andaroguerootprocesscancompromisethewholesystem.
www.it-ebooks.info
Android’suseofDACIntheAndroidsandboxmodel,everyapplicationrunsasitsownUID.Thismeansthateachappcanseparateitsstoreddatafromoneanother.TheuserandgrouparesettotheUIDandGIDofthatapplication,sonoappcanaccesstheprivatefilesofanapplicationwithouttheapplicationexplicitlyperformingchmodonitsobjects.Also,applicationsinAndroidcannothavecapabilities,sowedon’thavetoworryaboutcapabilitiessuchasCAP_SYS_PTRACE,whichistheabilitytodebuganotherapplication.InAndroid,inaperfectworld,onlysystemcomponentsrunwithprivileges,andapplicationsdon’taccidentallychmodprivatefilesforalltoread.ThisissuewasnotcorrectedbythecurrentAOSPSELinuxpolicyduetoappcompatibility,butcouldbeclosedwithSELinux.TheproperwaytosharedatabetweenapplicationsonAndroidisviabinder,andsharingfiledescriptors.Forsmalleramountsofdata,theprovidermodelsuffices.
www.it-ebooks.info
GlancingatAndroidvulnerabilitiesWithournewlyfoundunderstandingoftheDACpermissionmodelandsomeofitslimitations,let’slookatsomeAndroidexploitsagainstit.WewillcoveronlyafewexploitstounderstandhowtheDACmodelfailed.
www.it-ebooks.info
SkypevulnerabilityCVE-2011-1717wasreleasedin2011.Inthisexploit,theSkypeapplicationleftaSQLite3databaseworldreadable(somethinganalogousto0666permissions).Thisdatabasecontainedusernamesandchatlogs,andpersonaldatasuchasnameande-mail.AnapplicationcalledSkypwnedwasabletodemonstratethiscapability.Thisisanexampleofhowbeingabletochangethepermissionsonyourobjectscouldbebad,especiallywhenthecaseopensREADtoOTHERS.
www.it-ebooks.info
GingerBreakCVE-2011-1823showcasesarootattackonAndroid.Thevolumemanagementdaemon(vold)onAndroidisresponsibleforthemountingandunmountingoftheexternalSDcard.ThedaemonlistensformessagesoveraNETLINKsocket.Thedaemonnevercheckedwherethemessagesweresourcedfrom,andanyapplicationcouldopenandcreateaNETLINKsockettosendmessagestovold.OncetheattackeropenedtheNETLINKsocket,theysentaverycarefullycraftedmessagetobypassasanitycheck.Thechecktestedasignedintegerforamaximumbound,butnevercheckeditfornegativity.Itwasthenusedtoindexanarray.Thisnegativeaccesswouldleadtomemorycorruptionand,withapropermessage,couldresultintheexecutionofarbitrarycode.TheGingerBreakimplementationresultedinanarbitraryusergainingrootprivileges,atextbookprivilegeexecutionattack.Oncerooted,thedevice’ssandboxeswerenolongervalid.
www.it-ebooks.info
RageagainstthecageCVE-2010-EASYisasetuidexhaustionviaforkbombattack.ItsuccessfullyattackstheadbdaemononAndroid,whichstartslifeasrootanddowngradesitspermissionsifrootisnotneeded.Thisattackkeepsadbasrootandreturnsarootshelltotheuser.InLinuxkernel2.6,thesetuidsystemcallreturnsanerrorwhenthenumberofrunningprocessesRLIMIT_NPROCismet.Theadbdaemoncodedoesnotcheckthereturnofsetuid,whichleavesasmallracewindowopenfortheattacker.TheattackerneedstoforkenoughprocessestoreachRLIMIT_NPROCandthenkillthedaemon.TheadbdaemondowngradestoshellUIDandtheattackerrunstheprogramasshellUSER,thusthekillwillwork.Atthispoint,theadbserviceisrespawned,andifRLIMIT_NPROCismaxedout,setuidwillfailandadbwillstayrunningasroot.Then,runningadbshellfromahostreturnsanicerootshelltotheuser.
www.it-ebooks.info
MotoChopperCVE-2013-2596isavulnerabilityinthemmapfunctionalityofaQualcommvideodriver.AccesstotheGPUisprovidedbyappstodoadvancedgraphicsrenderingsuchasinthecaseofOpenGLcalls.Thevulnerabilityinmmapallowstheattackertommapkerneladdressspace,atwhichpointtheattackerisabletodirectlychangetheirkernelcredentialstructure.ThisexploitisanexamplewheretheDACmodelwasnotatfault.Inreality,outsideofpatchingthecodeorremovingdirectgraphicsaccess,nothingbutprogrammingchecksofthemmapboundscouldhavepreventedthisattack.
www.it-ebooks.info
SummaryTheDACmodelisextremelypowerful,butitslackoffinegranularityanduseofanextraordinarilypowerfulrootuserleavessomethingtobedesired.Withtheincreasingsensitivityofmobilehandsetuse,thecasetoincreasethesecurityofthesystemiswell-founded.Thankfully,AndroidisbuiltonLinuxandthusbenefitsfromalargeecosystemofengineersandresearchers.SincetheLinuxKernel2.6,anewaccesscontrolmodelcalledMandatoryAccessControls(MAC)wasadded.Thisisaframeworkbywhichmodulescanbeloadedintothekerneltoprovideanewformofaccesscontrolmodel.TheveryfirstmodulewascalledSELinux.ItisusedbyRedHatandotherstosecuresensitivegovernmentsystems.Thus,asolutionwasfoundtoenablesuchaccesscontrolsforAndroid.
www.it-ebooks.info
Chapter2.MandatoryAccessControlsandSELinuxInChapter1,LinuxAccessControls,weintroducedsomeoftheshortcomingsofadiscretionaryaccesscontrolsystem.Inthesesystems,theownerofanobjecthasfullcontroloveritspermissionsflagsandcandemonstrategreatercapabilities(forexample,theabilitytochown)whenexecutingasrootorwithcertaincapabilities.Inthischapter,wewill:
ExaminethefundamentalsofMACIntroducesomeindustrydriversforSELinuxDiscusslabels,users,roles,andtypesExploretheimplementationoftangiblepolicytoallowandconstrainobjectinteraction
IdealMACsystemsmaintainthepropertyofprovidingdefinitiveaccesscontrolsonkernelresources,suchasfiles,irrespectiveofanobject’sowner.Forinstance,withaMACsystem,theownerofanobjectmightnothavefullcontrolofitspermissions.InLinux,theMACframeworkworksorthogonallytothecurrentDACcontrols.ThismeansthattheMACcontrolsdonotinterferewiththeDACcontrols.Inotherwords,toavoidpotentialconflictsbetweentheMACandDACsystems,thekernelvalidatesaccessusingtheDACpermissionsbeforecheckingtheMACpermissions.IftheDACpermissionsresultinapermissionsviolation,thentheMACpermissionsareneverchecked.ThekernelwillvalidateaccessagainsttheMACpermissionsprovideronlywhentheDACpermissionspass.FailureateitherlevelwillresultinareturnofEACCESS.IftheDACandtheMACpermissionspass,thenthekernelresource(forexample,afiledescriptor)issentbacktouserspace.
InLinux,aframeworkcalledtheLinuxSecurityModule(LSM)frameworkwasmergedduringtheLinux2.6.xseriesofkernels.ThisframeworkallowsyoutoenablethemandatoryaccesscontrolsystemsinabuildtimeselectionbytetheringtheLSMhookstothesecurityprovider.SecurityEnhancedLinux(SELinux)isthefirstconsumerofthisMACsecurityframeworkwithinthekernelandisanimplementationofamandatoryaccesscontrolsystem.SELinuxshipsinawidevarietyofLinuxsystems,suchasRedHatEnterpriseLinux(RHEL)andconsequentlyFedora.Recently,ithasbegunshippingwithAndroid.ThesourcecodeforSELinuxcanbefoundintheLinuxsourcecodetreeunderkernel/security/selinuxforthosewishingtoreviewit.
www.it-ebooks.info
GettingbacktothebasicsSELinuxisareimplementationofadesignengineeredbytheU.S.governmentandTheUniversityofUtahknownastheFLUXAdvancedSecurityKernel(FLASK).TheSELinuxandFLASKarchitectureprovideacentralpolicyfileutilizedwhiledeterminingtheresultsofaccesscontroldecisions.Thiscentralpolicyisinawhitelistform.Thismeansthatallaccesscontrolrulesmustbedefinedexplicitlybythepolicyfile.Thispolicyfileisabstractedandservedbyasoftwarecomponentcalledasecurityserver.WhentheLinuxkernelneedstomakeanaccesscontroldecisionandSELinuxisenabled,thekernelinteractswiththesecurityserverbymeansoftheLSMhooks.
Inarunningsystem,aprocessistheactiveentitythatgetstimeontheCPUtoperformtasks.Theusermerelyinvokestheseprocessestodotheworkontheirbehalf.Thisisanimportantconcept.Aswetypethisbook,wetrustthatthewordprocessorsrunningonourmachineswithourcredentialsaren’topeningourSSHkeysandembeddingtheminthedocumentmetadata.Rightnow,theprocessisincontrolofthecomputingresources,nottheuser.Theprocessistherunningentity,itistheprocessthatmakessystemcallstothekernelforresources,notthephysicalhumanbeing.Withthisinmind,theveryfirstactorinthisSELinuxsystemistheprocess,typicallyreferredtoasthesubject.Itisthesubjectthataccessesfiles.Itisthesubjectthatthesecurityserverwillusetomakeaccessdecisionson.
Consequently,thesubjectutilizeskernelresources.Thiskindofkernelresourceisanexampleofatarget.Thesubjectperformsactionsonthetarget.Naturally,oneshouldask,“Whatactionsdoesasubjectperform?”Theseareknownasaccessvectorsandtypicallycorrelatetothenameofthesyscallperformed.Forexample,thesubjectcouldperformanopenonthetarget.Itisimportanttonotethattargetscouldbeprocessesaswell.Forinstance,ifthesystemcallisptrace,thesubjectcouldbesomethingalongthelinesofadebugger,andthetargetwouldbetheprocessyouwishtodebug.Asubjectisfrequentlyaprocess,butatargetcouldbeaprocess,socket,file,orsomethingelse.
www.it-ebooks.info
LabelsSELinuxprovidessemanticsfordescribingpoliciesrelatedtothetargetsandsubjectsusinglabels.Labelsarethemetadataassociatedwithanobjectthatmaintainsthesubject’sandtarget’saccessinformation.Thedataassociatedwiththisobjectisastring.Returningtothedebuggerexample,thegdbprocessmighthaveasubjectlabelstringofdebugger,andthetargetmighthavealabelofdebugee.Theninthesecuritypolicy,somesemanticcouldbeusedtoexpressthatprocesseswiththesubjectlabeldebuggerareallowedtodebugapplicationswithtargetlabeldebugee.
Fortunately,andperhapsunfortunately,SELinuxdoesnotusesuchsimplelabels.Infact,thelabelsaremadeupoffourcolon-delimitedfields:user,role,type,andlevel.Thisadditionalcomplexityaffordsveryflexiblecontroloptions.
www.it-ebooks.info
UsersTheveryfirstfieldinalabelidentifiestheuser.Theuserfieldisusedaspartofthedesignforuser-basedaccesscontrols(UBAC).However,thisisnottypicallyassociatedwithhumanusersasitiswiththeconceptofusersinDAC.SELinuxuserstypicallydefineagroupoftraditionalusers.AcommonexampleistoidentifyallnormalusersastheSELinuxuser,user_u.Perhapsaseparateuserforsystemprocesses,suchassystem_u.ByconventioninthedesktopSELinuxcommunity,userportionsofthestringaresuffixedwitha_u.
www.it-ebooks.info
RolesThesecondfieldinalabelisrole.Theroleisusedaspartofthedesignforrole-basedaccesscontrols(RBAC).Rolesareusedtoprovideadditionalgranularitytotheuser.Forinstance,supposewehavetheuserfield,sysadm_u,reservedforadministrators.Theadministratormightbeinseparatetasks,anddependingonthetasks,therole(andtherefore,privileges)ofusersinsysadm_umaychange.Forexample,whenanadministratorneedstomountandunmountfilesystems,therolefieldmightchangetomount_admin_r.Whenanadministratorissettingtheiptablesrules,therolemightchangetonet_admin_r.Rolesallowtheisolationofprivilegeswithinthescopeofthetasksbeingperformed.
www.it-ebooks.info
TypesTypeisthethirdfieldofthecolon-delimitedlabel.Thetypefieldisevaluatedduringthetypeenforcement(TE)portionofSELinux’saccesscontrolmodel.TEisthemajorcomponentthatdrivesSELinux’ssecuritycapabilities,anditisatthispointwherethepolicystartstotakeeffect.
SELinuxisbasedonawhitelistsystemwhereeverythingisdeniedbydefaultandrequiresexplicitapprovalfromthepolicyforaninteractiontooccur.Thisapprovalisinitiallydeterminedfromthepolicyviaanallowrulethatreferencesboththesubject’sandtarget’stype.SELinuxtypescanalsobeassignedattributes.Attributesallowyoutogivenumeroustypesacommonsetofrules.Attributescanhelpminimizetheamountoftypes,andcanbeusedinfashionsimilartothatofaninheritancemodel.
www.it-ebooks.info
AccessvectorsDataisaccessedbyprocessesviasystemcallsandpossibleuserdefinedaccessmethods.Theuserdefinedaccessmethodsareusuallycontrolledviaauserspaceobjectmanager.Theseaccesspaths,alsoknownasvectors,makeupasetofactionsthatcanbeappliedtotheobject.Forinstance,ifaprocessopensafile,writessomedataintothefile,andthenreadsitback,theaccessvectorsexercisedwouldbeopen,read,andwrite.Ifaprocessdebugsanotherprocess,theaccessvectorwouldbeptrace.
www.it-ebooks.info
MultilevelsecuritySELinuxalsosupportsamultilevelsecurity(MLS)model,whichpayshomagetotheBell-LaPadula(BLP)model,butalternatemodelscouldbeused.TheBLPmodelwascreatedtoformalizetheDepartmentofDefense’ssecuritypolicies.Forexample,apersonwithasecretclearanceshouldnotbeabletoreadtop-secretmaterial.However,let’ssupposethispersonhasabrilliantideathatultimatelyneedstobeprotectedatthetop-secretlevel;thatdatacouldthenbe“up-classified”totop-secret.Thisisreferredtoas“noreaduporwritedown”.
TheSELinuximplementationofthisfieldhassubfields.Thefirstfieldissensitivity,andwillalwaysbepresent.Inthecontextofthepreviousexample,pertinentsensitivitiesincludesecretandtopsecret.Thesecondsubfieldiscategory,andmightnotbepresent.Thesefieldsalsomakesenseinthecontextofgovernmentclassification.Thedataitselfmightbecompartmentalized,sowhilethesensitivityisthesame,suchastopsecret,thedatashouldonlybedisseminatedtopeoplewithinthesamecompartmentorcategory.Sensitivitiesaredefinedinahierarchicalfashionviathedominancekeyword.Inatypicalpolicy,s0isthelowestsensitivityandsNwheren>0isthehighest.Thus,s1hasagreatersensitivitythans0.Categoriesaresets.Thecontrolsassociatedwiththelevel,whichiscomprisedofsensitivitiesandpotentiallycategories,followsettheoryconcepts,suchasdominanceandequality.InMLSsecurity,allinteractionsareallowedbydefault,unliketypeenforcement.Boththesensitivityandthecategorycanberanged,andcategoriescanbeenumerated.Thus,alabelmighthavesomenumberofsensitivitiesanddifferentnumberofcategories.
www.it-ebooks.info
PuttingittogetherSELinuxlabelsarequiteflexibleandsometimescomplex.It’softenbeneficialtostartwithacontrivedexamplethatfocusesontypeenforcement.Later,wecanaddadditionalfieldslaterastheneedforfinergranularitybecomesmoreapparent.Conveniently,youcanprojectthismodeltoscenariosineverydaylifetoprovidesomesenseoftangibilitytothematerial.DanWalsh,aprominentSELinuxfigure,postedablogpostusingpetsasananalogy.Let’scontinueonwiththatpremise,butwewillmakesomemodificationsaswegoanddefineourownexamples.It’sbesttostartwithsimpletypeenforcementasitistheeasiesttounderstand.
NoteYoucanreadDanWalsh’soriginalblogpostintroducingthepetanalogyathttp://opensource.com/business/13/11/selinux-policy-guide.
Supposeweownacatandadog.Wedon’twantthecattoeatdogfood.Wedon’twantthedogtoeatcatfood.Atthispoint,wehavealreadyidentifiedtwosubjects,acatandadog,andtwotargets,catfoodanddogfood.Wealsohaveidentifiedanaccessvector,eating.Wecanuseallowrulestoimplementourpolicy.Possiblerulescouldlooklikethis:
allowcatcat_chow:foodeat;
allowdogdog_chow:foodeat;
Let’susethisexampletostartanddefineabasicsyntaxforexpressingtheaccesscontrolswewouldliketoenforce.Thefirsttokenisallow,statingwewishtoallowaninteractionbetweenasubjectandatarget.Thedogisassignedthetype,dog,andthecat,cat.Thecatfoodisassignedthetypecat_chow,andthedogfood,dog_chow.Theaccessvectorinthiscaseiseat.Withthisbasicsyntax,whichisalsovalidSELinuxsyntax,werestricttheanimalstothefoodtheyshouldeat.Noticethe:foodannotationafterthetype.Thisistheclassfieldofthetargetobject.Forinstance,theremightalsobedog_chowtreatandcat_chowclassesthatcouldindicateourdesiretoallowaccesstotreatsinafashionthatispotentiallydifferentfromthewayweallowaccesstofoodsthatarenottreats.
Let’ssaywegettwomoredogs,andourscenariohasthreedogs.Thedogsareofdifferentsizes:small,medium,andlarge.Wewanttomakesurenoneofthesenewdogseatothers’food.Wecoulddosomethinglikecreateanewtypeforeachofthedogsandpreventdogsfromeatingthefoodofotherdogs.Itwouldlooksomethinglikethis:
allowcatcat_chow:foodeat;
allowdog_smalldog_small_chow:foodeat;
allowdog_mediumdog_medium_chow:foodeat;
allowdog_largedog_largechow:foodeat;
Thiswouldwork;however,thetotalnumberoftypeswouldbedifficulttomanage,andthatwouldcontinuetogrowifweallowthelargedogtoeatthesmallerbreeds’food.WhatwecoulddoisuseMLSsupporttoassignasensitivitytoeachtargetordogfoodbowl.Let’sassumethefollowing:
Thecat’sfoodbowlhassensitivity,tiny
www.it-ebooks.info
Thesmalldog’sfoodbowlhassensitivity,smallThemedium-sizeddog’sfoodbowlhassensitivity,mediumThelargedog’sfoodbowlhassensitivity,large
Wealsoneedtomakesurethatthesubjectsarelabeledwiththepropersensitivityaswell:
Thecatshouldhavesensitivity,tinyThesmalldogshouldhavesensitivity,smallThemedium-sizeddogshouldhavesensitivity,mediumThelargedogshouldhavesensitivity,large
Atthispoint,weneedtointroduceadditionalsyntaxtoallowtheinteractions,sincebydefault,MLSallowseverythingandTEdenieseverything.We’llusemlsconstrain,torestrictinteractionswithinthesystem.Therulecouldlooklikethis:
mlsconstrainfoodeat(l1eql2);
Thisconstraintonlyallowssubjectstoeatfoodwiththesamesensitivitylevel.SELinuxdefinesthekeywordsl1andl2.Thel1keywordisthelevelofthetargetandl2isthelevelofthesource.Becausetherulesarepartofawhitelist,thisalsopreventssubjectsfromeatingfoodthatdoesnothavetheequivalentsensitivitylevel.
Now,let’ssaywegetyetanotherlargedog.Nowwehavetwolargebreeddogs.However,theyhavedifferentdietsandneedtoaccessdifferentfoods.Wecouldaddanewtypeormodifyanexistingtype,butthiswouldhavethesamelimitationsthatledustousesensitivitiestopreventaccess.Wecouldaddanothersensitivity,butitmightgetconfusingthattherearelarge1andlarge2sensitivities.Atthispoint,categorieswouldallowustogetabitmoregranularinourcontrols.Supposeweaddacategorydenotingthebreed.OurMLSportionofourlabelwouldlooksomethinglikethis:
large:golden_retriever
large:black_lab
Thesecouldbeusedtopreventtheblacklabfromeatingthegoldenretriever’sfood.Nowsupposeyou’resurprisedwithanotherdog,aSaintBernard.Let’ssaythisnewBernardcaneatanylargedog’sfood,buttheotherlargedogscan’teathisfood.Wecouldlabelthefoodbowlsandthedogs.
DogBreed Subjectlabel Targetlabel
GoldenRetriever Dog:large:golden_retriver dog_chow:large:golden_retriver
BlackLab Dog:large:black_lab dog_chow:large:black_lab
SaintBernard Dog:large:saint_bernard,black_lab,golden_retriever dog_chow:large:saint_bernard
Cat Cat:tiny cat_chow:tiny
Theexistingmlsconstraintneedsmodification.IftheSaintBernardranoutoffoodandwenttotheBlackLab’sdish,theSaintBernardwouldnotbeabletoeatfromitsincethelevelsarenotequal(Dog:large:saint_bernard,black_lab,golden_retrieverisnot
www.it-ebooks.info
thesameasdog_chow:large:black_lab).Remember,thelevelsaresets,soweneedtointroducesomenotionthatifthesubjectssetdominatesthetargetset,thatinteractionshouldbeallowed.
Thiscouldbeaccomplishedwiththedomkeyword:
mlsconstrainfoodeat(l1doml2);
Thedominatekeyword,dom,differsfromequality,indicatingl1isasupersetofl2Inotherwords,thelevelsassociatedwiththetarget,l2,areamongthepotentiallylargersetoflevelsassociatedwiththesubject,l1.Atthispoint,weareabletokeepallthefoodseparatedandusedhoweverweseefit.
Aftergettingallthesedogs,yourealizeit’stimetofeedthem,soyougetabagofdogfoodandputsomeineachbowl.However,beforeyoucanadddogfoodtothebowls,weneedsomeallowrulesandlabelsthatwillletyou.Remember,SELinuxisawhitelist-basedsystem,andeverythingmustbeexplicitlyallowed.
Wewilllabelthehumanwiththehumanlabelanddefinesomerules.Ohyeah…don’tforgettofeedthecat,aswell:
allowhumandog_chow:foodput;
allowhumancat_chow:foodput;
Wewillalsoneedtolabelhumanwithallthesensitivitiesandcategories,butthiswouldbecomecumbersomewhenweneedtoaddadditionaldogs,breeds,andbreedsizestooursystem.Wecouldjustbypasstheconstraintifthetypeishuman.Withthisapproach,wealwaystrusthumantoputthecorrectfoodintheappropriatebowl:
mlsconstrainfoodeat(l1doml2);
mlsconstrainfoodput(t1==human);
NotetheadditionofputintheaccessvectorsoftheMLSconstraint.Viola!Thehumancannowfeedhisever-growingpackofanimals.
Soyourbirthdayrollsaround,andyoureceiveanautomaticdogfeederasapresent.Youlabelthefooddispenser,dispenserandmodifytheMLSconstraints:
mlsconstrainfoodeat(l1doml2);
mlsconstrainfoodput(t1==humanort1==dispenser);
Again,weseeaneedtocondensethenumberoftypesandgetorganizedtopreventhavingtoduplicatelines.Thisiswhereattributesarequitehandy.Wecanassignanattributetoourhumananddispensertypesbyfirstdefiningtheattribute:
attributefeeder;
Thenwecanaddittothetype:
typeattributehuman,feeder;
typeattributedispenser,feeder;
Thiscouldalsobedoneattypedeclaration:
typehuman,feeder;
www.it-ebooks.info
typedispenser,feeder;
Atthispoint,wecouldmodifytheMLSstatementstolooklikethis:
mlsconstrainfoodeat(l1doml2);
mlsconstrainfoodput(t1==feeder);
Nowlet’ssupposeyouhireamaidservice.Youwanttoensureanyonesentbythemaidserviceisabletofeedyourpets.Forthatmatter,let’sletyourfamilymembersfeedthem,aswell.Thiswouldbeagoodusecasefortheusercapabilities.Wewilldefinethefollowingusers:adults_u,kids_u,andmaid_u.Thenwe’llneedtoaddaconstraintstatementtoallowinteractionsbytheseusers:
mlsconstrainfoodput(u1==adults_uoru1==maid_u);
Thiswouldpreventthekidsfromfeedingthedogs,butletthemaidsandadultsfeedthem.Nowsupposeyouhireagardener.Youcouldcreateyetanotheruser,gardener_u,oryoucouldcollapsetheusersintoafewclassesanduseroles.Let’ssupposewecollapsegardener_uandmaid_uintostaff_u.Thereisnoreasonthegardenershouldbefeedingthedog,sowecoulduserole-basedtransitionstomovethestaffbetweentheirduties.Forinstance,supposestaffcanperformmorethanoneservice,thatis,thesamepersonmightgardenandclean.Inthiscase,theymighttakeontheroleofgardener_rormaid_r.WecouldusetherolecapabilityofSELinuxtomeetthisneed:
mlsconstrainfoodput(u1==adults_uor(u1==staff_uandr1==
animal_care_r);
Staffmayonlyfeedthedogswhenthey’reintheanimal_care_rrole.Howtogetintoandbackoutofthatroleisreallytheonlycomponentmissing.Youneedtohaveawell-definedsystemforhowthestaffcanmoveintotheanimalcareroleandtransitionbackout.ThesetransitionsinSELinuxoccureitherautomaticallyviadynamicroletransitionsorviasourcecodemodifications.We’llassumethatanyhumanentity(gardener,adults,kids)allstartinthehuman_rrole.
Dynamicroletransitionsworkwithatwo-partrule,thefirstpartallowsthetransitiontooccurviaanallowrule:
allowhuman_ranimal_care_r;
Theroletransitionstatementsareasfollows:
role_transitionhuman_rdog_chowanimal_care_r;
role_transitionhuman_rcat_chowanimal_care_r;
Thiswouldbeagoodcasetoattributethedog_chowandcat_chowtypestoanewattribute,animal_chow,andrewritetheprecedingroletransitionsto:
typeattributedog_chow,animal_chow;
typeattributecat_chow,animal_chow;
role_transitionhuman_ranimal_chowanimal_care_r;
Withtheseroletransitions,youcanonlygofromthehuman_rroletoanimal_care_r.Youwouldneedtodefinetransitionstogetbackaswell.It’salsoimportanttonotethatyou
www.it-ebooks.info
mightdefineotherroles.Supposeyoudefinetherolegardener_r,andwhensomeoneisinthatrole,theycannottransitiontoanimal_care_r.Supposeyourjustificationforthispolicyisthatgardenersmightworkwithchemicalsunsafeforpets,sotheywouldneedtowashtheirhandsbeforefeedingpets.Insuchasituation,theyshouldonlybeabletotransitiontoanimal_care_rfromthehand_wash_rrole.
www.it-ebooks.info
ComplexitiesandbestpracticesAsyoucannowappreciate,SELinuxiscomplex,andcanbethoughtofasageneralpurpose“metaprogrammingpolicylanguage”.You’reliterallyprogrammingwhatinteractionsareallowedtooccurinaverycomplexOSsuchasLinux,wheretheinteractionsthemselvesareoftencomplex.Justlikeaprogramminglanguage,youcandothingswithdifferentstylesandmethodsthatwillyielddifferingresults.Perhapsusingaswitch()inthatprogramwillmakeitcleanerandeasiertounderstandratherthananelse-ifblock,eventhoughfunctionallyyouwillendupwiththesamething.SELinuxisthesame;youcanoftenaccomplishthingswithoneportionoftheenforcementmechanismsthatwouldbemoreappropriatelyaccomplishedusinganalternatemechanism.Inlaterchapters,wewillcovertheprocessoflabelingthetargetandsubject,oneofthemoredifficultpartsofthesystem.
Whensomeoneauthorsaprogram,theyoftenhaveasetofrequirementsinplacethatthesoftwareshouldperform.Thesearetherequirementsofthesoftware.InSELinux,youshoulddothesamething.Youshouldgatherthesecurityrequirementsandunderstandthethreatmodelsyouwishtoprotectyourselffrom.AwelldesignedSELinuxpolicywouldmeetthesegoals.Agreatdesignwoulddoitinawaythatiseasytoextend.That’sultimatelywherecarefulandjudicioususeofthecombinationofUBAC,RBAC,TE,andMLSwillhelpachievetherequirementsanddesigngoals.
www.it-ebooks.info
SummaryInthischapter,wecoveredthemajorworkingportionsofSELinuxthatincludetypeenforcement,multilevelandmulticategorysecurity,aswellasusersandroles.Additionally,wesawhowtoapplythesetechnologiestoimplementincreasinglycomplexaccesspoliciestoatangibleexample.Inthenextchapter,wewillmoveoutsideofthekernelanddiscoverhowAndroidworksinitsveryuniqueuserspace.
www.it-ebooks.info
Chapter3.AndroidIsWeirdItreallyis.AlthoughitisbuiltonthefamiliarLinuxkernel,Androidhasacompletelycustomuserspace,andwhilemanyofitsfunctionalitiesarerewritesoftheirGNUcousins,someareeitherneworhavesignificantlydifferentfunctionsthantheirdesktopcounterparts.Becauseofthesedifferences,thesesystemshadtobemodifiedtosupportSELinux.Inthischapter,wewill:
IntroducetheAndroidsecuritymodelInvestigatebinder,zygote,andthepropertyserviceCoverwhichSELinuxelementswereaddedtocomplementthesesystemsandwhy
Thecoverageofthesesystemswillbemoderate,butwewillpresentmoreintricatedetailsofeachsystemlater,whenappropriate,inourexploratoryinvestigationofSEforAndroid.
www.it-ebooks.info
Android’ssecuritymodelAndroid’scoresecuritymodelisbasedonLinuxDAC,includingcapabilities.Android,however,usestheLinuxconceptofUID/GIDinaverynon-traditionalway.EachprocessonthesystemhasitsownUIDratherthantheUIDofwhoeverlaunchedit.TheseUIDs(generallyunique)providesandboxingandprocessisolation.Thereareafewcircumstances,though,whereprocessescanshareUIDsandGIDs.Typically,whenaprocesssharesaUIDwithanotherprocess,itisbecausetheybothneedthesamesetofpermissionsonthesystemandsharedata.ThesamecouldbepossibleforGIDs.However,someGIDsinAndroidareactuallyusedtogainpermissiontoaccessunderlyingsystems,suchastheSDcardfilesystem.Inanutshell,theUIDisusedtoisolateprocessesandnotthehumanusersofthesystem.Infact,Androiddidn’thavesupportformultiplehumanusersuntilitsJellyBean4.3release.Itwasalwaysintendedfordeviceswithasinglehumanuser…atleastinoperation.
Withinthissecuritymodel,therearetwoprocessclasses.Thefirstiscalledsystemcomponentservices.Thesearetheservicesdeclaredinthesysteminitscripts.TheytendtobehighlyprivilegedandthusalmostnevershareaUIDwithanotherprocess.AnexamplesystemcomponentservicewouldbetheRadioInterfaceLayerDaemon(RILD).RILDisresponsibleforprocessingmessagesbetweenAndroiduserspaceandthemodemonthedevice.Becauseofthenatureofwhatitdoes,ittypicallyrunsasUIDroot.Thereisnorequirementthatprocessesbepurenativecode.Systemserverhasnon-nativecomponents,runsasthesystemUID,andishighlyprivileged.Almostallofthesesystemsshareacommontheme;theyhaveaUIDthatiseitherrootorissettotheownerofmanysensitivekernelobjects,suchassockets,pipes,andfiles.
Thesecondclassisapplications.ApplicationsaretypicallywritteninJava,althoughthisisnotarequirement;thisissimilartohowsystemcomponentservicesaretypicallywritteninnativecodewithoutitbeingarequirement.TheseapplicationshaveUIDsassignedautomaticallywhentheyareinstalled,andtheseUIDsarereservedbythesystemforthispurpose.ThepackagemanagerisresponsibleforissuingUIDstoapplications.TheseUIDshavenotiestoanythingsensitiveordangerousonthesystem,andtheapplicationsrunwithnocapabilities.Inordertoaccessasystemresource,anapplicationmusthaveitssupplementarygroupappendedtooritmustbearbitratedbyaseparateprocess.
AsimpleexampleofutilizingthesupplementarygroupisseenwhenanapplicationneedstousetheSDcard.ForapplicationstoaccesstheSDcard,theymusthaveSDCARD_RWintheirsupplementaryGIDs.ThesepermissionsareenforcedwithstandardLinuxDACpermissionsbythekernel.Thesupplementarygroupisassignedbythepackagemanagerduringtheapplication’sinstallationbasedonadeclaredpermission.ApplicationsinAndroidmustdeclaresomethingcalleduses-permissionintheapplication’smanifest.ThispermissionappearsasastringwhichismappedtoasupplementaryGID.Thismappingismaintainedinafileinthesystem,specifically/system/etc/permissions/platform.xml.Youwillseeanapplicationofthesepermissionstringsinalaterchapter.
www.it-ebooks.info
Thesecondwayanapplicationgainsaccesstoasystemresourceisthroughanotherprocess.Theapplicationwishingtouseasystemresourcemustgetanotherprocesstodothisonitsbehalf.Mostrequestsarehandledbyaprocessknownasthesystemserver.Thesystemservercheckswhethertheapplicationmakingthearbitrationrequesthaddeclaredamatchingpermissionstringinitsmanifestfile.Ifitdid,it’sallowedtoproceed,otherwiseasecurityexceptionisthrown.EvenarbitratedaccessesinAndroiduseaDACmodel,inessence.Whiletheobjectownercontrolstheaccessrulesontheobjectviapermissionstrings,anyconsumeroftheprotectedobjectcanjustrequestthepermissionstringtogetaccess.Essentially,anyonecanwriteanapplicationrequestinganypermissionstringstheywant.Whileinstallinganapplication,theuserispresentedwiththelistofpermissionsrequestedbytheapplication,whichtheychoosetoacceptorrejectenmasse.Iftheuser’sintentistoinstalltheapplication,allrequestedpermissionsmustbegranted.Iftheuserisnotcareful,theymightinadvertentlyallowthatapplicationtoaccessprotectedobjectsinawaythatcanthreatenthesecurityofthedevice,applications,oruserdata.Theownersofthedevicesshouldalwaysensuretheyarecomfortablewiththeapplicationusingthedeclaredpermissions.
NoteForexamplesorfurtherdiscussion,refertohttp://developer.android.com/guide/topics/security/permissions.html.
www.it-ebooks.info
BinderThearbitratedaccessmethoddiscussedbeforerequiressomeformofInterprocessCommunication(IPC),andwhileAndroiddoesuseUnixdomainsockets,italsobringsitsownIPCmechanismthatisusedmorewidelythroughoutthesystem.ThisIPCmechanismiscalledbinderandisthecoreIPCmechanismintheAndroidoperatingsystem.IthashistoricalrelevancefromtheBeOSandPalmOSimplementationsofOpenBinder,andsincetheinitialAndroiddevelopmentteamwascomprisedofmanyOpenBinderengineers,binderwentwiththemtoAndroid.However,Androidhasacomplete,fromscratchrewriteofthebindercodebasethatisspecifictoLinux.
NoteBinderiscurrentlynotcompletelymainstreamedintotheLinuxkernel,andmanyofAndroid’skernelchangesarestillstaged.
Thereissomecontroversyaroundbinderanditsmainlineadoption.Somepeopleargueagainsttheamountofheavyliftingitdoeswithinthedriverincontrasttocompetingimplementationssuchasdbus.However,itwilllikelybealongtimebeforeweseetheresolutionofthisdebate.RegardlessofwhetherbinderstaysanAndroid-specifictechnology,ismainstreamedintheLinuxkernel,oriseventuallyreplacedbyanothertechnologyinAndroid,binderisheretostayfortheforeseeablefuture.
www.it-ebooks.info
Binder’sarchitectureBinderIPCfollowsaclient/serverarchitecture.Aservicepublishesaninterfaceandclientsconsumefromthatinterface.Clientscanbindtoservicesviaoneofthetwomethods:knownaddressorservicename.
Eachbinderinterfaceinthesystemisknownasabindernode.Eachbindernodehasanaddress.Whenclientswanttouseaninterface,theymustbindtoabindernodeviathisaddress.ThisisanalogoustobrowsingawebpageviaitsIPaddress.However,unlikeanIPaddressthatisusuallyfixedforlongdurationsoftime,thebinderaddresscouldchangebasedonrestartsofthepublishingserviceorontheservicestartuporderattheboottimeofthedevice.Theorderofprocessesisn’tquiteguaranteed,thusthepublishingofprocessservicescanresultinadifferentbindertoken(asimplebinderobjecttoshareamongprocesses)beingassigned.Also,thisindirectionallowstheruntimeabilitytoreseatserviceimplementationsusingjustthepublishedservicenameswithoutthenecessitytoutilizethetoken.
ThewaythisredirectionfunctionsissimilartohowDNSprovidestheresolutionfromnametoIPaddressfornetworkeddeviceaccesses.Binderhassomethingcalledthecontextmanager(alsoknownastheservicemanager).Thecontextmanagerlivesatafixednodeaddressof0.Publishingservicessendanameandabindertokentothecontextmanager,andthen,whenclientsneedtofindaservicebyname,theycheckbindernode0andresolvethenametothebindertoken.Abindertokenisthepropernameforthisaddress,orID,thatuniquelyaddressesabinderinterface.Afteraclientbindstothebinderobject,whichisaprocessthatimplementsthebinderinterface,theprocessesthenperformbindertransactionsusingawell-establishedbinderprotocol.Thisprotocolallowssynchronoustransactionsanalogtoamethodcall.
Sincebinderisakerneldriver,ithassomenicefeaturesthatdeterminewhatonecandoacrosstheinterface.Forstarters,itallowsthetransmissionoffiledescriptors.Italsomanagesathreadpoolfordispatchingservicemethods.Additionally,itemploysanapproachreferredtoaszerocopywherebybinderdoesnotcopyanyofthetransactiondatabetweenprocesses…itsharestheminstead.Binderalsoaffordsreferencecountingofobjectsandletsservicesquerytheclientapplication’sLinuxcredentialslikeUID,GID,andProcessID(PID).Binderalsoallowstheserviceandclienttoknowwhentheotherhasterminatedviaitslinktodeathfunctionality.
TypicallyinAndroid,youdon’tworkwithbinderdirectly.Instead,youworkwithaserviceratherviaaserviceanditsAndroidInterfaceDescriptionLanguage(AIDL)interface.ThefinalchapterwillprovidedetailedexamplesofAIDLinpracticeforourcustomSEforAndroidsystem,butinthemeantime,thefollowingisasimpleexampleofanAIDLinterfaceprovidingthemeansforremoteprocessestoexecutethegetAccountName()andputAccountName()functions:
packagecom.example.sample;
interfaceIRemoteInterface{
StringgetAccountName();
www.it-ebooks.info
booleanputAccountName(inStringname);
}
ThebeautyinworkingwithanAIDLinterfaceisthatitisusedtogenerateasignificantamountofcodetomanagedataandprocessesthatwouldotherwisehavetobedonebyhand.Forexample,thefollowingisonlyasmallportionofthecodegeneratedfromtheprecedingAIDLsample:
@OverridepublicbooleanonTransact(intcode,android.os.Parceldata,
android.os.Parcelreply,intflags)throwsandroid.os.RemoteException
{
switch(code)
{
caseINTERFACE_TRANSACTION:
{
reply.writeString(DESCRIPTOR);
returntrue;
}
caseTRANSACTION_getAccountName:
{
data.enforceInterface(DESCRIPTOR);
java.lang.String_result=this.getAccountName();
reply.writeNoException();
reply.writeString(_result);
returntrue;
}
caseTRANSACTION_putAccountName:
{
data.enforceInterface(DESCRIPTOR);
java.lang.String_arg0;
_arg0=data.readString();
...
www.it-ebooks.info
BinderandsecurityThesecurityimplicationsofbinderarequitelarge.Youshouldbeabletocontrolwhobecomesthecontextmanager,asaroguecontextmanagercouldcompromisethewholesystembysendingclientstorogueservices,ratherthantheproperones.Outsideofthat,youmightwanttocontrolwhichclientscanbindtowhichbinderobjects.Lastly,youmightwishtocontrolwhetherfiledescriptorscanbesentviabinder.Thebinderalsohasthecapabilitytoallowsomeonetofakecredentialsovertheinterface,whichisdesignedtobeusedforgood.Forexample,someprivilegedsystemprocesses,suchasActivityManagerService(AMS),performoperationsonbehalfofotherprocesses.Thecredentialsexposedinthiskindofmasqueradingareoftheprocessyouaredoingtheworkfor,notoftheprivilegedentity.Thisisanalogoustoapowerofattorney,usedwhensomeoneisactingonyourbehalf.
Android’sbinderIPCmechanismwastraditionallycontrolledwithDACpermissions.However,aswesawinChapter1,LinuxAccessControls,thesepermissionshavesomeflaws.ItfollowsthatbinderneedstobemodifiedtosupportSELinuxbecausethebinderdriverdoesnototherwiseimplementhookstoanyadditionalsecuritymodules.Todothis,apatchwassenttoGooglebyStephenSmalleyimplementingthesefeatures.ThepatchimplementsnewhooksforconsumersofwhatisknownastheLinuxSecurityModule(LSM)framework.ThisframeworkallowsLSMssuchasSELinuxtobeinvokedandthenmakeaccessdecisions.Thedetailsofthispatchareoutsidethescopeofthisbook.Itsufficesthatbinderwaspatched,andSELinuxcannowcontrolitscapabilitieswithMAC.
NoteStephenSmalleyisacomputersecurityresearcherattheTrustedSystemsResearchorganizationoftheUnitedStatesNationalSecurityAgency(NSA)andleadstheSEAndroidproject.ThepatchhesenttoGoogletomodifythebinderforSELinuxhookscanbeviewedathttps://android-review.googlesource.com/45984.
BecauseoftheintegrationofSELinuxandbinder,SEforAndroidhasanadditionalclasswithaccessvectors(afancywayofsaying,“thingsitcando.”)InpreviousexamplesfromChapter2,MandatoryAccessControlsandSELinux,thetargetclassisfood.Similarly,theSELinuxclassforbinderisbinder.Itdefinestheaccessvectorslistedinthefollowingbullets.Ifyourecall,theaccessvectorforfoodinChapter2,MandatoryAccessControlsandSELinux,waseat.Thefollowingaccessvectorsareavailableforbinder:
impersonate:Thiscreatesfakecredentialsoverabinderinterfacecall:Thisbindsaclienttoabinderinterfaceandusesitset_context_mgr:Thissetsthecontextmanagertransfer:Thistransfersafiledescriptor
www.it-ebooks.info
Zygote–applicationspawnNon-nativeapplicationsinAndroidhistoricallymakeuseoftheDalvikvirtualmachine(VM)andrunaproprietarybytecodecalledDEX.Applicationsarealsospawnedfromacommonprocesscalledzygotethroughamechanismcalledforkandspecialize.ZygoteitselfisaprocessthathastheDalvikVMandsomecommonclasses,suchasjava.util.*,loadedintotheVM.Forkandspecializeisthemechanismofgoingfromazygotetoachildprocessofzygotethatexecutessomeapplicationcode.
NoteVersionsofAndroidsinceAndroid4.4arereplacingthiswiththeAndroidRunTime(ART).ItisspeculatedthatAndroidLwillnotusetheDalvikVMatall.
Thefirstpartofthisprocessinvolvesasocketconnection.Zygotelistensoverthissocketforanapplication’sspawnrequests.Someoftheargumentsincludethepackagenameoftheapplicationthatshouldbeloadedandaflagthatindicateswhethertheapplicationisthesystemserverornot.Oncethespawncommandisreceived,theforkcanproceed.
NoteAgreatwaytostarttracingbackthisinitialsocketconnectioniswiththeapp_processtool.ThiscommandstartsaprocesswithDalvik.Formoreinformation,navigatetoframeworks/base/cmds/app_process/app_main.cpp.
Afterthefork,thenowparentzygotereturnstolistenonthesocketformorerequests.Thechildprocessisexecutingandafewthingsneedtohappen.ThefirstthingthatneedstohappenisaUIDandGIDswitch.ZygoterunswiththeUIDroot,andthustomeettheAndroidsecuritymodel,itmustsetthechildprocessUIDsandGIDstosomethingotherthanroot.ThechildprocesswillsetUIDandGIDasdefinedbythepackagemanagerandthesupplementaryGIDs.Italsosetstheprocess’resourcelimitsandschedulingpolicy.Thenitclearsthecapabilitysetoftheapplicationtozero(nocapabilities).Inthecaseofthesystemserver,thecapabilitysetisnotclearedbutrathersetasoneoftheargumentssentoverthesocket.Afterthispoint,thechildprocessruns.Codefurtheralonginthezygoteloadstheclass,andothersysteminteractions,suchasintentdelivery,areusedtostartanactivity.Thesepartsofzygotearebeyondthescopeofthisbook.
www.it-ebooks.info
ThepropertyserviceThepropertyserviceinAndroidprovidesasharedmappingofkey-valuepairsbetweenallprocesses.AllprocessesonanAndroidsystemsharesomepagesofmemorydedicatedtothissystem.However,themappinginallprocessesisREADONLYwiththeexceptionofinitprocesses,whichhaveaREAD/WRITEmapping.Thepropertyservicesystemresideswithininit,anditisthissystem’sjobtoupdateoraddvaluestothiskey-valuemap.Inordertochangeavalue,youmustgothroughpropertyservice,butanyonecanreadavalue.It’simperativethatifyouusepropertyservice,youdonotstoresensitiveinformation.Itisprimarilyintendedtobeusedforsmallvalues,notagenericlarge-valuestore.Whatfollowsisonlyaverybasicintroductiontothepropertyservice.Athoroughinvestigationwillbeconductedlater.
Tosetaproperty,youmustsendarequestusingaUnixdomainsockettothepropertyservice.Propertyservicewillthenparsetherequestandsetthevalueifthepermissionsallowittodoso.Propertieshaveperiod-delimitedsegments,likepackagenames,thathavepermissionsassignedtoitstaticallyatbuildtime.Thepermissionsandpropertyservicecodecanbefoundtogetheratsystem/core/property_service.c.Theargumentsexpectedoverthisinterfaceincludeacommand,thepropertyname,andthepropertyvalue.Forthosewhoarecurious,thesearealldefinedinthestructureprop_msg,whichisdefinedinbionic/libc/include/sys/_system_properties.h.Uponreceivingthemessage,thepropertyservicechecksthepeersocket’scredentialsagainstthestaticmapofpermissions.IftheUIDisroot,itcanwritetoanything,otherwiseitmustbeamatchforeitherUIDorGID.InverynewAndroidversions,orthosewiththepatchappliedfromhttps://android-review.googlesource.com/#/c/98428/,boththepermissioncheckingandhardcodedDAChavebeenreplacedbySELinuxcontrols.
SincethepermissiontosetavalueiscontrolledbyuserspaceusingDAC,itfollowsthatthepropertysetmechanismssharetheinherentrootingvulnerabilityflaw.Withthisinmind,thepropertyservicecodewasaugmentedinSELinux.Sincethisisauserspaceprocess,itusestheSELinuxAPIthroughthekerneltoprogramsomethingcalledauserspaceobjectmanager.ThisjustmeanstheuserspaceapplicationcheckswithSELinuxinthekerneltoensureitcanperformanactivity…inthiscase,setonaproperty.
www.it-ebooks.info
SummaryAndroidhassomeveryuniqueproperties.FromitsuseofthecommonUIDandGIDmodeltopromoteitssecuritygoals,toitscustombinderIPCmechanism,thesesystemshaveimplicationsonthesecurityandfunctionalityofthedevice.Inthenextchapter,thesesystemswillcomebackintoplayaswegettheUDOOupandrunningandenableSEforAndroidonit.
www.it-ebooks.info
Chapter4.InstallationontheUDOOInordertocontinueourexploration,wewillneedtogetatangiblesysteminplacetoworkwith.Inthischapter,wewill:
BuildAndroid4.3fortheUDOOfromsourceFlashanSDcardwithourbootimagesGettheUDOOrunningwhilecapturinglogsEstablishanadbconnectiontotheUDOORebuildthekernelwithSELinuxsupportVerifyourSELinuxUDOOimageworksasexpected
WewillstartwiththepubliclyavailableUDOOAndroid4.3JellyBeansourcecode,whichcanbedownloadedfromhttp://www.udoo.org/downloads/.ItisassumedyouhaveaUDOOandhaveverifiedthatitisfunctional.ItisrecommendedyoufollowtheinstructionsontheUDOOwebsiteforgettingstartedwiththeAndroid4.3prebuiltimageasaninitialtest(formoreinformation,refertohttp://www.udoo.org/getting-started/).
YouwillalsoneedanappropriatedevelopmentsystemforworkingwithAndroidandaUDOO,butthedetailsofthisarebeyondthescopeofthischapter.AnappendixhasbeenprovideddetailingthesetupofastandardUbuntuLinux12.04systemtoensureyouhavethehighestprobabilityofsuccessduplicatingtheworkinthisbook.
www.it-ebooks.info
RetrievingthesourceLet’sstartthisexercisebydownloadingtheAndroid4.3Jellybeansourcecodefromthedownloadlinksgivenintheprecedingsection,andextractthedownloadintoaworkspaceusingthefollowingcommands:
$mkdir~/udoo&&cd~/udoo
$tar-xavf~/Downloads/UDOO_Android_4.3_Source_v2.0.tar.gz
Oncethisisdone,youshouldreviewtheUDOOdocumentationandtheAndroidsourcecodebuildinginstructionsatthefollowingURLs:
http://www.elinux.org/UDOO_compile_android_4-2-2_from_sourceshttp://source.android.com/source/initializing.html
TheinstructionsprovidedbytheprecedingURLdiscusshowtobuildAndroidwithOpenJDK7.However,theseinstructionsareforthecurrentreleaseofAndroid(Lpreview)andarenot100percentrelevant.ForAndroid4.3,youmustbuildwithOracleJava6,whichisarchivedbyOracleandfoundathttp://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase6-419409.html.
ItisassumedthatyouhaveaduplicateofthesystemdetailedintheAppendix,TheDevelopmentEnvironment.Thatappendix,amongotherthings,walksyouthroughthesetupofOracleJava6asyouronlyJavainstance.However,forthosewhoprefertoworkfromtheirexistingsystems,particularlythosewithmultipleJavaSDKs,pleasekeepinmindyouwillneedtoensureyoursystemisusingtheOracleJava6toolswhenworkingthroughtherestofthisbook.
FinishsettingupyourenvironmentbychangingtotherootofyourUDOOsourcetreeandexecutethefollowingcommand:
$.setupudoo-eng
Oncetheenvironmentisconfigured,weneedtobuildthebootloader:
$cdbootable/bootloader/uboot-imx
$./compile.sh-c
Agraphicalmenuwillappear.Ensurethesettingsareasfollows:
DDRSize:Select1Giga,bussize64,andactiveCS\1(256Mx4)BoardType:SelectUDOOCPUtype:Selectquad-coreordual-coreoption,dependentonwhichsystemyouhave.Wehappentobeusingthequad-coresystem.OStype:SelectAndroidEnvironmentdevice:MustselectSD/MMCExtraoptions:CLEANshouldbeselectedCompileroptions:Pathstotoolchainscanbeselectedhere;justtakethedefaults
Thefollowingscreenshotshowsthegraphicalmenudisplayedbytheprecedingcommand:
www.it-ebooks.info
Whenyouexit,besuretosave.Thenstartthecompilation:
$./compile.sh
Boardtypeselected:UDOO
CPUType:QUAD/DUAL
OStype:Android
...
/home/bookuser/udoo/prebuilts/gcc/linux-x86/arm/arm-eabi-4.6/bin/arm-eabi-
objcopy-Osrecu-bootu-boot.srec
/home/bookuser/udoo/prebuilts/gcc/linux-x86/arm/arm-eabi-4.6/bin/arm-eabi-
objcopy--gap-fill=0xff-Obinaryu-bootu-boot.bin
Justtobesafe,verifyyourbuildwassuccessfulbyusinglsu-boot.bintoensurethebootloaderimagenowexists.Now,buildAndroidusingthefollowingcommand:
$croot
$make–j42>&1|teelogz
ThefirstcommandissomethingthatwassourcedinthesetupscriptsforAndroidandtakesusbacktotherootofourprojecttree.Thesecondcommand,make,buildsthesystem.YoushouldsettheoptionforjtotwiceyourCPU/corecountinmostcases.Becausemanyofyoumighthaveadual-coremachine,we’lluse–j4.Oneoftheauthorsofthisbookuses8CPUcores,forexample,andusestheflag-j16.Thefileredirectionandteecommandscapturethebuildoutputtoafile.Thisisimportanttohelpanddebuganybuildissues.Thisbuild,dependingonyoursystemcantakealong,longtime.Onthepreviouslymentioned8-coresystemwith16GBRAM,thistookalittleover35minutes.Onothersystems,we’veexperiencedbuildtimesover3hours.
Inthiscase,capturingthelogsprovedveryuseful.Thebuildterminatedwithanerror,andbysearchingthelogsforerror,wefoundthefollowing:
$greperrorlogz
...
external/mtd-utils/mkfs.ubifs/mkfs.ubifs.h:48:23:fatalerror:uuid/uuid.h:
Nosuchfileordirectory
external/mtd-utils/mkfs.ubifs/mkfs.ubifs.h:48:23:fatalerror:uuid/uuid.h:
Nosuchfileordirectory
www.it-ebooks.info
external/mtd-utils/mkfs.ubifs/mkfs.ubifs.h:48:23:fatalerror:uuid/uuid.h:
Nosuchfileordirectory
...
Byevaluatingthoseerrors,wediscoverwearemissingheadersforuuidandlzo1x.WecanalsoopentheAndroidmakefile,external/mtd-utils/mkfs.ubifs/Android.mk,anddeterminethelikelylibrariesinvolvedfromthelineLOCAL_LDLIBS:=-lz-llzo2-lm-luuid-m64.SearchingrevealsthespecificUbuntupackagewe’remissing;wewillinstallthemandbuildagain.The$characterattheendofthesearchstringensuresweonlygetresultsendinginuuid/uuid.h.Withoutit,wemightmatchfilesendingin.htmlor.hpp:
$sudoapt-filesearch-x“uuid/uuid.h$”
uuid-dev:/usr/include/uuid/uuid.h
$sudoapt-getinstalluuid-dev
$make–j42>&1|teelogz
Asuccessfulbuildshouldproducesomefinaloutputsimilartothefollowing:
...
Running:mkuserimg.shout/target/product/udoo/system
out/target/product/udoo/obj/PACKAGING/systemimage_intermediates/system.img
ext4system293601280out/target/product/udoo/root/file_contexts
Installsystemfsimage:out/target/product/udoo/system.img
out/target/product/udoo/system.img+out/target/product/udoo/obj/PACKAGING/re
covery_patch_intermediates/recovery_from_boot.pmaxsize=299747712
blocksize=4224total=294120167reserve=3028608
www.it-ebooks.info
FlashingimageonanSDcardWiththebootloader,Androiduserspace,andLinuxkernelbuilt,it’stimetoinsertanSDcardandflashtheimages.InsertanSDcardintoyourhostcomputer,andensureit’sunmounted.InUbuntu,removablemediaaremountedautomatically,soyou’llneedtofindthe/dev/sd*devicethatisyourflashdrive,andumountit.Fortheremainderofthetext,wewilluse/dev/sddastheflashdrive,butitisimportanttousethecorrectdeviceforyoursystem.IfyouhaveusedthisSDcardforinstallingUDOObefore,thecardwillcontainmultiplepartitions,soyoumightsee/dev/sdd<num>mountednumeroustimes:
$mount|grepsdd
/dev/sdd7on/media/vendertypeext4(rw,nosuid,nodev,uhelper=udisks)
/dev/sdd4on/media/datatypeext4(rw,nosuid,nodev,uhelper=udisks)
/dev/sdd5on/media/57f8f4bc-abf4-655f-bf67-946fc0f9f25btypeext4
(rw,nosuid,nodev,uhelper=udisks)
/dev/sdd6on/media/cachetypeext4(rw,nosuid,nodev,uhelper=udisks)
$sudobash-c"umount/dev/sdd4&&umount/dev/sdd5&&umount/dev/sdd6&&
umount/dev/sdd7"
OncetheSDcardisproperlyunmounted,wecanflashourimage:
$sudo-E./make_sd.sh/dev/sdd
TipYoumustusethe-EparameteronsudotopreservealltheexportedvariablesfromtheAndroidbuild.YoumustbeinthesameterminalsessionyoubuiltAndroidin.OtherwiseyouwillseetheerrorNoOUTexportvariablefound!Setupnotcalledinadvance….
Oncethiscompletes(itwilltakeawhile),it’simportanttoflushtheblockdevicecachesbacktothediskwiththecommand,sudosync.Then,youcanremovetheSDcard,insertitintotheUDOO,andboot!
www.it-ebooks.info
UDOOserialandAndroidDebugBridgeNowthattheUDOOisbootingintoAndroid,wewanttomakesurewecanaccessitusingtheserialportaswellastheAndroidDebugBridge(adb).You’llneedtheUDOOserialdriversappropriateforyoursystem.ThedetailsofthisforMac,Linux,andWindowscanbefoundat
http://www.udoo.org/ProjectsAndTutorials/connecting-via-serial-cable/.
Theserialportisthefirstformofcommunicationthatwillcomefromthesystem,anditisinitializedbythebootloader.Itisacriticallinkfordebugginganykernelorsystemissuesthatyouencounterlateron.It’salsorequiredinordertoconfiguretheUSBporttoallowadbconnectionsacrossCN3(theUSBOTGportontheUDOO).Toconfiguretheport,weneedtoconfigureanduseminicomtoconnectashelltothedevice.StartbypluggingamicroUSBcablefromCN6(themicroUSBportclosesttothepowerbutton)tothehostmachine.Next,let’sfindtheserialconnectionbylookingthroughdmesgfortheconnectionmessageofaTTYoverUSB.
$sudodmesg|tail-n5
[9019.090058]usb4-1:Manufacturer:SiliconLabs
[9019.090061]usb4-1:SerialNumber:0078AEDB
[9019.096089]cp210x4-1:1.0:cp210xconverterdetected
[9019.208023]usb4-1:resetfull-speedUSBdevicenumber4usinguhci_hcd
[9019.359172]usb4-1:cp210xconverternowattachedtottyUSB0
OurTTYterminalisonthelastline.Let’sconnectthroughitwithminicom:
$sudominicom-sw
SelectSerialPortSetup,typea,changeSerialDeviceto/dev/ttyUSB0,andtypeftotogglethehardwareflowcontroloff:
Toexit,hitEnter,selectSaveSetupandDFL,thenselectExitfromMinicom,andpress
www.it-ebooks.info
Enter.NowrunminicomtoconnecttoyourUDOO,andwatchitboot:
$sudominicom-w
Ifthedeviceisbootedandrunning,you’llgetafriendlyrootshell:
Ifit’sbooting,you’llseethelogs.Justwaitfortherootshellprompt:
www.it-ebooks.info
NowweneedtoflipsomeGPIOpinstomovetheCN3microUSBintodebugmode:
root@udoo:/#echo0>/sys/class/gpio/gpio203/value
root@udoo:/#echo0>/sys/class/gpio/gpio128/value
Then,resettheSAM3X8Eprocessorthatwasusingthatbus,byremovingandreplacingtheJ16jumper.NowpluginamicroUSBcablefromthehosttoCN3.YoushouldnowseeaUSBdeviceaswellasadb:
$lsusb
Bus001Device009:ID18d1:4e42GoogleInc.
$adbdevices
Listofdevicesattached
0123456789ABCDEFoffline
YouneedtoselectAllowUSBdebuggingwhenthepromptappearsontheUDOOAndroidside.Whenyoudothis,thedeviceshouldgofromofflinetoonline;thiswayyoucanuseadb.
Nowtesttheconnectionandgrabthescreenshotoveradb:
$adbshell
root@udoo:/#
$adbshellscreencap-p|perl-pe's/\x0D\x0A/\x0A/g'>screen.png
Thisisthescreenshot:
Atthispoint,wehaveaworkingdevelopmentsystem.Wehaveearlybootlogsandarescueshellthroughtheserialconsole.WealsohaveanadbbridgewithwhichwecanusethestandardAndroiddebuggingtools!There’snothinglefttodobutgetthissystem
www.it-ebooks.info
FlippingtheswitchNowthatweareenablingSELinuxontheUDOO,weneedtoverifyitisn’tturnedon.Thewaytodothisistochecktheknownfilesystemtypesinthe/procfilesystem.SELinuxhasitsownpsuedo-filesystem,soifit’senabled,weshouldseeitinthelist:
$adbshellcat/proc/filesystems
nodevsysfs
nodevrootfs
nodevbdev
nodevproc
nodevcgroup
nodevcpuset
nodevtmpfs
nodevdebugfs
nodevsockfs
nodevpipefs
nodevanon_inodefs
nodevrpc_pipefs
nodevdevpts
ext3
ext2
ext4
cramfs
nodevramfs
vfat
msdos
nodevnfs
nodevjffs2
nodevfuse
fuseblk
nodevfusectl
nodevmtd_inodefs
nodevubifs
ThereisnoevidenceofSELinuxhere,solet’sfindthekernelconfigurationandturniton.Executethiscommandfromthe~/udoo/kernel_imxdirectory,andeventuallyyouwillbegreetedwithagraphicaleditingscreen:
$makemenuconfig
First,youwillneedtoenableAuditingsupport,asthisisadependencyofSELinux.UnderGeneralsetup|AuditingSupport,enableAuditSupportandEnablesystem-callauditing.Usetheupanddownarrowkeystohighlightanentry,andpressthespacebartoenableit.Whenanitemisenabled,youwillseeanasterisk(*)nexttoit:
www.it-ebooks.info
GobacktothemainmenubyselectingExit…it’snotveryintuitive.EntertheFilesystemsmenu,andforeachofthethreefilesystems,Ext2,Ext3,andExt4,ensurethatExtendedattributesandSecurityLabelsareenabled.Then,gobacktothemainmenubyselectingExit:
Fromthatscreen,exitbacktothemainmenuandgotoSecurityOptions.OnceintheSecurityOptionssubmenu,enabletheEnabledifferentsecuritymodelsandSocketandNetworkingSecurityHooksoptions:
www.it-ebooks.info
Oncetheseareenabled,moreoptionswillappear.EnableNSASELinuxSupportandensuretheotherselectionsandvaluesfromthefollowingscreenshotareduplicated:
Finally,setDefaultsecuritymoduletoSELinux:
OnceyouselectDefaultsecuritymodule,anewwindowwillappearfromwhichyoucanselectSELinux.ExittheconfigurationmenusbyselectingExituntilyouareaskedtosaveyournewconfiguration:
Savethenewconfigurationandwritethesechangestotheoriginatingkernelconfigurationfile.Otherwise,itwillbeoverwrittenonsubsequentbuilds.Todothis,we’llneedtodiscoverwhichconfigurationfilewasusedinthedefaultbuild,whichwebuiltearlierbeforewemadeourownconfigurationwithmakemenuconfig:
$grepdefconfiglogzmake-Ckernel_imximx6_udoo_android_defconfig
www.it-ebooks.info
ARCH=armCROSS_COMPILE=`pwd`/prebuilts/gcc/linux-x86/arm/arm-eabi-
4.6/bin/arm-eabi-
Youcanseethatimx6_udoo_android_defconfigwasusedasthedefaultconfiguration.Copyyourcustomconfigurationandbuildagain:
$cp.configarch/arm/configs/imx6_udoo_android_defconfig
$croot
$make–j4bootimage2>&1|teelogz
AquicksanitycheckofthelogfileisalwaysagoodideatoverifySELinuxwasactuallybuiltintothekernel:
$grep-iselinuxlogz
HOSTCCscripts/selinux/mdp/mdp
HOSTCCscripts/selinux/genheaders/genheaders
GENsecurity/selinux/flask.hsecurity/selinux/av_permissions.h
CCsecurity/selinux/avc.o
...
Now,withabuiltkernelsupportingSELinux,inserttheSDcardintothehostandrunthefollowingcommands:
$sudo-E./make_sd.sh/dev/sdd
$sudosync
TipDon’tforgettoumountanyautomountedpartitionsfromtheSDcardaswedidbefore.
PlugtheSDcardintotheUDOO,andfireitup.Youshouldseelogsovertheserialconsoleaswedidbefore:
Eventually,theserialconnectionshouldtakeustoarootshell.
www.it-ebooks.info
It’saliveHowdoweknowthatwehavesuccessfullyenabledSELinuxinthekernel?Earlierinthischapter,youranthecommand,adbshellcat/proc/filesystems.We’regoingtodothesamethingandlookforanewfilesystemcalledselinuxfs.Ifthatispresent,itindicateswehaveenabledSELinuxsuccessfully.Runthefollowingcommandintheserialterminal:
#cat/proc/filesystems|grepselinux
nodevselinuxfs
Wecanseethatselinuxfsispresent!AnothercommonpracticeistocheckdmesgforanySELinuxoutput.Todothis,executethefollowingcommandviatheserialterminal:
#dmesg|grep-iselinux
<6>SELinux:Initializing.
<7>SELinux:Startinginpermissivemode
<7>SELinux:Registeringnetfilterhooks
<3>SELinux:policydbversion26doesnotmatchmyversionrange15-23
<4>SELinux:Couldnotloadpolicy:Invalidargument
www.it-ebooks.info
SummaryThiswasaveryexcitingchapter.YoulearnedhowtoenableSELinuxinthekernelconfiguration,bootthe“secured”system,andhowtoverifyitspresence.WealsolearnedhowtoflashandbuildimagesfortheUDOOingeneralandhowtoconnecttoitviaserialandadbconnections.Inthenextchapters,wewillfocusonhowtomaketheUDOOusablewithSEforAndroidcapabilities.
www.it-ebooks.info
Chapter5.BootingtheSystemNowthatwehaveanSEforAndroidsystem,weneedtoseehowwecanmakeuseofit,andgetitintoausablestate.Inthischapter,wewill:
ModifythelogleveltogainmoredetailswhiledebuggingFollowthebootprocessrelativetothepolicyloaderInvestigateSELinuxAPIsandSELinuxFSCorrectissueswiththemaximumpolicyversionnumberApplypatchestoloadandverifyanNSApolicy
YoumighthavenoticedsomedisturbingerrormessagesdmesginChapter4,InstallationontheUDOO.Torefreshyourmemory,herearesomeofthem:
#dmesg|grep–iselinux
<6>SELinux:Initializing.
<7>SELinux:Startinginpermissivemode
<7>SELinux:Registeringnetfilterhooks
<3>SELinux:policydbversion26doesnotmatchmyversionrange15-23
...
ItwouldappearthateventhoughSELinuxisenabled,wedon’tquitehaveanerror-freesystem.Atthispoint,weneedtounderstandwhatcausesthiserror,andwhatwecandotorectifyit.Attheendofthischapter,weshouldbeabletoidentifythebootprocessofanSEforAndroiddevicewithrespecttopolicyloading,andhowthatpolicyisloadedintothekernel.Wewillthenaddressthepolicyversionerror.
www.it-ebooks.info
PolicyloadAnAndroiddevicefollowsabootsequencesimilartothatofthe*NIXbootingsequence.Thebootloaderbootsthekernel,andthekernelfinallyexecutestheinitprocess.Theinitprocessisresponsibleformanagingthebootprocessofthedevicethroughinitscriptsandsomehardcodedlogicinthedaemon.Likeallprocesses,inithasanentrypointatthemainfunction.Thisiswherethefirstuserspaceprocessbegins.Thecodecanbefoundbynavigatingtosystem/core/init/init.c.
Whentheinitprocessentersmain(refertothefollowingcodeexcerpt),itprocessescmdline,mountssometmpfsfilesystemssuchas/dev,andsomepseudo-filesystemssuchasprocfs.ForSEforAndroiddevices,initwasmodifiedtoloadthepolicyintothekernelasearlyinthebootprocessaspossible.ThepolicyinanSELinuxsystemisnotbuiltintothekernel;itresidesinaseparatefile.InAndroid,theonlyfilesystemmountedinearlybootistherootfilesystem,aramdiskbuiltintoboot.img.Thepolicycanbefoundinthisrootfilesystemat/sepolicyontheUDOOortargetdevice.Atthispoint,theinitprocesscallsafunctiontoloadthepolicyfromthediskandsendsittothekernel,asfollows:
intmain(intargc,char*argv[]){
...
process_kernel_cmdline();
unionselinux_callbackcb;
cb.func_log=klog_write;
selinux_set_callback(SELINUX_CB_LOG,cb);
cb.func_audit=audit_callback;
selinux_set_callback(SELINUX_CB_AUDIT,cb);
INFO("loadingselinuxpolicy\n");
if(selinux_enabled){
if(selinux_android_load_policy()<0){
selinux_enabled=0;
INFO("SELinux:Disabledduetofailedpolicyload\n");
}else{
selinux_init_all_handles();
}
}else{
INFO("SELinux:Disabledbycommandlineoption\n");
}
…
Intheprecedingcode,youwillnoticetheverynicelogmessage,SELinux:Disabledduetofailedpolicyload,andwonderwhywedidn’tseethiswhenwerandmesgbefore.Thiscodeexecutesbeforesetlevelininit.rcisexecuted.
ThedefaultinitloglevelissetbythedefinitionofKLOG_DEFAULT_LEVELinsystem/core/include/cutils/klog.h.Ifwereallywantedto,wecouldchangethat,rebuild,andactuallyseethatmessage.
Nowthatwehaveidentifiedtheinitialpathofthepolicyload,let’sfollowitonitscourse
www.it-ebooks.info
throughthesystem.Theselinux_android_load_policy()functioncanbefoundintheAndroidforkoflibselinux,whichisintheUDOOAndroidsourcetree.Thelibrarycanbefoundatexternal/libselinux,andalloftheAndroidmodificationscanbefoundinsrc/android.c.
Thefunctionstartsbymountingapseudo-filesystemcalledSELinuxFS.Ifyourecall,thiswasoneofthenewfilesystemsmentionedin/proc/filesystemsthatwesawinChapter4,InstallationontheUDOO.Insystemsthatdonothavesysfsmounted,themountpointis/selinux;onsystemsthathavesysfsmounted,themountpointis/sys/fs/selinux.
Youcancheckmountpointsonarunningsystemusingthefollowingcommand:
#mount|grepselinuxfs
selinuxfs/sys/fs/selinuxselinuxfsrw,relatime00
SELinuxFSisanimportantfilesystemasitprovidestheinterfacebetweenthekernelanduserspaceforcontrollingandmanipulatingSELinux.Assuch,ithastobemountedforthepolicyloadtowork.Thepolicyloadusesthefilesystemtosendthepolicyfilebytestothekernel.Thishappensintheselinux_android_load_policy()function:
intselinux_android_load_policy(void)
{
char*mnt=SELINUXMNT;
intrc;
rc=mount(SELINUXFS,mnt,SELINUXFS,0,NULL);
if(rc<0){
if(errno==ENODEV){
/*SELinuxnotenabledinkernel*/
return-1;
}
if(errno==ENOENT){
/*Fallbacktolegacymountpoint.*/
mnt=OLDSELINUXMNT;
rc=mkdir(mnt,0755);
if(rc==-1&&errno!=EEXIST){
selinux_log(SELINUX_ERROR,"SELinux:Couldnotmkdir:%s\n",
strerror(errno));
return-1;
}
rc=mount(SELINUXFS,mnt,SELINUXFS,0,NULL);
}
}
if(rc<0){
selinux_log(SELINUX_ERROR,"SELinux:Couldnotmountselinuxfs:%s\n",
strerror(errno));
return-1;
}
set_selinuxmnt(mnt);
returnselinux_android_reload_policy();
}
Theset_selinuxmnt(car*mnt)functionchangesaglobalvariableinlibselinuxsothatotherroutinescanfindthelocationofthisvitalinterface.Fromthereitcallsanotherhelper
www.it-ebooks.info
function,selinux_android_reload_policy(),whichislocatedinthesamelibselinuxandroid.cfile.Itloopsthroughanarrayofpossiblepolicylocationsinpriorityorder.Thisarrayisdefinedasfollows:
Staticconstchar*constsepolicy_file[]={
"/data/security/current/sepolicy",
"/sepolicy",
0};
Sinceonlytherootfilesystemismounted,itchooses/sepolicyatthistime.Theotherpathisfordynamicruntimereloadsofpolicy.Afteracquiringavalidfiledescriptortothepolicyfile,thesystemismemorymappedintoitsaddressspace,andcallssecurity_load_policy(map,size)toloadittothekernel.Thisfunctionisdefinedinload_policy.c.Here,themapparameteristhepointertothebeginningofthepolicyfile,andthesizeparameteristhesizeofthefileinbytes:
intselinux_android_reload_policy(void)
{
intfd=-1,rc;
structstatsb;
void*map=NULL;
inti=0;
while(fd<0&&sepolicy_file[i]){
fd=open(sepolicy_file[i],O_RDONLY|O_NOFOLLOW);
i++;
}
if(fd<0){
selinux_log(SELINUX_ERROR,"SELinux:Couldnotopensepolicy:%s\n",
strerror(errno));
return-1;
}
if(fstat(fd,&sb)<0){
selinux_log(SELINUX_ERROR,"SELinux:Couldnotstat%s:%s\n",
sepolicy_file[i],strerror(errno));
close(fd);
return-1;
}
map=mmap(NULL,sb.st_size,PROT_READ,MAP_PRIVATE,fd,0);
if(map==MAP_FAILED){
selinux_log(SELINUX_ERROR,"SELinux:Couldnotmap%s:%s\n",
sepolicy_file[i],strerror(errno));
close(fd);
return-1;
}
rc=security_load_policy(map,sb.st_size);
if(rc<0){
selinux_log(SELINUX_ERROR,"SELinux:Couldnotloadpolicy:%s\n",
strerror(errno));
munmap(map,sb.st_size);
close(fd);
return-1;
}
www.it-ebooks.info
munmap(map,sb.st_size);
close(fd);
selinux_log(SELINUX_INFO,"SELinux:Loadedpolicyfrom%s\n",
sepolicy_file[i]);
return0;
}
Thesecurityloadpolicyopensthe<selinuxmnt>/loadfile,whichinourcaseis/sys/fs/selinux/load.Atthispoint,thepolicyiswrittentothekernelviathispseudofile:
intsecurity_load_policy(void*data,size_tlen)
{
charpath[PATH_MAX];
intfd,ret;
if(!selinux_mnt){
errno=ENOENT;
return-1;
}
snprintf(path,sizeofpath,"%s/load",selinux_mnt);
fd=open(path,O_RDWR);
if(fd<0)
return-1;
ret=write(fd,data,len);
close(fd);
if(ret<0)
return-1;
return0;
}
www.it-ebooks.info
FixingthepolicyversionAtthispoint,wehaveaclearideaofhowthepolicyisloadedintothekernel.Thisisveryimportant.SELinuxintegrationwithAndroidbeganinAndroid4.0,sowhenportingtovariousforksandfragments,thisbreaks,andcodeisoftenmissing.Understandingallpartsofthesystem,howevercursory,willhelpustocorrectissuesastheyappearinthewildanddevelop.Thisinformationisalsousefultounderstandthesystemasawhole,sowhenmodificationsneedtobemade,you’llknowwheretolookandhowthingswork.Atthispoint,we’rereadytocorrectthepolicyversions.
Thelogsandkernelconfigareclear;onlypolicyversionsupto23aresupported,andwe’retryingtoloadpolicyversion26.ThiswillprobablybeacommonproblemwithAndroidconsideringkernelsareoftenoutofdate.
Thereisalsoanissuewiththe4.3sepolicyshippedbyGoogle.SomechangesbyGooglemadeitabitmoredifficulttoconfiguredevicesastheytailoredthepolicytomeettheirreleasegoals.Essentially,thepolicyallowsnearlyeverythingandthereforegeneratesveryfewdeniallogs.Somedomainsinthepolicyarecompletelypermissiveviaaper-domainpermissivestatement,andthosedomainsalsohaverulestoalloweverythingsodeniallogsdonotgetgenerated.Tocorrectthis,wecanuseamorecompletepolicyfromtheNSA.Replaceexternal/sepolicywiththedownloadfromhttps://bitbucket.org/seandroid/external-sepolicy/get/seandroid-4.3.tar.bz2.
AfterweextracttheNSA’spolicy,weneedtocorrectthepolicyversion.Thepolicyislocatedinexternal/sepolicyandiscompiledwithatoolcalledcheck_policy.TheAndroid.mkfileforsepolicywillhavetopassthisversionnumbertothecompiler,sowecanadjustthishere.Onthetopofthefile,wefindtheculprit:
...
#Mustbe<=/selinux/policyversreportedbytheAndroidkernel.
#Mustbewithinthecompatibilityrangereportedbycheckpolicy-V.
POLICYVERS?=26
...
Sincethevariableisoverridablebythe?=assignment.WecanoverridethisinBoardConfig.mk.Editdevice/fsl/imx6/BoardConfigCommon.mk,addingthefollowingPOLICYVERSlinetothebottomofthefile:
...
BOARD_FLASH_BLOCK_SIZE:=4096
TARGET_RECOVERY_UI_LIB:=librecovery_ui_imx
#SELinuxSettings
POLICYVERS:=23
-includedevice/google/gapps/gapps_config.mk
Sincethepolicyisontheboot.imgimage,buildthepolicyandbootimage:
$mmm-Bexternal/sepolicy/
$make–j4bootimage2>&1|teelogz
!!!!!!!!!WARNING!!!!!!!!!VERIFYBLOCKDEVICE!!!!!!!!!
$sudochmod666/dev/sdd1
www.it-ebooks.info
$ddif=$OUT/boot.imgof=/dev/sdd1bs=8192conv=fsync
EjecttheSDcard,placeitintotheUDOO,andboot.
TipThefirstoftheprecedingcommandsshouldproducethefollowinglogoutput:
out/host/linux-x86/bin/checkpolicy:writingbinaryrepresentation(version
23)toout/target/product/udoo/obj/ETC/sepolicy_intermediates/sepolicy
Atthispoint,bycheckingtheSELinuxlogsusingdmesg,wecanseethefollowing:
#dmesg|grep–iselinux
<6>init:loadingselinuxpolicy
<7>SELinux:128avtabhashslots,490rules.
<7>SELinux:128avtabhashslots,490rules.
<7>SELinux:1users,2roles,274types,0bools,1sens,1024cats
<7>SELinux:84classes,490rules
<7>SELinux:Completinginitialization.
Anothercommandweneedtorunisgetenforce.ThegetenforcecommandgetstheSELinuxenforcingstatus.Itcanbeinoneofthreestates:
Disabled:NopolicyisloadedorthereisnokernelsupportPermissive:Policyisloadedandthedevicelogsdenials(butisnotinenforcingmode)Enforcing:ThisstateissimilartothepermissivestateexceptthatpolicyviolationsresultinEACCESSbeingreturnedtouserspace
OneofthegoalswhilebootinganSELinuxsystemistogettotheenforcingstate.Permissiveisusedfordebugging,asfollows:
#getenforce
Permissive
www.it-ebooks.info
SummaryInthischapter,wecoveredtheimportantpolicyloadflowthroughtheinitprocess.Wealsochangedthepolicyversiontosuitourdevelopmenteffortsandkernelversion.Fromthere,wewereabletoloadtheNSApolicyandverifythatthesystemloadedit.ThischapteradditionallyshowcasedsomeoftheSELinuxAPIsandtheirinteractionswithSELinuxFS.Inthenextchapter,wewillexaminethefilesystemandthenmoveforwardinourquesttogetthesystemintoenforcingmode.
www.it-ebooks.info
Chapter6.ExploringSELinuxFSInthelastfewchapters,wesawSELinuxFSsurfaceonnumerousoccasions.Fromitsentryin/proc/filesystemstothepolicyloadintheinitdaemon,itseesfrequentuseinanSELinux-enabledsystem.SELinuxFSisthekernel-to-userspaceinterfaceandthefoundationonwhichhigheruserspaceidiomsandlibselinuxarebuilt.Inthischapter,wewillexplorethecapabilitiesofthisfilesystemforadeeperunderstandingofhowthesystemworks.Specifically,wewill:
DeterminehowtofindthemountpointoftheSELinuxfilesystemExtractstatusinformationaboutourcurrentSELinuxsystemModifyourSELinuxsystemstatusontheflyfromtheshellandthroughcodeInvestigateProcFSinterfaces
www.it-ebooks.info
LocatingthefilesystemThefirstthingweneedtodoislocatethemountpointforthefilesystem.libselinuxmountsthefilesystemineitheroftwoplaces:/selinux(bydefault)or/sys/fs/selinux.However,thisisnotastrictrequirementandcanbealteredwithacalltovoidset_selinuxmnt(char*mnt),whichsetstheSELinuxmountpointlocation.However,thisshouldhappenandshouldnotneedanyadjustmentinmostcircumstances.
Thebestwaytofindthemountpointinthesystemisbyrunningthemountcommandandfindingthelocationofthefilesystem.Fromtheserialconsole,issuethefollowingcommands:
root@udoo:/#mount|grepselinux
selinuxfs/sys/fs/selinuxselinuxfsrw,relatime00
Asyoucansee,themountpointis/sys/fs/selinux.Let’sgotothatdirectorybyissuingthefollowingcommandattheserialterminalprompt:
root@udoo:/#cd/sys/fs/selinux
root@udoo:/sys/fs/selinux#
YouarenowintherootoftheSELinuxfilesystem.
www.it-ebooks.info
InterrogatingthefilesystemYoucaninterrogateSELinuxFStofindoutwhatthekernel’shighestsupportedpolicyversionis.Thisisusefulwhenyoubegintoworkwithsystemsyoudidnotbuildfromsource.ItisalsousefulwhenyoudonothavedirectaccesstotheKConfigfile.ItisimportanttonotethatbothDACandMACpermissionsapplytothisfilesystem.WithrespecttoMACandSELinux,theaccessvectorsforthisareenumeratedinclasssecurityinthepolicyfilelocatedatexternal/sepolicy/access_vectors:
root@udoo:/sys/fs/selinux#echo'catpolicyvers'
23
TipInthepreviouscommand,andinseveralcommandstofollow,wedonotjustprintthefileswiththecatcommand.Thisisbecausethesefilesdonothaveatrailingnewlineattheendofthefile.Withoutthenewline,thecommandpromptfollowingthecommand’sexecutionwouldbeattheendofthelastlineoftheoutput.Wrappingthecatcommandwithechoguaranteesanewline.Analternatewaytogetthesameeffectisbyusingcatpolicyvers;echo.
Asweexpected,thesupportedversionis23.Asyourecall,wesetthisvalueinChapter4,InstallationontheUDOOwhileconfiguringthekerneltoenableSELinuxusingmakemenuconfigfromthekernel_imxdirectory.ThisisalsoaccessiblebythelibselinuxAPI:
intsecurity_policyvers(void);
Itshouldnotrequireanyelevatedpermissionsandisreadablebyanyoneonthesystem.
www.it-ebooks.info
TheenforcenodeInpreviouschapters,wediscussedthatSELinuxoperatesintwomodes,enforcingandpermissive.Bothmodeslogpolicyviolations,however,enforcingmodecausesthekerneltodenyaccesstotheresourceandreturnanerrortothecallinguserspaceprocess(forexample,EACCESS).SELinuxFShasaninterfacetoquerythisstatus—thefilenodeenforce.Readingfromthisfilereturnsthestatus0or1dependingonwhetherwearerunninginpermissiveorenforcingmode,respectively:
root@udoo:/sys/fs/selinux#echo'catenforce'
0
Asyoucansee,oursystemisinpermissivemode.Androidhasatoolboxcommandforprintingthisaswell.ThiscommandreturnsthestatusPermissiveorEnforcingdependingonwhetherwearerunninginapermissiveorenforcingmode,respectively:
root@udoo:/sys/fs/selinux#getenforce
Permissive
Youcanalsowritetotheenforcefile.TheDACpermissionsforthisfilesystemare:
Owner:rootread,write
Group:rootread
Others:read
Anyonecangettheenforcingstatus,buttosetit,youmustbetherootuser.TheMACpermissionrequiredforthisis:
class:security
vector:setenforce
Acommandcalledsetenforcecanchangethestatus:
root@udoo:/sys/fs/selinux#setenforce0
Toseewhatthecommanddoes,runitinstrace:
root@udoo:/sys/fs/selinux#stracesetenforce0
...
open("/proc/self/task/3275/attr/current",O_RDONLY)=4
brk(0x41d80000)=0x41d80000
read(4,"u:r:init_shell:s0\0",4095)=18
close(4)=0
open("/sys/fs/selinux/enforce",O_RDWR)=4
write(4,"0",1)
...
Aswecansee,theinterfacetoenforceisassimpleaswriting0or1.Thefunctioninlibselinuxtodothisisintsecurity_setenforce(intvalue).Anotherinterestingartifactoftheprecedingcommandiswecanseeprocfswasaccessed.SELinuxhassomeadditionalentriesinprocfsaswell.Thosewillbecoveredfurtherinthischapter.
www.it-ebooks.info
ThedisablefileinterfaceSELinuxcanalsobedisabledatruntimeusingthedisablefileinterface.However,thekernelmustbebuiltwithCONFIG_SECURITY_SELINUX_DISABLE=y.Ourkernelwasnotbuiltwiththisoption.ThisfileiswriteonlybyownerandhasnospecificMACpermissionassociatedwithit.Werecommendkeepingthisoptiondisabled.Additionally,SELinuxcanbedisabledbeforeapolicyisloaded.Evenwhentheoptionisenabled,onceapolicyisloaded,itisdisabled.
www.it-ebooks.info
ThepolicyfileThepolicyfileletsyoureadthecurrentSELinuxpolicyfilethatwasloadedintothekernel.Thiscanbereadandsavedtodisk:
root@udoo:/sys/fs/selinux#catpolicy>/sdcard/policy
Byenablingtheadbinterface,youcannowextractitfromthedeviceandanalyzeitonthehostwiththestandardSELinuxtools.TheDACpermissionsonthisfileareowner:root,read.ThereisnoSELinuxpermissionspecifictothisfile.
Theinversetothepolicyfileistheloadfile.WehaveseenthisfileappearwhenthepolicyfileisloadedbyinitusingthelibselinuxAPI:
intsecurity_load_policy(void*data,size_tlen);
www.it-ebooks.info
ThenullfileThenullfileisusedbySELinuxtoredirectunauthorizedfileaccesseswhendomaintransitionsoccur.Rememberthatadomaintransitioniswhenyoutransitionfromonecontexttoanother.Inmostcases,thisoccurswhenaprogramperformsaforkandexecfunction,butthiscouldhappenprogrammatically.Ineithercase,theprocesshasfilereferencesitcannolongeraccess,andtohelpkeepprocessesfromcrashing,theyjustwrite/readfromtheSELinuxnulldevice.
www.it-ebooks.info
ThemlsfileOneofthecapabilitiesoursystemhasisthatourcurrentpolicyisusingmultilevelsecurity(MLS)support.Thisiseither0or1,basedonwhethertheloadedpolicyfileisusingit.Sincewehaveitenabled,wewouldexpecttosee1fromthisfile:
root@udoo:/sys/fs/selinux#echo'catmls'
1
ThemlsfileisreadablebyallandhasacorrespondingSELinuxAPI:
intis_selinux_mls_enabled(void)
www.it-ebooks.info
ThestatusfileTheversionfileallowsamechanismbywhichyoucanbeinformedofupdatesthatoccurwithinSELinux.Onesuchexamplewouldbewhenapolicyreloadoccurs.Auserspaceobjectmanagercouldcachedecisionresultsandusethereloadeventasatriggertoflushtheircache.ThestatusfileisreadonlybyeveryoneandhasnospecificMACpermissions.ThelibselinuxAPIinterfaceis:
intselinux_status_open(intfallback);
voidselinux_status_close();
intselinux_status_updated(void);
intselinux_status_getenforce(void);
intselinux_status_policyload(void);
intselinux_status_deny_unknown(void);
Bycheckingthestatusstructure,youcandetectchangesandflushthecache.Currently,however,youaremissingthisAPIinyourlibselinux,butwe’llcorrectthatinChapter7,UtilizingAuditLogs.
TherearemanySELinuxFSfilesinthefiletree;ourintentherewasonlytocoverseveralfilesbecauseoftheirimportanceorpertinencetowhatwe’vedoneandwherewe’regoing.Wedidnotcover:
access
checkreqprot
commit_pending_bools
context
create
deny_unknown
member
reject_unknown
relabel
TheuseofthesefilesisnotsimpleandistypicallydonebyuserspaceobjectmanagersthatareusingthelibselinuxAPItoabstractthecomplexities.
www.it-ebooks.info
AccessVectorCacheSELinuxFSalsohassomedirectoriesyoucanexplore.Thefirstisavc.Thisstandsfor“AccessVectorCache”andcanbeusedtogetstatisticsaboutthesecurityserverinthekernel:
root@udoo:/sys/fs/selinux#cdavc/
root@udoo:/sys/fs/selinux/avc#ls
cache_stats
cache_threshold
hash_stats
Allthesefilescanbereadwiththecatcommand:
root@udoo:/sys/fs/selinux/avc#catcache_stats
lookupshitsmissesallocationsreclaimsfrees
285710285438272272128128
245827245409418418288288
267511267227284284192193
214328213883445445288298
Thecache_statsfileisreadablebyallandrequiresnospecialMACpermissions.
Thenextfiletolookatishash_stats:
root@udoo:/sys/fs/selinux/avc#cathash_stats
entries:512
bucketsused:284/512
longestchain:7
TheunderlyingdatastructurefortheAccessVectorCacheisahashtable;hash_statsliststhecurrentproperties.Aswecanseeintheoutputoftheprecedingcommand,wehave512slotsinthetable,with284oftheminuse.Forcollisions,wehavethelongestchainat7entries.ThisfileisworldreadableandrequiresnospecialMACpermissions.Youcanmodifythenumberofentriesinthistablethroughthecache_thresholdfile.
Thecache_thresholdfileisusedtotunethenumberofentriesintheavchashtable.Itisworldreadableandownerwriteable.ItrequirestheSELinuxpermissionsetsecparam,andcanbewrittentoandreadfromwiththefollowingsimplecommands,respectively:
root@udoo:/sys/fs/selinux/avc#echo"1024">cache_threshold
root@udoo:/sys/fs/selinux/avc#echo'catcache_threshold'
1024
Youcandisablethecachebywriting0.However,outsidethebenchmarkingtests,thisisnotencouraged.
www.it-ebooks.info
ThebooleansdirectoryTheseconddirectorytolookintoisbooleans.AnSELinuxbooleanallowspolicystatementstochangedynamicallyviabooleanconditions.Bychangingthebooleanstate,youcanaffectthebehavioroftheloadedpolicy.Thecurrentpolicydoesnotdefineanybooleans;sothisdirectoryisempty.Inpoliciesthatdefinebooleans,thedirectorywouldbepopulatedwithfilesnamedaftereachboolean.Youcanthenreadandwritetothesefilestochangethebooleanstate.TheAndroidtoolboxhasbeenmodifiedtoincludethegetseboolandsetseboolcommands.ThelibselinuxAPIalsoexposesthesecapabilities:
intsecurity_get_boolean_names(char***names,int*len);
intsecurity_get_boolean_pending(constchar*name);
intsecurity_get_boolean_active(constchar*name);
intsecurity_set_boolean(constchar*name,intvalue);
intsecurity_commit_booleans(void);
intsecurity_set_boolean_list(size_tboolcnt,SELboolean*boollist,int
permanent);
Booleansaretransactional.Thismeansitisanallornothingset.Whenyouusesecurity_set_boolean*,youmustcallsecurity_commit_booleans()tomakeittakeeffect.UnlikeLinuxdesktopsystems,permanentbooleansarenotsupported.Changingtheruntimevaluedoesnotpersistacrossreboots.Also,onAndroid,ifyouareattemptingAndroidCompatibilityTestSuite(CTS)compliance,booleanswillcausetheteststofail.BooleanscanhavevaryingDACpermissionsbasedonthetarget,buttheyalwaysrequiretheSELinuxpermission,setbool.
TipYoumustpasstheAndroidCompatabilityTestSuiteforAndroidbranding.MoreonCTScanbefoundathttps://source.android.com/compatibility/cts-intro.html.
www.it-ebooks.info
TheclassdirectoryThenextdirectorytolookatisclass.Theclassdirectorycontainsalltheclassesdefinedintheaccess_vectorsSELinuxpolicyfileorviatheclasskeywordintheSELinuxpolicylanguage.Foreachclassdefinedinthepolicy,adirectoryexistswiththesamename.Forinstance,runthefollowingontheserialterminal:
root@udoo:/sys/fs/selinux/class#ls-la
...
dr-xr-xr-xrootroot1970-01-0201:58peer
dr-xr-xr-xrootroot1970-01-0201:58process
dr-xr-xr-xrootroot1970-01-0201:58property_service
dr-xr-xr-xrootroot1970-01-0201:58rawip_socket
dr-xr-xr-xrootroot1970-01-0201:58security
...
Asyoucanseefromtheprecedingcommand,therearequiteafewdirectories.Let’sexaminetheproperty_servicedirectory.ThisdirectorywaschosenbecauseitisonlyonedefinedonAndroid.However,thefilespresentineachdirectoryarethesameandincludeindexandperms:
root@udoo:/sys/fs/selinux/class/property_service#ls
index
perms
ThemappingbetweenstringandsomearbitraryintegerthatisdefinedintheSELinuxkernelmoduleisindex.Adirectorythatcontainsallthepermissionspossibleforthatclassisperms:
root@udoo:/sys/fs/selinux/class/property_service#cdperms/
root@udoo:/sys/fs/selinux/class/property_service/perms#ls
set
Asyoucansee,thesetaccessvectorisavailablefortheproperty_serviceclass.Theclassdirectorycanbeverybeneficialtoobserveapolicyfilealreadyloadedinasystem.
www.it-ebooks.info
Theinitial_contextsdirectoryThenextdirectoryentrytopeerintoisinitial_contexts.Thisisthestaticmappingoftheinitialsecuritycontexts,betterknownassecurityidentifier(sid).ThismaptellstheSELinuxsystemwhichcontextshouldbeusedtostarteachkernelobject:
root@udoo:/sys/fs/selinux/initial_contexts#ls
any_socket
devnull
file
...
Wecanseewhattheinitialsidforfileisbyperforming:
root@udoo:/sys/fs/selinux/initial_contexts#echo'catfile'
u:object_r:unlabeled:s0
Thiscorrespondstotheentryinexternal/sepolicy/initial_sid_contexts:
...
sidfileu:object_r:unlabeled:s0…
www.it-ebooks.info
Thepolicy_capabilitiesdirectoryThelastdirectorytolookintoispolicy_capabilities.Thisdirectorydefinesanyadditionalcapabilitiesthepolicymighthave.Forourcurrentsetup,weshouldhave:
root@udoo:/sys/fs/selinux/policy_capabilities#ls
network_peer_controls
open_perms
Eachfileentrycontainsabooleanindicatingwhetherthefeatureisenabled:
root@udoo:/sys/fs/selinux/policy_capabilities#echo'catopen_perms'
1
Theentriesarereadablebyallandwriteablebynone.
www.it-ebooks.info
ProcFSWealludedtosomeoftheprocfsinterfacesthatarebeingexported.Muchofwhatisdiscussedisthesecuritycontexts,sothatmeanstheshellshouldhavesomesecuritycontextassociatedwithit…buthowdoweachievethis?SincethisisageneralmechanismthatallLSMsuse,thesecuritycontextsarebothreadandwrittenthroughprocfs:
root@udoo:/sys/fs/selinux/policy_capabilities#echo'cat
/proc/self/attr/current'
u:r:init_shell:s0
Youcanalsogetper-threadcontextsaswell:
root@udoo:/sys/fs/selinux/policy_capabilities#echo
'/proc/self/task/2278/attr/current'
u:r:init_shell:s0
Justreplace2278withthethreadIDyouwant.
TheDACpermissionsonthecurrentfilearereadandwriteforeveryone,butthosefilesaretypicallyveryrestrictedbyMACpermissions.Typically,onlytheprocessthatownstheprocfsentrycanreadthefiles,andyoumusthavebothstandardwritepermissionsandacombinationofsetcurrent.Notethatthe“from”and“to”domainsmustbeallowedusingadyntransition.Toread,youmusthavegetattr.Allofthesepermissionsareattainedfromthesecurityclass,process.ThelibselinuxAPIfunctionsgetconandsetconallowyoutomanipulatecurrent.
Theprevfilecanbeusedtofindthepreviouscontextyouswitchedfrom.Thisfileisnotwriteable:
root@udoo:/proc/self/attr#echo'catprev'
u:r:init:s0
Ourserialterminal’sformerdomainorsecuritycontextwasu:r:init:s0.
Theexecfileisusedtosetthelabelforchildrenprocesses.Thisissetbeforerunninganexec.AllthepermissionsonthesefilesarethesamewithrespecttotheMACpermissionsusedtoactuallysetthem.Thecallerattemptingtosetthismustalsoholdsetexecfromtheprocessclass.ThelibselinuxAPIintsetexeccon(security_context_tcontext)andintgetexeccon(security_context_t*context)canbeusedforsettingandretrievingthelabel.
Thefscreate,keycreate,andsockcreatefilesdosimilarthings.Whenaprocesscreatesanyoneofthecorrespondingobjects,fsobjects(files,namedpipes,orotherobjects),keys,orsockets,thevaluessethereareused.Thecallermustalsoholdsetfscreate,setsockcreate,andsetkeycreatefromtheprocessclass.ThefollowingSELinuxAPIisusedtoalterthese:
intset*createcon(security_context_tcontext);
intget*createcon(security_context_t*con);
www.it-ebooks.info
Where*canbefs,key,orsocket.
It’simportanttonotethatthesespecialprocessclasspermissionsgiveyoutheabilitytochangetheproc/attrfile.YoustillneedtogetthroughtheDACpermissionsandanySELinuxpermissionssetonthefileobjectsthemselves.Thenandonlythendoyouneedtheadditionalpermission,suchassetfscreate.
www.it-ebooks.info
JavaSELinuxAPISimilarAPIstotheCAPIsdiscussedpreviouslyexistforJavaaswell.Inthiscase,itisassumedyouwillbuildthecodewiththeplatform,asthesearenotpublicAPIsshippedwiththeAndroidSDK.TheAPIislocatedatframeworks/base/core/java/android/os/SELinux.java.However,thisisaverylimitedsubsetoftheAPI.
www.it-ebooks.info
SummaryInthischapter,weexploredtheinterfacebetweenthekernelanduserspacewithrespecttoSELinux,andreinforcedtheconceptsofaccessvectorclassandsecuritycontext.Inthenextchapter,wewillperformsomeupgradestooursystemandlookattheauditlogsgettingonestepclosertoourultimategoal—anoperabledeviceinSELinuxenforcingmode.Wesayoperablebecausewecanputitinenforcingmodenow.However,ifyoudoitnowviasetenforce1onaUDOO,yourdevicewillbecomeunstable.Onoursystem,forexample,thebrowserfailstolaunchifwedothis.
www.it-ebooks.info
Chapter7.UtilizingAuditLogsSofarwe’veseenAVCrecordsortheSELinuxdenialmessagesshowupindmesg,butdmesgisacircularmemorybuffer,subjecttofrequentrolloverdependentonhowverboseyourkernelis.Byusingtheauditkernelsubsystem,wecanroutethesemessagesintouserspaceandlogthemtodisk.Onthedesktop,thedaemonthatdoesthisiscalledauditd.AminimalportofauditdismaintainedintheNSAbrancheshowever,ithasnotofficiallybeenmergedintoAOSP.WearegoingtousetheauditdversionfromtheNSAbranchessinceweareworkingonAndroid4.3.TheofficiallymergedversionasofApril7,2014canbefoundathttps://android-review.googlesource.com/#/c/89645/.It’simplementedwithinlogd,andmergedathttps://android-review.googlesource.com/#/c/83526/.
Inthischapter,wewill:
Updateoursystemwiththefast-pacedSEforAndroidOpenSourceCommunity(AOSP)InvestigatehowtheauditsubsystemworksLearntoreadSELinuxauditlogsandstartwritingpolicyLookatcontextsrelativetothelogs
AllLSMsshouldlogtheirmessagesintotheauditsubsystem.Theauditsubsystemcanthenroutethemessagestothekernelcircularbufferusingprintk,ortotheauditingdaemoninuserspace,ifoneispresent.ThekernelanduserspaceloggingdaemoncommunicateusingtheAUDIT_NETLINKsocket.Wewilldissectthisinterfacefurtherinthechapter.
Lastly,theauditsubsystemhasthecapabilitytoprintcomprehensiverecordswhenpolicyviolationsoccur.Althoughyoudon’tneedthisfeaturetoenableandworkwithSELinux,itcanmakeyourlifeeasier.Toenablethissystem,youmustuseauditd,becauselogdcurrentlydoesn’thavethissupport.You’llneedtobuildyourkernelwithCONFIG_AUDITSYSCALL=yandplaceanaudit.rulesfilein/data/misc/audit/.Afteryoupatchyourtreewiththefollowinginstructions,readsystem/core/auditd/README.
Unfortunately,theUDOOkernelversion3.0.35doesnotsupportCONFIG_AUDITSYSCALL.Thepatchlocatedathttps://git.kernel.org/cgit/linux/kernel/git/stable/linux-stable.git/commit/?id=29ef73b7a823b77a7cd0bdd7d7cded3fb6c2587bshouldenablethesupport.However,ontheUDOO,itcausesadeadlockwecouldnottracedown.
www.it-ebooks.info
Upgrades–patchesgaloreAlthoughAndroid4.3,releasedfromGoogle,hadSEforAndroidsupport,itisstilllimited,especiallyintheareasofauditing.OneofthesimplestwaystobringthistoamoreuseablestateistogetthepatchesforsomeoftheprojectsfromtheNSA’sSEforAndroid4.3branch.Here,thecommunityhasstagedanddeployedmanyofthemoreadvancedfeatureswhichwerenotmergedinthe4.3timeframe.
TheNSAmaintainsrepositoriesathttps://bitbucket.org/seandroid/.Therearemanyprojectssofiguringoutwhichtouseandwhatbranchcanbedaunting.AwaytofindthemistogothrougheachprojectandfindtheprojectswithaSEAndroid-4.3branch.Youdon’tneedtodescendintothedevicetreessincewe’renotbuildingAOSPdevices.Thelistofsuchprojectis:
https://bitbucket.org/seandroid/system-corehttps://bitbucket.org/seandroid/frameworks-basehttps://bitbucket.org/seandroid/external-libselinuxhttps://bitbucket.org/seandroid/buildhttps://bitbucket.org/seandroid/frameworks-native
Wecanalsosafelyskipsepolicysincewe’vealreadyupdatedittothebleedingedge,butthekernelsareabittrickier.Weneedthechangesfromkernel-common(https://bitbucket.org/seandroid/kernel-common)andthebinderpatch(https://android-review.googlesource.com/#/c/45984/),whichcanbeattainedasfollows:
$mkdir~/sepatches
$cd~/sepatches
$gitclonehttps://bitbucket.org/seandroid/system-core.git
$gitclonehttps://bitbucket.org/seandroid/frameworks-base.git
$gitclonehttps://bitbucket.org/seandroid/external-libselinux.git
$gitclonehttps://bitbucket.org/seandroid/build.git
$gitclonehttps://bitbucket.org/seandroid/frameworks-native.git
Wecanstartbyfiguringouttheexactversionweneedtopatchtobylookingatthebuild/core/build_id.mkfile,andbyusingthewebpagehttps://source.android.com/source/build-numbers.htmltodoalookup.
ThefileshowsBUILD_IDisJSS15J,andthelookupshowsthatweareworkingwiththeandroid-4.3_r2.1releasefortheUDOO.
Foreachdownloadedprojectsofar,generatethepatchesbyrunningthecommandgitcheckoutorigin/seandroid-4.3_r2.Finally,executegitformat-patchorigin/jb-mr2.0-release.Sincethereisno4.3._r2.1branch,we’reusingr2.
Foreachofthesepatches,you’llneedtoapplytheminthetreefromtheircorrespondingudoo/<project>folder.Itisimportanttoapplythepatchesforeachprojectinnumericorderstartingwiththe0001*patch,movingonto0002*,andsoon.Asanexampleofhowtoapplyaspecificpatchforaproject,let’slookatthefirstpatchneededforsystem-core.NotethattheseGitrepositoriesusehyphensinplaceoftheslashesinthesourcetree;soframeworks-basecorrelatestoframeworks/base.
www.it-ebooks.info
First,generatethepatches:
$cdsepatches/system-core
$gitcheckoutorigin/seandroid-4.3_r2
$gitformat-patchorigin/jb-mr2.0-release
Applythefirstpatch,asfollows:
$cd<udoo_root>/system/core
$patch-p1<~/sepatches/system-core/0001-Add-writable-data-space-for-
radio.patch
patchingfilerootdir/init.rc
Reversed(orpreviouslyapplied)patchdetected!Assume-R?[n]
NoteNotethatforUDOO,itisimportantnottoapplyapatchnumberhigherthan0005inframeworks/base.Forotherprojects,youshouldapplyallthepatches.
Notetheerror.JusthitCtrl+Ctoquitthepatchingprocesswheneveryouseethis.TheGittreesarenotquiteperfect,andbecauseofthis,someofthepatchesarealreadyintheUDOOsource.Thepatchcommandwillletusknow,andwecanskipthesebycancelingthem,whenwarned,withCtrl+C.Keepgoingthroughthepatches,cancelingtheonesalreadyapplied,andfixingupanyfailures.Afterpatchinguserspace,it’shighlyrecommendedthatyoubuildtoensurenothingisbroken.
Onceuserspaceiscompletelypatched,weneedtopatchthekernel.Startbycloningthekernel-commonprojectfromBitbucketwiththegitclonehttps://bitbucket.org/seandroid/kernel-common.gitcommand.Wewillpatchthekernelwiththesamemethodastherestoftheprojectswiththeexceptionofthebinderpatch.Byviewingthelinkforthebinderpatchmentioned,https://android-review.googlesource.com/#/c/45984/,wefoundthattheGitSHAhashisa3c9991b560cf0a8dec1622fcc0edca5d0ced936,asgiveninthePatchset4referencefieldinthefollowingscreenshot:
WecanthengeneratethepatchforthisSHAhash:
$gitformat-patch-1a3c9991b560cf0a8dec1622fcc0edca5d0ced936
www.it-ebooks.info
0001-Add-security-hooks-to-binder-and-implement-the-hooks.patch
Then,applythatpatchwiththepatchcommandaswedidbefore.Thepatchhasafailedhunkforaheaderfileinclusion;justfixitupliketheothersbyusingtherejectfile.Whenyoubuild,you’llgetthiserrorinthekernel:
security/selinux/hooks.c:1846:9:error:variable'sad'hasinitializerbut
incompletetype
security/selinux/hooks.c:1846:28:error:storagesizeof'sad'isn'tknown
Goaheadandremovethislineandallreferences.Thiswasachangemadeinthe3.0kernels:
structselinux_audit_datasad={0,};
ad.selinux_audit_data=&sad;
NoteWefiguredthisoutbylookingthroughtheoriginal3.0patches,whichcanbefoundatfollowinglink:
https://bitbucket.org/seandroid/kernel-omap/commits/59bc19226c746f479edc2acca9a41f60669cbe82?at=seandroid-omap-tuna-3.0
Asyourecall,theUDOOusesacustominit.rc.Weneedtoaddanychangestoinit.rctotheoneUDOOactuallyuses.Allthepatchesthatcanmodifyinit.rcwillbeinthesystem-coreproject,specificallythese:
0003-Auditd-initial-commit.patch
0007-Handle-policy-reloads-within-ueventd-rather-than-res.patch
0009-Allow-system-UID-to-set-enforcing-and-booleans.patch
Goaheadandfindthechangestoinit.rcinthesepatchesandapplythemtodevice/fsl/imx6/etc/init.rcusingthesamepatchtechnique.
www.it-ebooks.info
TheauditsystemIntheprevioussection,wedidalotofpatching;thepointofwhichwastoenabletheauditintegrationworkdoneonAndroidanditsdependencies.Thesepatchesalsofixsomebugsinthecodeand,veryimportantly,enabletheSELinux/LSMbinderhooksandpolicycontrols.
TheauditsysteminLinuxisusedbyLSMstoprintthedenialrecordsaswellastogatherverythoroughandcompleterecordsofevents.Nomatterwhat,whenanLSMprintsamessage,itgetspropagatedtotheauditsubsystemandprinted.However,iftheauditsubsystemhasbeenenabled,thenyougetmorecontextassociatedwiththedenial.Theauditsubsystemevensupportsloadingrulesforwatchingthis.Forinstance,youcouldwatchallwritesto/systemthatwerenotdonebythesystemUID.
www.it-ebooks.info
TheauditddaemonTheauditddaemon,orservice,runsinuserspaceandlistensoveraNETLINKsockettotheauditsubsystem.Thedaemonregistersitselftoreceivethekernelmessages,andcanalsoloadtheauditrulesoverthissocket.Onceregistered,theauditddaemonreceivesalltheauditevents.Theauditddaemonwasminimallyported,andtherewasanattempttomainlineitintoAndroidthatwaslaterrejected.However,auditdhasbeenusedbyvariousOEMs(suchasSamsung)andbytheNSA’s4.3branch.AnalternativeapproachthatputrecordsinlogcatwaslatermergedintoAndroid(formoreinformation,refertohttps://android-review.googlesource.com/89645).
Earlier,wesawtheAVCdenialmessagesfromSELinuxindmesg.Theproblemwiththisisthatthecircularmemorylogispronetorolloverwhenyouhavemanydenialsorachattykernel.Withauditd,allthemessagescometothedaemonandarewrittentothe/data/misc/audit/audit.logfile.Thislogfile,hereinreferredtoasaudit.log,mayexistondevicebootandisrotatedintothe/data/misc/audit/audit.oldfile,knownasaudit.old.Thedaemonresumesloggingtoanewaudit.logfile.ThisrotateeventoccurswhenthesizethresholdAUDITD_MAX_LOG_FILE_SIZEKB(setduringcompiletimeinthesystem/core/auditd/Android.mkfile)isexceeded.Thisthresholdistypically1000KBbutcanbechangedinthedevice’smakefile.Also,sendingSIGHUPwithkillwillcausearotateasinthefollowingexample.
VerifythedaemonisrunningandgetitsPID:
root@udoo:/#ps-Z|grepaudit
u:r:auditd:s0audit22811/system/bin/auditd
u:r:kernel:s0root22932kauditd
Verifyonlyonelogexists:
root@udoo:/#ls-la/data/misc/audit/
-rw-r-----auditsystem791731970-01-0200:19audit.log
Rotatethelogs:
root@udoo:/#kill-SIGHUP2281
Verifyaudit.old:
root@udoo:/#ls-la/data/misc/audit/
-rw-r-----auditsystem3191970-01-0200:20audit.log
-rw-r-----auditsystem791731970-01-0200:19audit.old
www.it-ebooks.info
AuditdinternalsSincetheauditdandlibauditcodefromtheLinuxdesktophaveaGPLlicense,arewritewasdoneforAndroid,releasedundertheApachelicense.Therewriteisminimal,thusyouwillonlyfindthefunctionsimplementedthatwererequiredtosupportthedaemon.Thefunctionalandheaderinterfacesshouldremainidenticalthough.
Theauditddaemonstartslifeatmain()insystem/core/auditd.c.ItquicklychangesitspermissionsfromUIDroottoaspecialauditdUID.Whenitdoesthis,itretainsCAPSYS_AUDIT,whichisarequiredDACcapabilitychecktousetheAUDITNETLINKsocket.Itdoesthisviaacalltodrop_privileges_or_die().Fromthere,itdoessomeoptionparsingwithgetopt(),andwefinallygettotheaudit-specificcalls,thefirstofwhichopenstheNETLINKsocketusingaudit_open().Thisfunctionsimplycallssocket(PF_NETLINK,SOCK_RAW,NETLINK_AUDIT),whichopensafiledescriptortotheNETLINKsocket.Afteropeningthesocket,thedaemonopensahandletoaudit.logwithacalltoaudit_log_open(constchar*logfile,constchar*rotatefile,size_tthreshold).Thisfunctioncheckswhethertheaudit.logfileexistsand,ifitdoes,renamesittoaudit.old.Itthencreatesanewemptylogfileinwhichthedataisrecorded.
Thenextstepistoregisterthedaemonwiththeauditsubsystemsothatitknowstowhomtosendmessages.BysettingthePIDofthedaemon,youensurethatonlythisdaemonwillgetthemessages.SinceNETLINKcansupportmanyreaders,youdon’twanta“rogueauditd”toreadthemessages.Withthatstated,thedaemoncallsaudit_set_pid(audit_fd,getpid(),WAIT_YES),whereaudit_fdistheNETLINKsocketfromaudit_open(),getpid()returnsthedaemon’sPID,andWAIT_YEScausesthedaemontoblockuntiltheoperationiscomplete.Next,thedaemonenablestheauditsubsystem’sadvancedfeatureswithacalltoaudit_set_enabled(audit_fd,1)andaddsrulestotheauditsubsystemviaaudit_rules_read_and_add(audit_fd,AUDITD_RULES_FILE).Thisfunctionreadstherulesfromthatfile,formatssomestructures,andsendsthosestructurestothekernel.
Theaudit_set_enabled()andaudit_rules_read_and_add()onlyhaveaneffectifthekernelisbuiltwithCONFIG_AUDITSYSCALL.Afterthis,thedaemoncheckswhetherthe-koptionwasspecified.The-koptiontellsauditdtolookindmesgforanymissedauditrecords.Itdoesthisbecausethereisaracebetweencapturingauditrecordsbeforethecircularbufferoverflowsanduserspacestartingmanyservices,generatingauditeventsandpolicyviolations.Essentially,thishelpscoalescetheauditeventsfromearlybootintothesamelogfiles.
Afterthis,thedaemonentersalooptoreadfromtheNETLINKsocket,formattingthemessages,andwritingthemtothelogfile.ItstartsthisloopbywaitingforIOontheNETLINKsocketusingpoll().Ifpoll()exitswithanerror,theloopcontinuestocheckthequitvariable.IfEINTRisraised,theloopguard,quit,issettotrueinthesignalhandler,andthedaemonexits.Ifpoll()isdataontheNETLINK,thedaemoncallsaudit_get_reply(audit_fd,&rep,GET_REPLY_BLOCKING,0),gettinganaudit_reply
www.it-ebooks.info
structurebackwiththerepparameter.Itthenwritestheaudit_replystructure(withformatting)totheaudit.logfilewithaudit_log_write(alog,"type=%dmsg=%.*s\n",rep.type,rep.len,rep.msg.data).ItdoesthisuntilEINTRisraised,atwhichpoint,thedaemonexits.
Whenthedaemonexits,itclearsthePIDregisteredwiththekernel(audit_set_pid(audit_fd,0)),closestheauditsocketviaaudit_close()(whichisreallyjustthesyscall,close(audit_fd)),andclosestheaudit.logwithaudit_log_close().Theaudit_log_*familyoffunctionsisnotpartoftheGPLedinterfacetoauditandisacustomwrite.
WhenGoogleportedauditdtothelogdinfrastructureinAndroid,itusedthesamefunctionsandlibrarycodeusedbythedaemon’smain()andwrappeditintologd.However,Googledidnottaketheaudit_set_enabled()andaudit_rules_read_and_add()functions.
www.it-ebooks.info
InterpretingSELinuxdeniallogsTheSELinuxdenialsgetroutedtothekernelauditsubsystem,toauditd,andfinally,toaudit.logandaudit.old.Withthelogsresidentinaudit.log,let’spullthisfileoveradbandhaveacloserlookatit.
Runthefollowingcommandfromthehost,withadbenabled:
$adbpull/data/misc/audit/audit.log
Now,let’stailthatfileandlookfortheselines:
$tailaudit.log
...
type=1400msg=audit(88526.980:312):avc:denied{getattr}forpid=3083
comm="adbd"path="/data/misc/audit/audit.log"dev=mmcblk0p4ino=42
scontext=u:r:adbd:s0tcontext=u:object_r:audit_log:s0tclass=file
type=1400msg=audit(88527.030:313):avc:denied{read}forpid=3083
comm="adbd"name="audit.log"dev=mmcblk0p4ino=42scontext=u:r:adbd:s0
tcontext=u:object_r:audit_log:s0tclass=file
type=1400msg=audit(88527.030:314):avc:denied{open}forpid=3083
comm="adbd"name="audit.log"dev=mmcblk0p4ino=42scontext=u:r:adbd:s0
tcontext=u:object_r:audit_log:s0tclass=file
Therecordshereconsistoftwomajorportions:typeandmsg.Thetypefieldindicateswhattypeofmessageitis.Messageswithtype1400areAVCmessages,whichareSELinuxdenialmessages(thereareothertypes,aswell).Themsg(shortformessage)portionoftheprecedingpolicycontainsthepartforustoanalyze.
Thelastcommandweexecutedwasadbpull/data/misc/audit/aduit.logand,asyoucansee,wehaveafewadbpolicyviolationsatthetailoftheaudit.logfile.Let’sstartbylookingatthisevent:
type=1400msg=audit(88526.980:312):avc:denied{getattr}forpid=3083
comm="adbd"path="/data/misc/audit/audit.log"dev=mmcblk0p4ino=42
scontext=u:r:adbd:s0tcontext=u:object_r:audit_log:s0tclass=file
Wecanseethatthecommfieldisadbd.However,it’snotwisetotrustthisvaluesinceitcanbecontrolledfromuserspaceusingtheprctl()interface.Itcanonlybeviewedasahint.ThebestwaytoverifythisistocheckthePIDusingps-Z:
#ps-Z|grepadbd
u:r:adbd:s0root30831/sbin/adbd
Withthedaemonverified,wecannowcheckthemessageinmoredetail.Themessageconsistsofthefollowingfields(optionalfieldsareidentifiedby*):
avc:denied:Thispartwillalwayshappenanddenotesitisadenialrecord.{permission}:Thisisthepermissionthatwasdenied,inthiscase,getattr.for:Thiswillalwaysbeprintedandmakestheoutputreadable.Path*:Thisistheoptionalfieldthatcontainsthepathoftheobjectinquestion.Itonlymakessenseforfilesystemaccessdenials.dev*:Thisistheoptionalfieldthatidentifiestheblockdeviceforthemounted
www.it-ebooks.info
filesystem.Itonlymakessenseforfilesystemaccessdenials.ino*:Thisistheoptionalinodeofthefile.OnlytheanonymousfilesinLinuxprintinode.Itonlymakessenseforfilesystemaccessdenials.tclass:Thisisthetargetclassoftheobject,whichinourcasewasfile.
Atthispoint,weneedtounderstandwhatthemsgportionofthedenialrecordistellingusataverydistilledlevel.ItissayingthattheAndroiddebugbridgedaemonwantstobeabletocallgetattronourpolicyfile.Afeweventsdown,wewillseeitalsowantsreadandopen.Thisisthesideeffectofrunningadbpull.Agetattrpermissiondenialoccursfromastat()syscall,andtheread/openarefromread()andopen()syscalls.Ifyouwanttoallowthisinyourpolicy,whichwouldbeasecuritydecisionbasedonyourthreatmodel,youshouldadd:
allowadbdaudit_log:file{getattrreadopen};
Alternatively,usethemacrosetsdefinedinglobal_macros:
allowadbdaudit_log:filer_file_perms;
Mostofthetime,youshouldusethemacrosdefinedinglobal_macrosforfilepermissionaccesses.Typically,addingthemonebyoneisverytimeconsumingandtedious.Themacrosgroupthepermissionsinacontextanalogoustoread,write,andexecuteDACpermissions.Forinstance,ifyougiveitopenandread,there’sagoodchanceatsomepointthatthesourcedomainwillneedtostatthefile.So,ther_file_permsmacrohasthosepermissionsinitalready.
Youshouldaddthisruletoexternal/sepolicy/adbd.te.The.tefiles(alsocalledtypeenforcementfiles)areorganizedbysourcecontext,somakesureyouaddittothecorrectfile.Wedonotrecommendaddingthisallowrule—there’snolegitimatereasonthatadbdneedsaccesstotheauditlogs—wecansafelyignorethesewithadontauditrule:
dontauditadbdaudit_log:filer_file_perms;
Thedontauditruleisapolicystatementthatsaysdon’taudit(print)denialsthatmatchthisrule.
Ifyou’renotsurewhattodo,thebestadviceistoleveragethemailinglistsforSEforAndroid,SELinux,andaudit.Justkeepthemessagesappropriatetothespecificmailingliststopic.
Atoolexistscalledaudit2allow,whichcanhelpyouwritepolicyallowrules.However,it’sonlyatoolandcanbemisused.Ittranslatesthepolicyfiletotheallowrulesforthepolicy:
$cataudit.log|audit2allow
#=============adbd==============
allowadbdaudit_log:file{readgetattropen};
Theaudit2allowtoolisnotmacroawareorawareifyoureallywanttoaddthisallowruletothepolicyfile.Onlythepolicyauthorcanmakethisdecision.
Thereisalsoatooltoenablether_file_*macromappingcalledfixup.py.Youcanget
www.it-ebooks.info
thetoolathttps://bitbucket.org/billcroberts/fixup/overview.Afterdownloading,makeitexecutable,andplaceitsomewhereinyourexecutablepath:
$chmoda+xfixup.py
$cataudit.log|audit2allow|fixup.py
#=============adbd==============
allowadbdaudit_log:filer_file_perms;
www.it-ebooks.info
ContextsInthesimplestsense,writingpoliciesisjusttheactivityofidentifyingpolicyviolationsandaddingtheappropriateallowrulestothepolicyfile.However,inorderforSELinuxtobeeffective,thesourceandtargetcontextsmustbecorrect.Iftheyarenot,theallowrulesaremeaningless.
Thefirstthingsyoumightencounteraredenialswherethetargettypeisunlabeled.Inthiscase,thepropertargetlabelneedstobeset(refertoChapter11,LabelingProperties).Also,processlabelscanbewrong.Multipleprocessescanbelongtoadomain,andunlessexplicitlydoneviapolicy,thechildprocessofaparentinheritstheparent’sdomain.However,inAndroid,domainsthathavemultipleprocessesarequitelimited.Youwillneverseemultipleprocessesininit,system_server,adbd,auditd,debuggerd,dhcp,servicemanager,vold,netd,surfaceflinger,drmserver,mediaserver,installd,keystore,sdcardd,wpa,andzygotedomains.
It’sokaytoseemultipleprocessesinthefollowingdomains:
system_app
untrusted_app
platform_app
shared_app
media_app
release_app
isolated_app
shell
Onareleaseddevice,nothingshouldberuninthesu,recovery,andinit_shelldomains.Thefollowingtableprovidesacompletemappingofdomainstotheexpectedexecutablesandcardinality:
Domain Executable(s) Cardinality(N)
u:r:init:s0" /init N==1
u:r:ueventd:s0 /sbin/ueventd N==1
u:r:healthd:s0 /sbin/healthd N==1
u:r:servicemanager:s0 /system/bin/servicemanager N==1
u:r:vold:s0 /system/bin/vold N==1
u:r:netd:s0 /system/bin/netd N==1
u:r:debuggerd:s0 /system/bin/debuggerd,/system/bin/debuggerd64 N==1
u:r:surfaceflinger:s0 /system/bin/surfaceflinger N==1
u:r:zygote:s0 zygote,zygote64 N==1
u:r:drmserver:s0 /system/bin/drmserver N==1
www.it-ebooks.info
u:r:mediaserver:s0 /system/bin/mediaserver N>=1
u:r:installd:s0 /system/bin/installd N==1
u:r:keystore:s0 /system/bin/keystore N==1
u:r:system_server:s0 system_server N==1
u:r:sdcardd:s0 /system/bin/sdcard N>=1
u:r:watchdogd:s0 /sbin/watchdogd N>=0&&N<2
u:r:wpa:s0 /system/bin/wpa_supplicant N>=0&&N<2
u:r:init_shell:s0 null N==0
u:r:recovery:s0 null N==0
u:r:su:s0 null N==0
SeveralCompatibilityTestSuite(CTS)testshavebeenwrittenaroundthisandsubmittedtoAOSPathttps://android-review.googlesource.com/#/c/82861/.
Basedonthesegenericassertionsofwhatagoodpolicyshouldlooklike,let’sevaluateours.
First,wewillcheckforunlabeledobjects.Fromthehost,withtheaudit.logfileyouobtainedwithadbpull:
$cataudit.log|grepunlabeled
...
type=1400msg=audit(86527.670:341):avc:denied{rename}forpid=3206
comm="pool-1-thread-1"name="com.android.settings_preferences.xml"
dev=mmcblk0p4ino=129664scontext=u:r:system_app:s0
tcontext=u:object_r:unlabeled:s0tclass=file
...
Itlookslikewehavesomefilesandotherthingsthatarenotlabeledproperly;wewilladdresstheseintheChapter11,LabelingProperties.Now,let’scheckfordomainsthathavemultipleprocesseswhentheyshouldnot,andfindimproperbinariesinthosedomains(refertotheprevioustableforthecompletemapping.)
Init:
$adbshellps-Z|grepu:r:init:s0
u:r:init:s0root10/init
u:r:init:s0root22671/sbin/watchdogd
Zygote:
$adbshellps-Z|grepu:r:zygote:s0
u:r:zygote:s0root22851zygote
$adbshellps-Z|grepu:r:init_shell
u:r:init_shell:s0root22781/system/bin/sh
…throughalldomains
www.it-ebooks.info
Afterdoingthis,wefoundissuesbecausesomethingisrunningintheinit_shelldomain,andwatchdogdisintheinitdomain.Thesemustbecorrected.
www.it-ebooks.info
SummaryWritingsepolicyisrelativelyeasy,writinggoodpolicyisanart.Itrequiresthepolicyauthortounderstandthesystemandtheimplicationsoftheallowrule.Policyitselfisameta-programminglanguagewherethelanguagecontrolshowuserspaceandthekernelgetalong,andmuchlikeanyprogram,thepolicycanbearchitectedforaspecificuse.Policiescanbetooporous(essentiallyuseless)orverytightanddifficulttochangewithoutbreakingtheportionsthatalreadywork.
Agoodpolicyneedstopreservetheintendedproperfunctionofthesystem,sothoroughtestingofallthesystemswithinAndroidisessential.CTSisagreathelpinexercisingAndroid,butitoftendoesnotcoverallthecases;usertestingisrecommended.Inthenextchapter,wewillcoverhowfilesystemsandfilesystemobjectsgettheirsecuritylabelsandhowwecanchangethem.Later,wewillgooverhowtouseCTSasatooltotestthesystemandgeneratepolicyviolationsforintendedbehaviors.
www.it-ebooks.info
Chapter8.ApplyingContextstoFilesInthelastchapter,weupgradedoursystem,collectedtheauditlogs,andstartedtoanalyzetheauditrecords.Wediscoveredthatsomeobjectsonthefilesystemwereunlabeled.Inthischapter,wewill:
LearnhowfilesystemsandfilesystemobjectsgettheirlabelsDemonstratetechniquestochangelabelsIntroduceextendedattributesforlabelingInvestigatefilecontextsanddynamictypetransitions
www.it-ebooks.info
LabelingfilesystemsFilesystemsonLinuxoriginatefrommount,withtheexceptionoframdiskrootfsonAndroid.FilesystemsonLinuxvarydrastically.Ingeneral,inordertosupportallthefeaturesofSELinux,youneedafilesystemwiththesupportforxattrandthesecuritynamespace.Wesawthisrequirementwhenweweresettingupthekernelconfiguration.
Filesystemobjects,astheyarecreated,allstartwithaninitialcontext,justlikeallotherkernelobjects.Contextsonfilessimplyinheritfromtheirparent,soiftheparentisunlabeled,thenthechildisunlabeled,withtheexceptionofatypetransitionrule.Typically,ifthecontextisunlabeled,itinfersthatthedatawascreatedonafilesystempriortoenablingSELinuxsupport,orthetypelabelinthexattrdoesnotexistinthecurrentlyloadedpolicy.
Theinitiallabelorinitialsecurityid(sid),isinthesepolicyfileinitial_sid_contexts.Eachobjectclasshasitsassociatedinitialsidpresent.Forexample,let’stakealookatthefollowingcodesnippet:
...
sidfsu:object_r:labeledfs:s0
sidfileu:object_r:unlabeled:s0…
www.it-ebooks.info
fs_useFilesystemscanbelabeledinavarietyofways.Thebestcasescenarioiswhenthefilesystemsupportsxattrs.Inthatcase,anfs_use_xattrstatementshouldappearinthepolicy.Thesestatementsappearinthefs_usefileinthesepolicydirectory.Thesyntaxforfs_use_xattris:
fs_use_xattr<fstype><context>
Tolookatfs_usefromsepolicy,wecanrefertoanexamplefortheext4filesystems:
...
fs_use_xattrext3u:object_r:labeledfs:s0;
fs_use_xattrext4u:object_r:labeledfs:s0;
fs_use_xattrxfsu:object_r:labeledfs:s0;
...
ThistellsSELinuxthatwhenitencountersanext4fsobject;lookintheextendedattributesforthelabelorfilecontext.
www.it-ebooks.info
fs_task_useTheotherwayafilesystemcanbelabeledisbyusingtheprocess’contextwhilecreatingobjects.Thismakessenseforpseudofilesystemswheretheobjectsarereallyprocesscontexts,suchaspipefsandsockfs.Thesepseudofilesystemsmanagethepipeandsocketsyscallsandarenotreallymountedtouserspace.Theyexistinternallytothekernel,forthekernelsuse.However,theydohaveobjects,andlikeanyotherobject,theyneedtobelabeled.Thisisthecontextinwhichthefs_task_usepolicystatementmakessense.Theseinternalfilesystemscanonlybeaccessedbyprocessesdirectly,andprovideservicestothoseprocesses.Hence,labelingthemwiththecreatormakessense.Thesyntaxisasfollows:
fs_task_use<fstype><context>
Examplesfromthesepolicyfilefs_useareasfollows:
...
#Labelinodesfromtasklabel.
fs_use_taskpipefsu:object_r:pipefs:s0;
fs_use_tasksockfsu:object_r:sockfs:s0;
...
www.it-ebooks.info
fs_use_transThenextwayyoumightwishtosetlabelsonpseudofilesystemsthatareactuallymounted,isbyusingfs_use_trans.Thissetsafilesystemwidelabelonthepseudofilesystem.Thesyntaxforthisisasfollows:
fs_use_trans<fstype><context>
Examplefromthesepolicyfilefs_useisasfollows:
...
fs_use_transdevptsu:object_r:devpts:s0;
fs_use_transtmpfsu:object_r:tmpfs:s0;
...
www.it-ebooks.info
genfsconIfnoneofthefs_use_*statementsmeetyourusecases,whichwouldbethecaseforvfatfilesystemsandprocfs,thenyouwouldusethegenfsconstatement.Thelabelspecifiedforgenfsconappliestoallinstancesofthatfilesystemmount.Forinstance,youmightwishtousegenfsconwiththevfatfilesystems.Ifyouhavetwovfatmounts,theywillusethesamegenfsconstatementforeachmount.However,genfsconbehavesdifferentlywithprocfs,andletsyoulabeleachfileordirectorywithinthefilesystem.
Thesyntaxofgenfsconisasfollows:
genfscon<fstype><path><context>
Examplesfromsepolicygenfs_contextsareasfollows:
...
#Labelinodeswiththefslabel.
genfsconrootfs/u:object_r:rootfs:s0
#proclabelingcanbefurtherrefined(longestmatchingprefix).
genfsconproc/u:object_r:proc:s0
genfsconproc/net/xt_qtaguid/ctrlu:object_r:qtaguid_proc:s0…
Notethattherootfspartialpathis/.It’snotprocfs,soitdoesn’tsupportanyfinegranularitytoitslabeling;so/istheonlythingyoucanuse.However,youcangetwildwithprocfsandsettoanygranularityyoudesire.
www.it-ebooks.info
MountoptionsAnotheroption,ifnoneofthosefityourneeds,istopassthecontextoptionviathemountcommandline.Thissetsafilesystemwidemountcontext,suchasgenfscon,butisusefulinthecaseofmultiplefilesystemsthatneedtohaveseparatelabels.Forinstance,ifyouhavetwovfatfilesystemsmounted,youmightwishtoseparateaccessestothem.Withgenfsconstatements,bothfilesystemswouldusethesamelabelprovidedbygenfscon.Byspecifyingthelabelatmounttime,youcanhavetwovfatfilesystemsmountedwithdifferentlabels.
Takethefollowingcommandasanexample:
mount-ocontext=u:object_r:vfat1:s0/dev/block1/mnt/vfat1
mount-ocontext=u:object_r:vfat2:s0/dev/block1/mnt/vfat2
Additionaltothecontextasamountoptionare:fscontextanddefcontext.Theseoptionsaremutuallyexclusivefromcontext.Thefscontextoptionsetsthemetafilesystemtypethatisusedforcertainoperations,suchasmount,butdoesnotchangetheperfilelabels.Thedefcontextsetsthedefaultcontextforunlabeledfilesoverridingtheinitial_sidstatements.Lastly,anotheroption,rootcontextallowsyoutosettherootinodecontextinthefilesystem,butonlyforthatobject.Accordingtothemanpagemount(man8mount),itwasfoundusefulinstatelessLinux.
www.it-ebooks.info
LabelingwithextendedattributesLastly,andprobablythemostfrequentlyusedwayoflabeling,isbyusingtheextendedattributessupportalsoknownasxattrorEAsupport.Evenwithxattrsupport,newobjectsinheritthecontextoftheirparentdirectory;however,theselabelshavethegranularityofbeingperfilesystemobject-basedorinode-based.Ifyouremember,wehadtoturnonorverifythatXATTR(CONFIG_EXT4_FS_XATTR)supportwasenabledforourfilesystemsonAndroidaswellasconfiguringSELinuxtouseitviatheconfigoptionCONFIG_EXT4_FS_SECURITY.
Extendedattributesareakey-valuemetadatastoresforfiles.SELinuxsecuritycontextsusethesecurity.selinuxkey,andthevalueisastringthatisthesecuritycontextorlabel.
www.it-ebooks.info
Thefile_contextsfileWithinthesepolicydirectory,youwillfindthefile_contextsfile.Thisfileisconsultedtosettheattributesonfilesystemsthatsupportperfilesecuritylabels.Notethatacoupleofpseudofilesystemssupportthisaswell,suchastmpfs,sysfs,andrecentlyrootfs.Thefile_contextfilehasaregularexpression-basedsyntaxasfollows,whereregexpistheregularexpressionforthepath:
regexp<type>(<filelabel>|<<none>>)
Ifmultipleregularexpressionsaredefinedforafile,thelastmatchisused,soorderisimportant.
Thefollowinglistshowseachtypefieldvalueforthetypeoffilesystemobject,theirmeanings,andsyscallinterface:
--:Thisdenotesaregularfile.-d:Thisdenotesadirectory.-b:Thisdenotesablockfile.-s:Thisdenotesasocketfile.-c:Thisdenotesacharacterfile.-l:Thisdenotesalinkfile.-p:Thisdenotesanamedpipefile.
Asyoucansee,thetypeisessentiallythemodeasoutputbyls-lacommand.Ifit’snotspecified,itmatcheseverything.
Thenextfieldisthefilelabelorthespecialidentifier<<none>>.Eitheronewouldsupplyacontextortheidentifier<<none>>.Ifyouspecifythecontext,theSELinuxtoolsthatconsultfile_contextsusethelastmatchtothespecifiedcontext.Ifthecontextspecifiedis<<none>>,itmeansthatnocontextisassigned.So,leavetheonethatwehavefound.Thekeyword<<none>>isnotusedintheAOSPreference,sepolicy.
It’simportanttonotethattheprecedingparagraphexplicitlystatesthatSELinuxtoolsusethefile_contextspolicy.Thekernelisnotawarethatthisfileexists.SELinuxlabelsallitsobjectsbyexplicitlysettingthemfromuserspacewithtoolsthatlookupthecontextinfile_contextorviathefs_use_*andgenfspolicystatements.Inotherwords,file_contextsisnotbuiltinthecorepolicyfile,anditisnotloadedoruseddirectlybythekernel.Atbuildtime,thefile_contextsfileisbuiltintheramdiskrootfsandcanbefoundat/file_contexts.Also,duringbuildtime,thesystemimageislabeled,freeingthedeviceitselffromthisburden.
InAndroid,init,ueventd,andinstalldhaveallbeenmodifiedtolookupthecontextsofobjectstheyarecreating;sothattheycanlabelthemproperly.Thus,alltheinitbuiltinsthatcreatefilesystemobjects,suchasmkdir,havebeenmodifiedtomakeuseofthefile_contextsfileifitexists,andthesamegoesforinstalldandueventd.
Let’stakealookatsomesnippetsfromthefile_contextfilelocatedinsepolicy:
...
www.it-ebooks.info
/dev(/.*)?u:object_r:device:s0
/dev/accelerometeru:object_r:sensors_device:s0
/dev/alarmu:object_r:alarm_device:s0…
Here,wearesettingupthecontextsforfilesin/dev.Notehowtheentriesareinorderfrommostgenerictomorespecificdevfiles.Thus,anyfilesnotcoveredbythemorespecificentrieswillendupwiththecontextu:object_r:device:s0,andthefilesthatmatchfurtherdown,endupwithamorespecificlabel.Forinstance,theaccelerometerat/dev/accelerometerwillgetthecontextu:object_r:sensors_device:s0.Notethatthetypefieldwasomitted,whichmeansthatitmatchesonallfilesystemobjects,suchasdirectories(type-d).
Youmightbewonderinghow/dev,thedirectoryitself,getsafilecontext.Lookingatsomeofthesnippets,wesaythe/orroot,gotlabeledviathestatementgenfsconrootfs/u:object_r:rootfs:s0inthegenfs_contextfile.Thischapterstatedearlierthat,“newobjectsinheritthecontextoftheirparentdirectory.”Hence,wecanreasonthat/devisofcontextu:object_r:rootfs:s0sincethatisthelabel/has.Wecantestthisbypassingthe-Zflagtolstoshowusthelabelof/dev.OntheUDOOserialconnection,executethefollowingcommand:
130|root@udoo:/#ls-laZ/
...
drwxr-xr-xrootrootu:object_r:device:s0dev
...
Itseemsthatthehypothesisisincorrect,butnotethatitistruethateverythinghasalabel,andifit’snotspecified,thenitinheritsfromtheparent.Lookingbackatsepolicy,wecanseethatthedevfilesystemwasinitiallysetwithafs_use_transdevtmpfsu:object_r:device:s0;policystatement.Sowhenthefilesystemismounted,itissetfilesystemwide.Later,whenentriesareaddedbyinitorueventd,theyusefile_contextsentriestosetthecontextofthenewlycreatedfilesystemobjecttowhatisspecifiedinthefile_contextsfile.Thefilesystemat/dev,whichisadevtmpspseudofilesystem,isanexampleofafilesystemthathasbothafilesystem-widelabelviathefs_use_transstatement,butcanalsosupportfinegrainedlabelingviafile_contexts;.FilesystemsarenotveryconsistentincapabilitiesonLinux.
www.it-ebooks.info
DynamictypetransitionsDynamictypetransitionsindicatedbytheSELinuxpolicystatementtype_transitionareawaytoallowfilestodynamicallydeterminetheirtypes.Becausethesearecompiledintothepolicy,thesedonothaveanyrelationtothefile_contextsfile.Thesepolicystatementsallowthepolicyauthortodynamicallydictatethecontextofafilebasedonthecontextinwhichthefileiscreated.Theseareusefulinsituationswhereyoudon’tcontrolsourcecode,ordonotwishtocoupleSELinuxinanyway.Forinstance,thewpasupplicant,whichisaservicethatrunsforWi-Fisupportandcreatesasocketfileinitsdatadirectory.Itsdatadirectoryislabeledwiththetypewifi_data_fileandasexpected,thesocketendsupwiththatlabel.However,thissocketissharedbythesystemserver.Now,wecanallowjustthesystemservertoaccessthetypeandobjectclass,however,hostapdandotherthingsarecreatingsocketsandotherobjectsinthatdirectoryandthustheobjectsalsohavethistype.Wereallywanttoensurethatthetwosocketsinquestion,theoneusedbyhostapdandtheotherbysystemserver,arekeptexclusivefromeachother.Todothis,weneedtobeabletolabeloneofthesocketsatafinergranularity,andtodoso,wecaneithermodifythecodeoruseadynamictypetransition.Ratherthanmuckingwiththecode,let’suseatypetransition,asfollows:
type_transitionwpawifi_data_file:sock_filewpa_socket;
Thisisanactualstatementfromthesepolicyfile,wpa_supplicant.te.Itsaysthat,whenaprocessofthetypewpacreatesafileofthetypewifi_data_fileandtheobjectclassissock_filetolabelitaswpa_socketoncreation.Thestatementsyntaxisasfollows:
type_transition<creatingtype><createdtype>:<class><newtype>;
AsofSELinuxpolicyversion25,thetype_transitionstatementcansupportnamedtypetransitionswhereafourthargumentexistsandisthenameofthefile:
type_transition<creatingtype><createdtype>:<class><newtype><file
name>;
Wewillseeanexampleuseofthisfilenameinthesepolicyfile,system_server.te:
type_transitionsystem_serversystem_data_file:sock_file
system_ndebug_socket"ndebugsocket";
Notethefilenameorbasenameandnotthepath,anditmustmatchexactly.Regexisnotsupported.It’salsointerestingtonotethatthedynamictransitionsarenotlimitedtofileobjects,butanyobjectclasseventprocesses.WewillseehowdynamicprocesstransitionsareusedinChapter9,AddingServicestoDomains.
www.it-ebooks.info
ExamplesandtoolsWiththetheorybehindus,let’slookatthetoolsandtechniquestolabelfilesinthesystem.Let’sstartbymountingaramfsfilesystem.Wewillstartbyremounting/sinceitisreadonlyandcreateamountpointforthefilesystem.ViatheUDOOserialconsole,execute:
root@udoo:/#mount-oremount,rw/
root@udoo:/#mkdir/ramdisk
root@udoo:/#mount-tramfs-osize=20mramfs/ramdisk
Now,wewanttoseewhichlabelthefilesystemhas:
#ls-laZ/|grepramdisk
drwxr-xr-xrootrootu:object_r:unlabeled:s0ramdisk
Asyoucanrecall,theinitial_sid_contextfilehadthisinitialsidsetforthefilesystem:
sidfileu:object_r:unlabeled:s0
Ifwewanttogetthisramdiskinanewlabel,weneedtocreatethetypeinthepolicy,andsetanewgenfsconstatementtouseit.Wewilldeclarethenewtypeinthesepolicyfilefile.te:
typeramdisk,file_type,fs_type;
Thetypepolicystatementsyntaxisasfollows:
type<newtype>,<attribute0,attribute1…attributeN>;
AttributesinSELinuxarestatementsthatletyoudefinecommongroups.Theyaredefinedviatheattributestatement.InAndroidSELinuxpolicy,wehavefile_typeandfs_typedefinedforusalready.Wewillusethemherebecausethisnewtype,whichwe’recreating,hastheattributesfile_typeandfs_type.Thefile_typeattributeisassociatedwithatypeforafile,andthefs_typeattributemeansthatthistypeisalsoassociatedwithfilesystems.Attributes,rightnow,arenotofgreatimportance;sodon’tgetcaughtupinthedetail.
Thenextthingtomodifyisthesepolicyfile,genfs_contextbyaddingthefollowing:
genfsconramfs/u:object_r:ramdisk:s0
Now,wewillcompilethebootimageandflashittothedevice,orbetteryet,let’susethedynamicpolicyreloadsupportlikethefollowing.
FromtherootoftheUDOOprojecttreebuildjustthesepolicyproject:
$mmmexternal/sepolicy/
Pushthenewpolicyoveradb,asfollows:
$adbpush$OUT/root/sepolicy/data/security/current/sepolicy
544KB/s(86409bytesin0.154s)
Triggerareloadbyusingthesetpropcommand:
www.it-ebooks.info
$adbshellsetpropselinux.reload_policy1
Ifyouhavetheserialconsoleconnected,youshouldsee:
SELinux:Loadedpolicyfrom/data/security/current/sepolicy
Ifyoudon’t,andjusthaveadb,checkdmesg:
$adbshelldmesg|grep"SELinux:Loaded"
<4>SELinux:Loadedpolicyfrom/sepolicy
<6>init:SELinux:Loadedpropertycontextsfrom/property_contexts
<4>SELinux:Loadedpolicyfrom/data/security/current/sepolicy
Asuccessfulloadshoulduseourpolicyatthepath,/data/security/current/sepolicy.Let’sunmounttheramdiskandremountittocheckoutitstype:
root@udoo:/#umount/ramdisk
root@udoo:/#mount-tramfs-osize=20mramfs/ramdisk
root@udoo:/#ls-laZ/|grepramdisk
drwxr-xr-xrootrootu:object_r:ramdisk:s0ramdisk
Wewereabletomodifythepolicyandusegenfscontochangethefilesystemtype,andnowtoshowinheritance,let’sgoaheadandcreateafileonthefilesystemwithtouch:
root@udoo:/#cd/ramdisk
root@udoo:/ramdisk#touchhello
root@udoo:/ramdisk#ls-Z
-rw-------rootrootu:object_r:ramdisk:s0hello
Asweexpected,thenewfileislabeledwiththetyperamdisk.Now,supposewhenwedotouchfromtheshell,wewantthefiletobeofadifferenttype,suchasramdisk_newfile;howcanwedothis?Wecandothisbymodifyingtouchitselftoconsultfile_contexts,orwecandefineadynamictypetransition;letustrythedynamictypetransitionapproach.Thefirstargumenttothetype_transitionstatementisthecreatingtype;sowhattypeisourshellin?Youcangetthisbyperforming:
root@udoo:/ramdisk#echo`cat/proc/self/attr/current`
u:r:init_shell:s0
Asimplerwayistoruntheid-Zcommand,whichusestheaforementionedprocfile.Foraserialconsole,execute:
root@udoo:/ramdisk#id-Z
uid=0(root)gid=0(root)context=u:r:init_shell:s0
Andtorunthesamecommandfortheadbshell:
$adbshellid-Z
uid=0(root)gid=0(root)context=u:r:shell:s0
Notethediscrepancybetweenourserialconsoleshellandtheadbshell,inChapter9,AddingServicestoDomains;wewillfixthis.Becauseofthis,thepolicyweauthornowwilladdressbothcases.
Startbyopeningthesepolicyfile,init_shell.teandappendthefollowingtotheendofthefile:
www.it-ebooks.info
type_transitioninit_shellramdisk:fileramdisk_newfile;
Dothisforthesepolicyfile,shell.te:
type_transitionshellramdisk:fileramdisk_newfile;
Now,weneedtodeclarethenewtype;soopenupthesepolicyfile,file.teandappendthefollowing:
typeramdisk_newfile,file_type;
Notethatwehaveonlyusedthefile_typeattribute.Thisisbecauseafilesystemshouldneverhavethetyperamdisk_newfile,onlyafileresidingwithinthatfilesystemshould.
Now,buildtheadbpolicy,pushittothedevice,andtriggerareload.Withthatdone,createthefileandchecktheresults:
$adbshell'touch/ramdisk/shell_newfile'
$adbshell'ls-laZ/ramdisk'
-rw-rw-rw-rootrootu:object_r:ramdisk:s0shell_newfile
Soitdidn’twork.Let’sinvestigatethereasonbytryingonanexampleofanext4filesystem.Let’susethefollowingcommands:
root@udoo:/#cd/data/
root@udoo:/data#mkdirramdisk
Now,checkitscontext:
root@udoo:/data#ls-laZ|grepramdisk
drwx------rootrootu:object_r:system_data_file:s0ramdisk
Thelabelissystem_data_file.Thisisnothelpful,asitdoesn’tapplytoourtypetransitionrule;tofixthis,wecanusethechconcommandtoexplicitlychangethefilescontext:
root@udoo:/data#chconu:object_r:ramdisk:s0ramdisk
root@udoo:/data#ls-laZ|grepramdisk
drwx------rootrootu:object_r:ramdisk:s0ramdisk
Nowwiththecontextchangedtomatchwhatweweretryingearlierwiththeramdisk,let’strytocreateafilewithinthisdirectory:
root@udoo:/data/ramdisk#touchnewfile
root@udoo:/data/ramdisk#ls-laZ
-rw-------rootrootu:object_r:ramdisk_newfile:s0newfile
Asyoucansee,thetypetransitionhasoccurred.ThiswasmeanttoillustratetheissuesyoumayfindwhileworkingwithSELinuxandAndroid.Nowthatwehaveshownthatourtype_transitionstatementisvalid,thereareonlytwopossibilitieswhythisisfailing:thefilesystemdoesn’tsupportitorwe’remissingsomethingsomewhereto“turniton”.Itturnsoutthatthelatteristhecase;weweremissingourfs_use_transstatements.Sogoaheadandopenupthesepolicyfile,fs_useandaddthefollowingline:
fs_use_transramfsu:object_r:ramdisk:s0;
www.it-ebooks.info
ThisstatementenablesSELinuxdynamictransitionsonthisfilesystem.Now,rebuildthesepolicyproject,adbpushthepolicyfile,andenableadynamicreloadviasetprop:
$mmmexternal/sepolicy
$adbpush$OUT/root/sepolicy/data/security/current/sepolicy546KB/s
(86748bytesin0.154s)
$adbshellsetpropselinux.reload_policy1
root@udoo:/#cdramdisk
root@udoo:/ramdisk#touchfoo
root@udoo:/ramdisk#ls-Z
-rw-------rootrootu:object_r:ramdisk_newfile:s0foo
Thereyouhaveit,theobjecthastherightvaluedeterminedbyadynamictypetransition.Weweremissingfs_use_trans,whichenabledtypetransitionsonfilesystemsthatdon’tsupportxattrs.
Now,supposewewanttomountanotherramdisk,whatwouldhappen?Wellsinceitwaslabeledwiththegenfsconstatement,allfilesystemsmountedwiththattypeshouldgetthecontext,u:object_r:ramdisk:s0.Wewillmountthisfilesystemat/ramdisk2,andverifythisbehavior:
root@udoo:/#mkdirramdisk2
root@udoo:/#mount-tramfs-osize=20mramfs/ramdisk2
Also,checkthecontexts:
root@udoo:/#ls-laZ|grepramdisk
drwxr-xr-xrootrootu:object_r:ramdisk:s0ramdisk
drwxr-xr-xrootrootu:object_r:ramdisk:s0ramdisk2
Ifwewanttowriteallowrulestoseparateaccessestothesefilesystems,wewillneedtohavetheirtargetfilesinseparatetypes.Todothis,wecanmountthenewramdiskwiththecontextoption.Butfirst,weneedtocreatethenewtype;letsgotothesepolicyfile,file.teandaddanewtypecalledramdisk2:
typeramdisk2,file_type,fs_type;
Now,buildthesepolicywiththecommandmmm,followedbeusingthecommandabdpushtopushthepolicy,andtriggerareloadwiththesetpropcommand:
$mmmexternal/sepolicy/
$adbpushout/target/product/udoo/root/sepolicy
/data/security/current/sepolicy542KB/s(86703bytesin0.155s)
$adbshellsetpropselinux.reload_policy1
Atthispoint,let’sumount/ramdisk2andremountitwiththecontext=option:
root@udoo:/#umount/ramdisk2/
root@udoo:/#mount-tramfs-osize=20m,context=u:object_r:ramdisk2:s0
ramfs/ramdisk2
Now,verifythecontexts:
root@udoo:/#ls-laZ|grepramdisk
drwxr-xr-xrootrootu:object_r:ramdisk:s0ramdisk
drwxr-xr-xrootrootu:object_r:ramdisk2:s0ramdisk2
www.it-ebooks.info
Wecanoverridethegenfsconcontextwiththemountoption,context=<context>.Infact,ifwelookatdmesg,wecanseesomegreatmessages.Whenwemountedramfswithoutthecontextoption,wegot:
<7>SELinux:initialized(devramfs,typeramfs),usesgenfs_contexts
Whenwemounteditwiththecontext=<context>option,wegot:
<7>SELinux:initialized(devramfs,typeramfs),usesmountpointlabeling
WecanseethatSELinuxgivesussomehelpfulmessageswhiletryingtofigureoutfromwhereitsourcesitslabels.
Now,let’sgoontolabelingfilesystemswiththexattrsupport,suchasext4.Wewillstartwiththetoolboxcommand,chcon.Thechconcommandallowsyoutosetthecontextofafilesystemobjectexplicitly,itdoesnotconsultfile_contexts.
Let’stakealookat/system/binandinit,atthefirst10files:
$adbshellls-laZ/system/bin|head-n10
-rwxr-xr-xrootshellu:object_r:system_file:s0InputDispatcher_test
-rwxr-xr-xrootshellu:object_r:system_file:s0InputReader_test
-rwxr-xr-xrootshellu:object_r:system_file:s0abcc
-rwxr-xr-xrootshellu:object_r:system_file:s0adb
-rwxr-xr-xrootshellu:object_r:system_file:s0am
-rwxr-xr-xrootshellu:object_r:zygote_exec:s0app_process
-rwxr-xr-xrootshellu:object_r:system_file:s0applypatch
-rwxr-xr-xrootshellu:object_r:system_file:s0applypatch_static
drwxr-xr-xrootshellu:object_r:system_file:s0asan
-rwxr-xr-xrootshellu:object_r:system_file:s0asanwrappe
Wecanseethatmanyofthemhavethesystem_filelabel,whichisthedefaultlabelforthatfilesystem;let’schangetheamtypetoam_exec.Again,weneedtocreateanewtypebyaddingthefollowingtosepolicyfile,file.te:
typeam_exec,file_type;
Now,rebuildthepolicyfile,pushittotheUDOO,andtriggerareload.Afterthat,let’sstartremountingthesystem,sinceitisreadonly:
root@udoo:/#mount-orw,remount/system
Nowperformchcon:
root@udoo:/#chconu:object_r:am_exec:s0/system/bin/am
Verifytheresult:
root@udoo:/#la-laZ/system/bin/am
-rwxr-xr-xrootshellu:object_r:am_exec:s0am
Additionally,therestoreconcommandwillusefile_contexts,andrestorethatfiletowhatissetinthefile_contextsfile,whichshouldbesystem_file:
root@udoo:/#restorecon/system/bin/am
root@udoo:/#la-laZ/system/bin/am
www.it-ebooks.info
-rwxr-xr-xrootshellu:object_r:system_file:s0am
Asyoucansee,restoreconwasabletoconsultfile_contextsandrestorethespecifiedcontextonthatobject.
TheAndroidsystem’sfilesystemgetsconstructedduringthebuildtime,andconsequently,allitsfileobjectsarelabeledduringthatprocess.Wecanalsochangethisatbuildtimebychangingfile_contexts.Withthischanged,thesystempartitionrebuilt,andafterreflashingthesystem,weshouldseetheamfilewiththeam_exectype.Wecantestthisbyamendingthesepolicyfile,file_contextsbyaddingthislineattheendofthesystem/binsection:
/system/bin/amu:object_r:am_exec:s0
Rebuildthewholesystemwith:
$make-j82>&1|teelogz
Nowflashandreboot,andlet’stakealookatthe/system/bin/amcontextasfollows:
root@udoo:/#ls-laZ/system/bin/am
-rwxr-xr-xrootshellu:object_r:am_exec:s0am
Thisshowsthatthesystempartitionrespectsthefilecontextsforbuild-timelabeling,andhowwecancontroltheselabels.
www.it-ebooks.info
Fixingup/dataAdditionallyintheauditlogs,wehaveseenabunchofunlabeledfiles,forinstance,thefollowingdenial:
type=1400msg=audit(86559.780:344):avc:denied{append}forpid=2668
comm="UsbDebuggingHan"name="adb_keys"dev=mmcblk0p4ino=42
scontext=u:r:system_server:s0tcontext=u:object_r:unlabeled:s0tclass=file
Wecanseethatthedeviceismmcblk0p4,whichmountcommandsandwilltelluswhatfilesystemthisismountedto,initsoutput:
root@udoo:/#mount|grepmmcblk0p4
/dev/block/mmcblk0p4/dataext4
rw,seclabel,nosuid,nodev,noatime,nodiratime,errors=panic,user_x0
Sowhydoesthe/datafilesystemhavesomanyunlabeledfiles?ThereasonisthatSELinuxismeanttobeturnedonfromanemptydevice,thatis,fromfirstboot.Androidbuildsthedatadirectorystructuresondemand.Thus,allthelabelsforthe/dataarehandledbythefile_contextsfilesinceitisext4.Also,itishandledbythesystemsthatcreatethe/datafilesanddirectories.Thesesystemshavebeenmodifiedtolabelthedatapartitionbasedonthefile_contextsspecifications.Sothispresentstwooptions:wipe/dataandreboot,orrestorecon-R/data.
Optiononeisabitharsh,butifyouejecttheSDcardandremoveallthefilesonthedatapartition,partition4,Androidwillrebuildandyouwon’tseeanymoreunlabeledissues.However,thisisnotrecommendedfordeployeddeviceswhenyouupgrade;youwilldestroyalloftheusers’data.
Optiontwoismorepalatableindeployedscenarios,buthasitslimitations.Notably,executingrestorecon-R/datawilltakealongtimeandmustbedoneearlyinboot,rightafterthemount.However,thisisreallytheonlyoptionatthispoint.Google,however,hasdonealotofworkinthisarea,andcreatedasystemthatintelligentlyrelabels/dataonpolicyupdates.Forouruse,wewillchooseavariantofoptiontwo,especiallyafterconsideringhowsparselypopulatedthe/datafilesystemis;wereallyhaven’tinstalledorgeneratedalotofuserdatayet.Withthatstated,execute:
root@udoo:/#restorecon-R/data
root@udoo:/#reboot
Wedon’thavetoexecuterestoreconearlyinbootsinceoursystemisinpermissivemode,andwe’renotinadeployedscenario.Now,let’spulltheaudit.logfileandcompareittothealreadypulledaudit.log:
$adbpull/data/misc/audit/audit.logaudit_data_relabel.log
170KB/s(14645bytesin0.084s)
Let’susegreptocountthenumberofoccurrencesineachfile:
$grep-cunlabeledaudit.log
185
$grep-cunlabeledaudit_data_relabel.log
www.it-ebooks.info
AsidenoteonsecurityNotethateventhoughwearerunningallthesecommandsandchangingallthesethings,thisisnotasecurityvulnerabilitywithinSELinux.Beingabletochangetypelabels,mountingfilesystems,andassociatingfilesystemswithatype,allrequireallowrules.Ifyoulookthroughtheauditlogs,you’llseeaslewofdenials;asampleisprovided:
type=1400msg=audit(90074.080:192):avc:denied{associate}forpid=3211
comm="touch"name="foo"scontext=u:object_r:ramdisk_newfile:s0
tcontext=u:object_r:ramdisk:s0tclass=filesystem
type=1400msg=audit(90069.120:187):avc:denied{mount}forpid=3205
comm="mount"name="/"dev=ramfsino=1992scontext=u:r:init_shell:s0
tcontext=u:object_r:ramdisk:s0tclass=filesystem
Ifwewereinanenforcingmode,wewouldn’thavebeenabletoperformanyoftheexperimentsshownhere.
www.it-ebooks.info
SummaryInthischapter,wesawhowtogetfilesintocontextsbyrelabelingthem.Weusedavarietyoftechniquestoaccomplishthistask,fromtoolboxcommandssuchaschconandrestorecon,tomountoptionsanddynamictransitions.Withthesetools,wecanensurethatallfilesystemobjectsarelabeledcorrectly.Thisway,weendupwiththerighttargetcontextssothatthepoliciesweauthorareeffective.Inthenextchapter,wewillfocusontheprocesses,makingsurethattheyareintherightdomainorcontext.
www.it-ebooks.info
Chapter9.AddingServicestoDomainsInthepreviouschapter,wecoveredtheprocessofgettingfileobjectsintheproperdomain.Inmostcases,thefileobjectisthetarget.However,inthischapter,wewill:
Emphasizelabelingprocesses—notablyAndroidservicesrunandmanagedbyinitManagetheancillaryassociatedobjectscreatedbyinit
www.it-ebooks.info
Init–thekingofdaemonsTheinitprocessisvitalinaLinuxsystem,andAndroidisnotspecialinthiscase.However,Androidhasitsownimplementationofinit.Initisthefirstprocessonthesystem,andthushasaProcessID(PID)of1.Allotherprocessesaretheresultofadirectfork()frominit,thusallprocesseseventuallyareparentedunderinit,eitherdirectlyorindirectly.Initisresponsibleforcleaningupandmaintainingtheseprocesses.Forinstance,anychildprocesswhoseparentdiesisreparentedunderinitbythekernel.Inthisway,initcancallwait()(man2waitformoredetails)tocleanupaftertheprocesswhenitexits.
NoteAprocesswhichhasterminatedbuthasnothadwait()calledisazombieprocess.Thekernelmustkeeptheprocessdatastructuresarounduntilthiscall.Failingtodosowillconsumememoryindefinitely.
Sinceinitistherootofallprocesses,italsoprovidesamechanismtodeclareandexecutecommandsthroughitsownscriptinglanguage.Filesusingthislanguagetocontrolinitarereferredtoasinitscripts,andwehavealreadymodifiedsomeofthem.Inthesourcetree,weusedtheinit.rcfile,whichyoucanreachbynavigatingtodevice/fsl/imx6/etc/init.rc,butonthedevice,itispackagedwiththeramdiskat/init.rc,andismadeavailabletoinit,whichisalsopackagedintheramdiskat/init.
Toaddaservicetotheinitscript,youcanmodiheinit.reandaddadeclaration,asfollows:
service<name><path>[<argument>...]
Here,nameistheservicename,pathisthepathtotheexecutable,andargumentarespacedelimitedargumentstringstobedeliveredtotheexecutableinitsargvarray.
Forexample,hereistheservicedeclarationforrild,theRadioInterfaceLayerDaemon(RILD):
Serviceril-daemon/system/bin/rild
Itisoftenthecasethatadditionalserviceoptionscanandneedtobeadded.Theinitscriptservicestatementsupportsarichassortmentofoptions.Forthecompletelist,refertotheinformationalfilelocatedatsystem/core/init/readme.txt.Additionally,wecoveredtheSEforAndroid-specificchangesinChapter3,AndroidIsWeird.
Continuingtodissectrild,weseethattherestofthedeclarationintheUDOOinit.rcisasfollows:
Serviceril-daemon/system/bin/rild
classmain
socketrildstream660rootradio
socketrild-debugstream660radiosystem
socketrild-pppstream660radiosystem
userroot
www.it-ebooks.info
groupradiocacheinetmiscaudiosdcard_rwlog
Theinterestingthingtonotehereisthatitcreatesquiteafewsockets.Thesocketkeywordininit.rcisdescribedbythereadme.txtfile:
NoteFromthesourcetreefilesystem/core/init/readme.txt:
socket<name><type><perm>[<user>[<group>[<context>]]]
CreateaUnixdomainsocketnamed/dev/socket/<name>andpassitsfdtothelaunchedprocess.Thetypemustbedgram,stream,orseqpacket.TheuserandgroupIDsdefaultto0.TheSELinuxsecuritycontextforthesocketiscontext.Itdefaultstotheservicesecuritycontext,asspecifiedbyseclabel,oriscomputedbasedontheserviceexecutablefile’ssecuritycontext.
Let’stakealookatthisdirectoryandseewhatwe’vefound.
root@udoo:/dev/socket#ls-laZ|grepadb
srw-rw----systemsystemu:object_r:adbd_socket:s0adbd
Thisraisesthequestion,“Howdiditgetintothatdomain?”Usingourknowledgefromthepreviouschapter,weknowthat/devisatmpfs,soweknowthatitdidnotenterthisdomainthroughxattrs.Itmustbeeitheracodemodificationoratypetransition.Let’scheckwhetherit’satypetransition.Ifitis,wewouldexpecttoseeastatementintheexpandedpolicy.conf.SELinuxpolicyisbasedonthem4macrolanguage.Duringbuilds,itisexpandedintopolicy.conf,andthencompiled.Chapter12,MasteringtheToolChain,hasmoredetailsonthis.
Wecandiscoverthisbyusingsesearchtofindtypetransitionsforadbd_socket:
$sesearch-T-tadbd_socket$OUT/sepolicy
Asyoucanseefromtheemptyoutput,therearezerosuchlines,soit’snotthepolicywhichisdoingthisbutacodechange.
InLinux,processesarecreatedwithfork()followedbyexec().Becauseofthis,weareabletoaffordgreatkeywordstosearchtheinitdaemon.Wesuspectthatthecodetosetupthesocketisjustafteracalltofork()inthechildprocessesandbeforeacalltoexec():
$grep-nforksystem/core/init/init.c
235:pid=fork();
So,theforkwearesearchingforisonline235ofinit.c;let’sopeninit.cinatexteditorandtakealook.Wewillfindthefollowingsnippettoexamine:
...
NOTICE("starting'%s'\n",svc->name);
pid=fork();
if(pid==0){
structsocketinfo*si;
structsvcenvinfo*ei;
www.it-ebooks.info
chartmp[32];
intfd,sz;
umask(077);
if(properties_inited()){
get_property_workspace(&fd,&sz);
sprintf(tmp,"%d,%d",dup(fd),sz);
add_environment("ANDROID_PROPERTY_WORKSPACE",tmp);
}
for(ei=svc->envvars;ei;ei=ei->next)
add_environment(ei->name,ei->value);
for(si=svc->sockets;si;si=si->next){
intsocket_type=(
!strcmp(si->type,"stream")?SOCK_STREAM:
(!strcmp(si->type,"dgram")?SOCK_DGRAM:SOCK_SEQPACKET));
ints=create_socket(si->name,socket_type,
si->perm,si->uid,si->gid,si->socketcon?:scon);
if(s>=0){
publish_socket(si->name,s);
}
...
Accordingtoman2fork,thereturncodeoffork()inthechildprocessis0.Thechildprocessexecuteswithinthisifstatementandtheparentskipsit.Thefunctioncreate_socket()alsoseemsinteresting.Itappearstotakethenameoftheservice,thetypeofsocket,permissionsflags,uid,gid,andsocketcon.Whatissocketcon?Let’scheckwhetherwecantracebacktowhereitisset.
Ifwelookbeforefork(),wecanseethattheparentprocessgetsitssconbasedontwofactors:
...
if(svc->seclabel){
scon=strdup(svc->seclabel);
if(!scon){
ERROR("Outofmemorywhilestarting'%s'\n",svc->name);
return;
}
}else{
...
Thefirstpaththroughtheifstatementoccurswhensvc->seclabelisnotnull.Thissvcstructureispopulatedwiththeoptionsthatcanbeassociatedwithaservice.AsarefresherfromChapter3,AndroidIsWeird,seclabelletsyouexplicitlysetthecontextonaservice,hardcodedtothevalueininit.rc.Theelseclauseisabitmoreinvolvedandinteresting.
Intheelseclause,wegetthecontextofthecurrentprocessbycallinggetcon().Thisfunction,sincewe’rerunningininit,shouldreturnu:r:init:s0andstoreitinmycon.Thenextfunction,getfilecon()ispassedthepathoftheexecutable,andchecksthecontextofthefileitself.Thethirdfunctionistheworkhorsehere:security_compute_create().
www.it-ebooks.info
Thistakesthemycon,fcon,andtargetclassandcomputesthesecuritycontext,scon.Giventheseinputs,ittriestodetermine,basedonpolicytypetransitions,whattheresultingdomainforthechildshouldbe.Ifnotransitionsaredefined,sconwillbethesameasmycon.
Aconditionalexpressionwithinthecreate_socket()functionadditionallydeterminesthesocketcontextpassed.Thevariablesiisastructurethatcontainsalltheoptionstothesocketstatementintheinitservicesection.Asspecifiedbythereadme.txtfile,si->socketconisthesocketcontextargument.Inotherwords,thesocketcontextcancomefromoneofthreeplaces(indescendingpriority):
ThesocketconoptiononthesocketoptionintheservicedeclarationTheseclabeloptionontheservicekeywordDynamicallycomputedfromsourceandtargetcontexts
Thesocketcontextispassedtocreate_socket().Now,let’slookatcreate_socket().Thisfunctionisdefinedatsystem/core/init/util.c:87.Thesnippetsofcodearoundsocket()seeminteresting:
...
if(socketcon)
setsockcreatecon(socketcon);
fd=socket(PF_UNIX,type,0);
if(fd<0){
ERROR("Failedtoopensocket'%s':%s\n",name,strerror(errno));
return-1;
}
if(socketcon)
setsockcreatecon(NULL);
...
Thesetsockcreatecon()functionsetstheprocess’socketcreationcontext.Thismeansthatthesocketcreatedbythesocket()callwillhavethecontextsetviasetsockcreatecon().Afterit’screated,theprocessresetsittotheoriginalbyusingsetsockcreatecon(NULL).
Thenextbitofinterestingcodeisaroundbind():
...
filecon=NULL;
if(sehandle){
ret=selabel_lookup(sehandle,&filecon,addr.sun_path,S_IFSOCK);
if(ret==0)
setfscreatecon(filecon);
}
ret=bind(fd,(structsockaddr*)&addr,sizeof(addr));
if(ret){
ERROR("Failedtobindsocket'%s':%s\n",name,strerror(errno));
gotoout_unlink;
}
www.it-ebooks.info
setfscreatecon(NULL);
freecon(filecon);
...
Here,wehavesetthefilecreationcontext.Thefunctionsareanalogoustosetsock_creation(),butworkforfilesystemobjects.However,theselabel_lookup()functionlooksinfile_contextsforthecontextofthefile.Thepartyoumightbemissingisthatthecalltobind(),forpath-basedsockets,createsafileatthepathspecifiedinsockaddr_unstruct.So,thesocketobjectandthefilesystemnodeentryaredistinctlyseparatethingsandcanhavedifferentcontexts.Typically,thesocketbelongstotheprocess’context,andthefilesystemnodeisgivensomeothercontext.
www.it-ebooks.info
DynamicdomaintransitionsWesawinitcomputingofthecontextsfortheinitsockets,butweneverencountereditwhilesettingthedomainsforchildprocesses.Inthissection,wewilldiveintothetwotechniquestodoso:explicitsettingwithaninitscriptandsepolicydynamicdomaintransitions.
Thefirstwaytothedomainsforchildprocessesiswiththeseclabelstatementintheinitscriptservicedeclaration.Withinthechildprocessesexecutionafterfork(),wefindthisstatement:
if(svc->seclabel){
if(is_selinux_enabled()>0&&setexeccon(svc->seclabel)<0){
ERROR("cannotsetexeccon('%s'):%s\n",svc->seclabel,strerror(errno));
_exit(127);
}
}
Toclarify,thesvcvariableisthestructurethatcontainstheserviceoptionsandarguments,sosvc->seclabelisseclabel.Ifit’sset,itcallssetexeccon(),whichsetstheprocess’executioncontextforanythingitexecutesviaexec().Furtherdown,weseethattheexec()functioncallsaremade.Theexec()syscallneverreturnsonsuccess;itonlyreturnsonfailure.
Theotherwaytosetthedomainsforchildprocesses,whichisthepreferredway,isbyusingsepolicy.It’spreferredbecausethepolicyhasnodependenciesonanythingelse.Byhardcodingacontextintoinit,you’recouplingadependencybetweentheinitscriptandthesepolicy.Forinstance,ifthesepolicyremovesatypethatwashardcodedintheinitscript,theinitsetconwillfail,butbothsystemswillcompilecorrectly.Ifyouremoveatypeforatypetransitionandleavethetransitionstatement,youcancatchtheerroratcompiletime.Sincewelookedattherildservicestatement,let’slookattherild.tepolicyfilelocatedinsepolicy.Weshouldsearchforthetype_transitionkeywordinthisfileusinggrep:
$grep-ctype_transitionrild.te
0
Noinstancesoftype_transitionarefound,butthiskeywordmustexist,similartofiles.However,itcanbehiddeninanunexpandedmacro.TheSELinuxpolicyfilesareinthem4macrolanguage,andtheygetexpandedpriortobeingcompiled.Let’slookthroughrild.teandcheckwhetherwecanfindsomemacros.Theyaredistinguishedandlooklikefunctionswithparameters.Thefirstmacrowecomeacrossistheinit_daemon_domain(rild)macro.Now,weneedtofindthismacro’sdefinitioninsepolicy.Them4languageusesthedefinekeywordtodeclaremacros,sowecansearchforthat:
$grep-ninit_daemon_domain*|grepdefine
te_macros:99:define(`init_daemon_domain',`
Ourmacroisdeclaredinte_macros,whichcoincidentallyholdsallthemacrosrelatedto
www.it-ebooks.info
typeenforcement(TE).Let’stakealookatwhatthismacrodoesinmoredetail.First,itsdefinitionis:
...
#####################################
#init_daemon_domain(domain)
#Setupatransitionfrominittothedaemondomain
#uponexecutingitsbinary.
define(`init_daemon_domain',`
domain_auto_trans(init,$1_exec,$1)
tmpfs_domain($1)
')
...
Thecommentedlinesintheprecedingcode(linesstartingwith#inm4),statethatitsetsupatransitionfrominittothedaemondomain.Thissoundslikesomethingwewant.However,boththeencompassingstatementsaremacros,andweneedtorecursivelyexpandthem.Wewillstartwithdomain_auto_trans():
...
#####################################
#domain_auto_trans(olddomain,type,newdomain)
#Automaticallytransitionfromolddomaintonewdomain
#uponexecutingafilelabeledwithtype.
#
define(`domain_auto_trans',`
#Allowthenecessarypermissions.
domain_trans($1,$2,$3)
#Makethetransitionoccurbydefault.
type_transition$1$2:process$3;
')
...
Thecommenthereindicatesthatweareheadedintheproperdirection;however,weneedtokeepexpandingmacrosinoursearch.Accordingtothecomment,thedomain_trans()macroallowsjustthetransitiontooccur.RememberthatalmosteverythinginSELinuxneedsexplicitpermissionfromthepolicyinordertohappen,includingtypetransitions.Thelaststatementinthemacroistheoneweweresearchingfor:
type_transition$1$2:process$3;
Ifyouexpandthisstatementout,you’llget:
type_transitioninitrild_exec:processrild;
Whatthisstatementconveysisthatifyoumakeanexec()syscallonafilewiththetyperild_exec,andtheexecutingdomainisinit,thenmakethechildprocess’domainrild.
www.it-ebooks.info
ExplicitcontextsviaseclabelTheotheroptionforsettingcontextsisverystraightforward.It’shardcodingthemwiththeinitscriptintheservicedeclaration.Intheservicedeclaration,aswesawinChapter3,AndroidIsWeird,thereweremodificationstotheinitlanguage.Oneoftheadditionsisseclabel.Thisoptionjustletsinitexplicitlychangethecontextoftheservicetotheargumentgiventoseclabel.Hereisanexampleofadbd:
Serviceadbd/sbin/adbd
classcore
socketadbdstream660systemsystem
disabled
seclabelu:r:adbd:s0
Sowhyusedynamictransitionsonsomeandseclabelonothers?Theanswerisdependentonwhereyou’reexecutingfrom.Thingssuchasadbdexecuteearlyonfromtheramdisk,andsincetheramdiskreallydoesn’tuseperfilelabels,youcan’tsetuptransitionsproperly—thetargethasthesamecontext.
www.it-ebooks.info
RelabelingprocessesNowthatwearearmedwithdynamicprocesstransitions,andtheabilitytosetsocketcontextsfrominitscriptsisneeded.Let’sattempttorelabeltheservicesthatareinimpropercontexts.Wecantellifthey’reimproperbycheckingthemagainstthefollowingrules:
NootherprocessbutinitshouldbeintheinitcontextNolongrunningprocessshouldbeintheinit_shelldomainNothingbutzygoteshouldbeinthezygotedomain
NoteAmorecomprehensivetestsuiteispartofCTSonAOSP.RefertotheAndroidCTSprojectformoredetails:(gitclone)https://android.googlesource.com/platform/cts.Takenoteofthe./hostsidetests/security/src/android/cts/security/SELinuxHostTest.javaand./tests/tests/security/src/android/security/cts/SELinux.*.javatests.
Let’srunsomebasiccommandsandevaluatethestatusofourUDOOovertheadbconnection:
$adbshellps-Z|grepinit
u:r:init:s0root10/init
u:r:init:s0root22671/sbin/watchdogd
u:r:init_shell:s0root22781/system/bin/sh
$adbshellps-Z|grepzygote
u:r:zygote:s0root22851zygote
Wehavetwoprocessesintheimproperdomains.Thefirstiswatchdogd,andthesecondisashprocess.Weneedtofindtheseandcorrectthem.
Wewillstartwiththemysteryshprogram.Asyoucanrecallfromthepreviouschapter,ourUDOOserialconsoleprocesshadthecontextofinit_shell,sothisisagoodsuspect.Let’scheckPIDsandfindout.FromaUDOOserialconsoleexecute:
root@udoo:/#echo$$
2278
WecancomparethisPIDtothePIDfieldintheadbshellpsoutputhere(PIDfieldisthethirdfield,index2),andasyoucansee,wehaveamatch.
Fromthere,weneedtofindtheservicedeclarationforthis.Weknowthatitisininit.rcsinceit’srunningininit_shell,atypethatcanonlybetransitionedtobyinitdirectlyaspertheSELinuxpolicy.Also,initonlystartsprocessingthingsbyservicedeclarations,soinordertobeininit_shell,youmuststartbyinitviaaservicedeclaration.
NoteUsesesearchtofindoutsuchthingsonthecompiledsepolicybinary:
$sesearch-T-sinit-tshell_exec-cprocess$OUT/root/sepolicy
www.it-ebooks.info
Ifwesearchinit.rcfortheUDOO,whichisinudoo/device/fsl/imx6/etc,wecangrepitscontentsfor/system/bin/sh,thecommandinquestion.Ifwedothat,wewillfind:
$grep-n"/system/bin/sh"init.rc
499:serviceconsole/system/bin/sh
702:servicewifi_mac/system/bin/sh/system/etc/check_wifi_mac.sh
Let’slookat499sincewedon’thaveanythingtodowithWi-Fi:
serviceconsole/system/bin/sh
classcore
console
userroot
grouproot
Ifthisistheserviceinquestion,weshouldbeabletodisableit,andverifythatourserialconnectionnolongerworks:
$adbshellsetpropctl.stopconsole
Myliveserialconnectiondiedat:
root@udoo:/#avc:denied{set}forproperty=ctl.console
scontext=u:r:shell:s0tcontext=u:e
Nowthatwehaveverifiedwhatitis,wecanstartitbackup:
$adbshellsetpropctl.startconsole
Withthesystembackinaworkingstate,wenowneedtoaddressthebestwaytocorrectthelabelonthisservice.Wehavetwooptions:
Usinganexplicitseclabelentryininit.rcUsingatypetransition
Theoptionwewillusehereisthefirst.Thereasonisbecauseinitexecutesshellfromtimetotime,andwedon’twantalloftheseintheconsoleprocessesdomain.Wewantleastprivilegetosegregatetherunningprocesses.Byusingtheexplicitseclabel,wewon’tchangeanyoftheothershellsthatareexecutedalongtheway.
Todothis,weneedtomodifytheinit.rcentryforconsole;add:
serviceconsole/system/bin/sh
classcore
console
userroot
grouproot
seclabelu:r:shell:s0
Theproperdomainforthisexecutableisshell,sinceitshouldhavethesamepermissionsetasadbshell.Afteryoumakethischange,recompilethebootimage,flash,andthenreboot.Wecanseethatitisnowinashelldomain.Toverify,executethefollowingfromaUDOOserialconnection:
root@udoo:/#id-Z
www.it-ebooks.info
uid=0(root)gid=0(root)context=u:r:shell:s0
Alternatively,executethefollowingcommandusingadb:
$adbshellps-Z|grep"system/bin/sh"
u:r:shell:s0root22791/system/bin/sh
Thenextoneweneedtotakecareofiswatchdogd.Thewatchdogdprocessalreadyhasadomainandallowsrulesinwatchdog.te;sowejustneedtoaddaseclabelstatementandgetitintothisproperdomain.Modifyinit.rc:
#Setwatchdogtimerto30secondsandpetitevery10secondstogeta20
secondmargin
servicewatchdogd/sbin/watchdogd1020
classcore
seclabelu:r:watchdogd:s0
Toverifyusingadb,executethefollowingcommand:
$adbshellps-Z|grepwatchdog
u:r:watchdogd:s0root22671/sbin/watchdogd
Atthispoint,wehavemadeactualpolicycorrectionsthattheUDOOwasinneedof.However,weneedtopracticetheuseofdynamicdomaintransitions.Agoodteachingexamplewouldhavesubshellsfromashellintheirowndomain.Let’sstartbydefininganewdomainandsettingupthetransition.
Wewillcreateanew.tefileinsepolicycalledsubshell.te,andedititsothatitscontentscontainthefollowing:
typesubshell,domain,shelldomain,mlstrustedsubject;
#domain_auto_trans(olddomain,type,newdomain)
#Automaticallytransitionfromolddomaintonewdomain
#uponexecutingafilelabeledwithtype.
#
domain_auto_trans(shell,shell_exec,subshell)
Now,themmmtrickusedearlierinthebookcanbeusedtocompilejustthepolicyAlso,useadbpushcommandtopushthenewpolicyto/data/security/current/sepolicyandexecutesetproptoreloadthepolicy,justaswedidinChapter8,ApplyingContextstoFiles.
Totestthis,weshouldbeabletotypesh,andverifythedomaintransition.Wewillstartbygettingourcurrentcontext:
root@udoo:/#id-Z
uid=0(root)gid=0(root)context=u:r:shell:s0
Thenexecuteashellbydoing:
root@udoo:/#sh
root@udoo:/#id-Z
uid=0(root)gid=0(root)context=u:r:subshell:s0
Wewereabletouseadynamictypetransitiontogetanewprocessinadomain.Ifyoucouplethiswithlabelingfiles,aspresentedinChapter8,ApplyingContextstoFiles,you
www.it-ebooks.info
LimitationsonapplabelingAfundamentallimitationofthesedynamicprocesstransitionsisthattheyrequireanexec()systemcalltobemade.OnlythencanSELinuxcomputethenewdomain,andtriggerthecontextswitch.Theonlyotherwaytodothisisbymodifyingthecode,whichessentiallyiswhatinitisdoingwhenyouspecifyseclabel().Theinitcodesetstheexeccontextforitsprocess,causingthenextexectoendupinthespecifieddomain.Infact,wecanseethisintheinit.ccode:
if(svc->seclabel){
if(is_selinux_enabled()>0&&setexeccon(svc->seclabel)<0){
ERROR("cannotsetexeccon('%s'):%s\n",svc->seclabel,strerror(errno));
_exit(127);
}
}
Here,thechildprocessgetsitsexecutecontextsetbyacalltosetexeccon()beforetheexec()systemcallhandsovercontroltoanewbinaryimage.InAndroid,applicationsarenotspawnedthisway,andnoexec()syscallexistsintheprocesscreationpath;soanewmechanismwillbeneeded.
www.it-ebooks.info
SummaryInthischapter,welearnedhowtolabelprocessesviatypetransitionsaswellasviatheseclabelstatements.Wealsoinvestigatedhowinitmanagesservicesockets,andhowtoproperlylabelthem.Wethencorrectedtheprocesscontextsfortheserialconsoleaswellasthewatchdogdaemon.
ApplicationsinAndroidneverhaveanexplicitcalltoexec()tostarttheirprogramexecution.Sincethereisnoexec(),wehavetolabelapplicationswithacodechange.Inthenextchapter,wewilladdresshowthishappens,andhowapplicationsgetlabeled.
www.it-ebooks.info
Chapter10.PlacingApplicationsinDomainsInChapter3,AndroidIsWeird,weintroducedthezygoteandthatallapplications,APKsinAndroidspeak,emanatefromthezygotejustlikeservicesemanatefromtheinitprocess.Assuch,theyneedtobelabeled,aswedidinthepreviouschapter.Recallthatlabelingisthesameasplacingaprocessinadomainofthatlabel.Applicationsneedtobelabeledaswell.
NoteAPKisthefileextensionandformatforinstallableapplicationpackagesonAndroid.It’sanalogoustothedesktoppackageformatslikeRPM(Redhatbased)orDEB(Debianbased).
Inthischapter,wewilllearnto:
ProperlylabelapplicationprivatedatadirectoriesandtheirruntimecontextsFurtherexaminezygoteandmethodstosecureitDiscoverhowafinishedmac_permssions.xmlfileassignsseinfovalueCreateanewcustomdomain
www.it-ebooks.info
ThecasetosecurethezygoteAndroidapplicationswithelevatedpermissionsandcapabilitiesarespawnedfromthezygote.Anexampleofthisisthesystemserver,alargeprocesscomprisedofnativeandnon-nativecodehostingavarietyofservices.Thesystemserverhousestheactivitymanager,packagemanager,GPSfeedsandsoon.ThesystemserveralsorunswithahighlysensitiveUIDofsystem(1000).Also,manyOEMspackagewhatareknownassystemapps,whicharestandaloneapplicationsrunningwiththesystemUID.
Thezygotealsospawnsapplicationsthatdonotneedelevatedpermissions.Allthird-partyapplicationsrepresentthis.ThirdpartyapplicationsrunastheirownUID,separatefromsensitiveUIDs,suchassystem.Additionally,applicationsgetspawnedintovariousUIDssuchasmedia,nfc,andsoon.OEMstendtodefineadditionalUIDs.
It’simportanttonotethattogetintoaspecialUID,likesystem,youmustbesignedwiththeproperkey.Androidhasfourmajorkeysusedtosignapplications:media,platform,shared,andtestkey.Theyarelocatedinbuild/target/product/security,alongwithaREADME.
AccordingtotheREADME,thekeyusageisasfollows:
testkey:Agenerickeyforpackagesthatdonototherwisespecifyakey.platform:Atestkeyforpackagesthatarepartofthecoreplatform.shared:Atestkeyforthingsthataresharedinthehome/contactsprocess.media:Atestkeyforpackagesthatarepartofthemedia/downloadsystem.
InordertorequestsystemUIDforyourapplication,youmustbesignedwiththeplatformkey.Possessionoftheprivatekeyisrequiredtoexecuteinthesemoreprivilegedenvironments.
Asyoucansee,wehaveapplicationsexecutingatavarietyofpermissionlevels,andtrustlevels.Wecannottrustthirdpartyapplicationssincetheyarecreatedbyunknownentities,andwecantrustthingssignedwithourprivatekeys.However,beforeSELinux,applicationpermissionswerestillboundbythesameDACpermissionlimitationsasthoseidentifiedinChapter1,LinuxAccessControls.Becauseoftheseproperties,itmakesthezygoteaprimetargetforattack,aswellasfortificationwithSELinux.
www.it-ebooks.info
FortifyingthezygoteNowthatwehaveidentifiedaproblemwithzygote,thenextstepisunderstandinghowtogetapplicationsintoappropriatedomains.WeneedeitherSELinuxpolicyorcodechangestoplacenewprocessesintoadomain.InChapter9,AddingServicestoDomains,wecovereddynamicdomaintransitionswithinit-basedservicesandtheendofthechaptermentionstheimportanceoftheexec()syscallinthe“LimitationsonAppLabeling”section.Thisisthetriggeronwhichdynamicdomaintransitionsoccur.Ifthereisnoexecinthepath,wewouldhavetorelyoncodechanges.However,onealsohastoconsiderthesigningkeyinthissecuritymodel,andthereisnowayinpureSELinuxpolicylanguagetoexpressthekeytheprocesswassignedwith.
Ratherthanexploringthewholezygote,wecandissectthefollowingpatchesthatintroduceapplicationlabelingintoAndroid.Additionally,wecandiscoverhowtheintroduceddesignmeetstherequirementsofrespectingthesigningkey,workingwithinthedesignofSELinuxandthezygote.
www.it-ebooks.info
PlumbingthezygotesocketInChapter3,AndroidIsWeird,welearnedthatthezygotelistensforrequeststospawnanewapplicationfromasocket.Thefirstpatchtoexamineishttps://android-review.googlesource.com/#/c/31066/.ThispatchmodifiesthreefilesinthebaseframeworksofAndroid.ThefirstfileisProcess.javainthemethodstartViaZygote().ThismethodisthemainentrypointforothermethodswithrespecttobuildingstringargumentsandpassingthemtothezygotewithzygoteSendArgsAndGetResult().Thepatchintroducesanewargumentcalledseinfo.Lateron,wewillseehowthisgetsused.Itappearsthatthispatchisplumbingthisnewseinfoargumentoverthesocket.Notethatthiscodeiscalledexternaltothezygoteprocess.
ThenextfiletolookatinthispatchisZygoteConnection.java.Thiscodeexecutesfromwithinthecontext.ThepatchstartsoffbydeclaringastringmembervariablepeerContextintheZygoteConnectionclass.Intheconstructor,thispeerContextmemberissettothevalueobtainedfromacalltoSELinux.getPeerContext(mSocket.getFileDescriptor()).
SincetheLocalSocketmSocketisaUnixdomainsocketunderthehood,youcanobtaintheconnectedclient’scredentials.Inthiscase,thecalltogetPeerContext()getstheclient’ssecuritycontext,orinmoreformalterms,theprocesslabel.Aftertheinitialization,furtherdowninmethodrunOnce(),weseeitbeingusedincallstoapplyUidSecurityPolicyandotherapply*SecurityPolicyroutines.TheprotectedmethodrunOnce()iscalledtoreadonestartcommandfromthesocketandarguments.Eventually,aftertheapply*SecurityPolicychecks,itcallsforkandSpecialize().EachsecuritypolicycheckhasbeenmodifiedtouseSELinuxontopoftheexistingDACsecuritycontrols.IfwereviewapplyUidSecurityPolicy,weseetheymakethecall:
booleanallowed=SELinux.checkSELinuxAccess(peerSecurityContext,
peerSecurityContext,"zygote","specifyids");
Thisisanexampleofauserspaceleveragingmandatoryaccesscontrolsinwhatisknownasanobjectmanager.Additionally,asecuritycheckhasbeenaddedforthemysteriousseinfostringintheapplyseInfoSecurityPolicy()method.AllthesecuritycheckshereforSELinuxspecifythetargetclasszygote.Soifwelookintosepolicyaccess_vectors,weseetheaddedclasszygote.ThisisacustomclassforAndroidanddefinesallthevectorscheckedinthesecuritychecks.
Thelastfilewe’llconsiderfromthispatchisActivityManagerService.java.TheActivityManagerisresponsibleforstartingapplicationsandmanagingtheirlifecycles.It’saconsumeroftheProcess.startAPIandneedstospecifyseinfo.Thispatchissimple,andfornow,justsendsnull.Later,wewillseethepatchenablingitsuse.
Thenextpatch,https://android-review.googlesource.com/#/c/31063/,executeswithinthecontextoftheAndroidDalvikVMandiscodedintheVMzygoteprocessspace.TheforkAndSpecialize()wesawinZygoteConnectionendsupinthisnativeroutine.Itentersusingstaticpid_tforkAndSpecializeCommon(constu4*args,boolisSystemServer).Thisroutineisresponsibleforcreatingthenewprocessthatbecomes
www.it-ebooks.info
theapplication.
ItbeginswithhousekeepingcodemovingfromJavatoCandsetsuptheniceNameandseinfovaluesasC-stylestrings.Eventually,thecodecallsfork()andthechildprocessstartsdoingthings,likeexecutingsetgidandsetuid.TheuidandgidvaluesarespecifiedtothezygoteconnectionwiththeProcess.startmethod.WealsoseeanewcalltosetSELinuxContext().Asanaside,theorderoftheseeventsisimportanthere.IfyousettheSELinuxcontextofthenewprocesstooearly,theprocesswouldneedadditionalcapabilitiesinthenewcontexttodothingslikesetuidandsetgid.However,thosepermissionsarebestlefttothezygotedomain,sotheapplicationdomainweenteredcanbeasminimalaspossible.
Continuing,setSELinuxContexteventuallycallsselinux_android_setcontext().NotethattheHAVE_SELINUXconditionalcompilationmacroswereremovedafterthiscommit,butpriortothe4.3release.Alsonotethatselinux_android_setcontext()isdefinedinlibselinux,soourjourneywilltakeusthere.Hereweseethemysteriousseinfoisstillbeingpassedalong.
Thenextpatchtoevaluateishttps://android-review.googlesource.com/#/c/39601/.ThispatchactuallypassesamoremeaningfulseinfovaluefromtheJavalayer.Ratherthanbeingsettonull,thispatchintroducessomeparsinglogicfromanXMLfile,andpassesthisalongtotheProcess.startmethod.
Thispatchmodifiestwomajorcomponents:PackageManagerandinstalld.PackageManagerrunsinsidethesystem_server,andperformsapplicationinstallation.Itmaintainsthestateofallinstalledpackagesinthesystem.Thesecondcomponent,aserviceknownasinstalld,isaveryprivilegedrootservicethatcreatesalltheapplications’privatedirectoriesondisk.Ratherthangivingsystemserver,andthereforePackageManager,thecapabilitytocreatethesedirectories,onlyinstalldhasthesepermissions.Usingthisapproach,eventhesystemservercannotreaddatainyourprivatedatadirectoriesunlessyoumakeitworldreadable.
Thispatchislargerthantheothers,soweareonlygoingtoinspectthepartsdirectlyrelevanttoourdiscussion.We’llstartbylookingatPackageManagerService.java.Thisclassisthepackagemanager,properforAndroid.IntheconstructorforPackageManagerService(),weseetheadditionofmFoundPolicyFile=SELinuxMMAC.readInstallPolicy();.
Basedonthenaming,wecanconjecturethatthismethodislookingforsometypeofpolicyconfigurationfile,andiffound,returnstrue,settingthemFoundPolicyFilemembervariable.WealsoseesomecallstocreateDataDirsandmInstaller.*calls.Thesewecanignore,sincethosecallsareheadedtoinstalld.
Thenextmajorportionaddsthefollowing:
if(mFoundPolicyFile){
SELinuxMMAC.assignSeinfoValue(pkg);
}
It’simportanttonotethatthiscodewasaddedintothescanPackageLI()method.This
www.it-ebooks.info
methodiscalledeverytimeapackageneedstobescannedforinstallation.Soatahighlevel,ifsomepolicyfileisfoundduringservicestartup,thenaseinfovalueisassignedtothepackage.
ThenextfiletolookatisApplicationInfo.java,acontainerclassformaintainingmetainformationaboutapackage.Aswecansee,theseinfovalueisspecifiedhereforstoragepurposes.Additionally,thereissomecodeforserializinganddeserializingtheclassviatheAndroidspecificParcelimplementation.
Atthispoint,weshouldhaveacloserlookattheSELinuxMMAC.javacodetoconfirmourunderstandingofwhat’sgoingon.Theclassstartsbydeclaringtwolocationsforpolicyfiles.
//Locationsofpotentialinstallpolicyfiles.
privatestaticfinalFile[]INSTALL_POLICY_FILE={
newFile(Environment.getDataDirectory(),"system/mac_permissions.xml"),
newFile(Environment.getRootDirectory(),
"etc/security/mac_permissions.xml"),
null};
Accordingtothis,policyfilescanexistintwolocations-/data/system/mac_permissions.xmland/system/etc/security/mac_permissions.xml.Eventually,weseethecallfromPackageManagerServiceinitializationtothemethoddefinedintheclassreadInstallPolicy(),whicheventuallyreducestoacallof:
privatestaticbooleanreadInstallPolicy(File[]policyFiles){
FileReaderpolicyFile=null;
inti=0;
while(policyFile==null&&policyFiles!=null&&policyFiles[i]!=
null){
try{
policyFile=newFileReader(policyFiles[i]);
break;
}catch(FileNotFoundExceptione){
Slog.d(TAG,"Couldn'tfindinstallpolicy"+
policyFiles[i].getPath());
}
i++;
}
...
WithpolicyFilessettoINSTALL_POLICY_FILE,thiscodeusesthearraytofindafileatthespecifiedlocations.Itisprioritybased,withthe/datalocationtakingprecedenceover/system.Therestofthecodeinthismethodlookslikeparsinglogicandfillsuptwohashtablesthatweredefinedintheclassdeclaration:
//Signatureseinfovaluesreadfrompolicy.
privatestaticfinalHashMap<Signature,String>sSigSeinfo=
newHashMap<Signature,String>();
//Packagenameseinfovaluesreadfrompolicy.
privatestaticfinalHashMap<String,String>sPackageSeinfo=
newHashMap<String,String>();
www.it-ebooks.info
ThesSigSeinfomapsSignatures,orsigningkeys,toseinfostrings.Theothermap,sPackageSeinfomapsapackagenametoastring.
Atthispoint,wecanreadsomeformattedXMLfromthemac_permissions.xmlfileandcreateinternalmappingsfromsigningkeytoseinfoandpackagenametoseinfo.
TheothercallfromPackageManagerServiceintothisclasscamefromvoidassignSeinfoValue(PackageParser.Packagepkg).
Let’sinvestigatewhatthismethodcando.ItstartsbycheckingiftheapplicationissystemUIDorasysteminstalledapp.Inotherwords,itcheckswhethertheapplicationisathird-partyapplication:
if(((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM)!=0)||
((pkg.applicationInfo.flags&ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)!=
0)){
ThiscodehassubsequentlybeendroppedbyGoogle,andwasinitiallyarequirementformerge.Wecan,however,continueourevaluation.Thecodeloopsoverallthesignaturesinthepackage,andchecksagainstthehashtable.Ifitissignedwithsomethinginthatmap,itusestheassociatedseinfovalue.Theothercaseisthatitmatchesbypackagename.Ineithercase,thepackage’sApplictionInfoclassseinfovalueisupdatedtoreflectthisandbeusedelsewherebyinstalldandzygoteapplicationspawn:
//Wejustwantoneofthesignaturestomatch.
for(Signatures:pkg.mSignatures){
if(s==null)
continue;
if(sSigSeinfo.containsKey(s)){
Stringseinfo=pkg.applicationInfo.seinfo=sSigSeinfo.get(s);
if(DEBUG_POLICY_INSTALL)
Slog.i(TAG,"package("+pkg.packageName+
")labeledwithseinfo="+seinfo);
return;
}
}
//Checkforseinfolabeledbypackage.
if(sPackageSeinfo.containsKey(pkg.packageName)){
Stringseinfo=pkg.applicationInfo.seinfo=
sPackageSeinfo.get(pkg.packageName);
if(DEBUG_POLICY_INSTALL)
Slog.i(TAG,"package("+pkg.packageName+
")labeledwithseinfo="+seinfo);
return;
}
}
}
Asanaside,whatismergedintomainlineAOSPandwhatismaintainedintheNSABitbucketrepositoriesisabitdifferent.TheNSAhasadditionalcontrolsinthesepolicyfilesthatcancauseanapplicationinstallationtoabort.GoogleandtheNSAare“forked”overthisissue,sotospeak.IntheNSAversionsofSELinuxMMAC.java,youcanspecifythatapplicationsmatchingaspecificsignatureorpackagenameareallowedtohave
www.it-ebooks.info
certainsetsofAndroid-levelpermissions.Forinstance,youcanblockallapplicationsfrombeinginstalledthatrequestCAMERApermissionsorblockapplicationssignedwithcertainkeys.Thisalsohighlightshowimportantitcanbetofindpatcheswithinlargecodebasesandquicklycomeuptospeedonhowprojectsevolve,whichcanoftenseemdaunting.
ThelastfileinthispatchforustoconsiderisActivityManagerService.java.Thispatchreplacesthenullwithapp.info.seinfo.Afterallthatworkandallthatplumbing,wefinallyhavethemysticalseinfovaluefullyparsed,associatedperapplicationpackage,andsentalongtothezygoteforuseinselinux_android_setcontext().
Nowitwouldbenefitustositbackandthinkaboutsomeofthepropertieswewantedtoachieveinlabelingapplications.Oneofthemistosomehowcoupleasecuritycontextwiththeapplicationsigningkey,andthisispreciselythemainbenefitofseinfo.Thisisahighlysensitiveandtrustedstringassociatedvalueofasigningkey.Theactualcontentsofthestringarearbitraryanddictatedinmac_permissions.xml,whichisthenextstoponouradventure.
www.it-ebooks.info
Themac_permissions.xmlfileThemac_permissions.xmlfilehasaveryconfusingname.Expanded,thenameisMACpermissions.However,itsmajormainlinefunctionalityistomapasigningkeytoaseinfostring.Secondarily,itcanalsobeusedtoconfigureanon-mainstreaminstall-timepermission-checkingfeature,knownasinstalltimeMMAC.MMACcontrolsarepartoftheNSA’sworktoimplementmandatoryaccesscontrolsinthemiddlewarelayer.MMACstandsfor“MiddlewareMandatoryAccessControls”.GooglehasnotmergedanyoftheMMACfeatures.However,sinceweusedtheNSABitbucketrepositories,ourcodebasecontainsthesefeatures.
Themac_permissions.xmlisanXMLfile,andshouldadheretothefollowingrules,whereitalicizedportionsareonlysupportedonNSAbranches:
AsignatureisahexencodedX.509certificateandisrequiredforeachsignertag.A<signersignature="">elementmayhavemultiplechildelements:
allow-permission:Itproducesasetofmaximalallowedpermissions(whitelist)deny-permission:Itproducesablacklistofpermissionstodenyallow-all:Itisawildcardtagthatwillalloweverypermissionrequestedpackage:Itisacomplextagwhichdefinesallow,deny,andwildcardsub-elementsforaspecificpackagenameprotectedbythesignature
Zeroormoreglobal<packagename="">tagsareallowed.Thesetagsallowapolicytobesetoutsideanysignatureforspecificpackagenames.A<default>tagisallowedthatcancontaininstallpolicyforallappsnotsignedwithapreviouslylistedcertandnothavingaperpackageglobalpolicy.Unknowntagsatanylevelareskipped.Zeroormoresignertagsareallowed.Zeroormorepackagetagsareallowedpersignertag.A<packagename="">tagmaynotcontainanother<packagename="">tag.Iffound,it’sskipped.Whenmultiplesub-elementsappearforatag,thefollowinglogicisusedtoultimatelydeterminethetypeofenforcement:
Ablacklistisusedifatleastonedeny-permissiontagisfound.Awhitelistisused,ifnotablacklist,andatleastoneallow-permissiontagisfound.Awildcard(acceptallpermissions)policyisusedifnotablacklistandnotawhitelist,andatleastoneallow-alltagispresent.Ifa<packagename="">sub-elementisfound,thenthatsub-element’spolicyisusedaccordingtotheearlierlogicandoverridesanysignatureglobalpolicytype.Inorderforapolicystanzatobeenforced,atleastoneoftheprecedingsituationsmustapply.Meaning,emptysigner,defaultorpackagetagswillnotbeaccepted.
www.it-ebooks.info
Eachsigner/default/package(globalorattachedtoasigner)tagisallowedtocontainone<seinfovalue=""/>tag.ThistagrepresentsadditionalinfothateachappcanuseinsettinganSELinuxsecuritycontextontheeventualprocess.StrictenforcingofanyXMLstanzaisnotenforcedinmostcases.Thismainlyappliestoduplicatetags,whichareallowed.Intheeventthatatagalreadyexists,theoriginaltagisreplaced.Therearealsonochecksonthevalidityofpermissionnames.AlthoughvalidAndroidpermissionsareexpected,nothingpreventsunknowns.Followingaretheenforcementdecisions:
Allsignaturesusedtosignanapparecheckedforpolicyaccordingtosignertags.However,onlyoneofthesignaturepolicieshastopass.Intheeventthatnoneofthesignaturepoliciespass,ornoneevenmatch,thenaglobalpackagepolicyissought.Iffound,thispolicymediatestheinstall.Thedefaulttagisconsultedlast,ifneeded.Alocalpackagepolicyalwaysoverridesanyparentpolicy.Ifnoneofthecasesapply,thentheappisdenied.
ThefollowingexamplesignoretheInstallMMACsupportandfocusonthemainlineusageofseinfomapping.Thefollowingisanexampleofstanzamappingallthingssignedwiththeplatformkeytoseinfovalueplatform:
<!--PlatformdevkeyinAOSP-->
<signersignature="@PLATFORM">
<seinfovalue="platform"/>
</signer>
Hereisanexamplemappingallthingssignedwiththereleasekeytothereleasedomainwiththeexceptionofthebrowser.Thebrowsergetsassignedaseinfovalueofbrowser,asfollows:
<!--releasedevkeyinAOSP-->
<signersignature="@RELEASE">
<seinfovalue="release"/>
<packagename="com.android.browser">
<seinfovalue="browser"/>
</package>
</signer>
...
Anythingwithanunknownkey,getsmappedtothedefaulttag:
...
<!--Allotherkeys-->
<default>
<seinfovalue="default"/>
</default>
Thesigningtagsareofinterest,the@PLATFORMand@RELEASEarespecialprocessingstringsusedduringbuild.Anothermappingfilemapsthesetoactualkeyvalues.Thefilethatisprocessedandplacedontothedevicehasallkeyreferencesreplacedwithhexencodedpublickeysratherthantheseplaceholders.Italsohasallwhitespaceand
www.it-ebooks.info
commentsstrippedtoreducesize.Let’stakealookbypullingthebuiltfilefromthedeviceandformattingit.
$adbpull/system/etc/security/mac_permissions.xml
$xmllint--formatmac_permissions.xml
Now,scrolltothetopoftheformattedoutput;youshouldseethefollowing:
<?xmlversion="1.0"encoding="iso-8859-1"?>
<!--AUTOGENERATEDFILEDONOTMODIFY-->
<policy>
<signer
signature="308204ae30820396a003020102020900d2cba57296ebebe2300d06092a864886
f70d0101050500308196310b300906035504061302555331133…
dec513c8443956b7b0182bcf1f1d">
<allow-all/>
<seinfovalue="platform"/>
</signer>
Noticethatsignature=@PLATFORMisnowahexstring.ThishexstringisavalidX509certificate.
www.it-ebooks.info
keys.confTheactualmagicdoingthemappingfromsignature=@PLATFORMinmac_permissions.xmliskeys.conf.Thisconfigurationfileallowsyoutomapapemencodedx509toanarbitrarystring.Theconventionistostartthemwith@,butthisisnotenforced.TheformatofthefileisbasedonthePythonconfigparserandcontainssections.Thesectionnamesarethetagsinthemac_permissions.xmlfileyouwishtoreplacewithkeyvalues.Theplatformexampleis:
[@PLATFORM]
ALL:$DEFAULT_SYSTEM_DEV_CERTIFICATE/platform.x509.pem
InAndroid,whenyoubuild,youcanhavethreelevelsofbuilds:engineering,userdebug,oruser.Inthekeys.conffile,youcanassociateakeytobeusedforalllevelswiththesectionattributeALL,oryoucanassigndifferentkeysperlevel.Thisishelpfulwhenbuildingreleaseoruserbuildswithveryspecialreleasekeys.Weseeanexampleofthisinthe@RELEASEsection:
[@RELEASE]
ENG:$DEFAULT_SYSTEM_DEV_CERTIFICATE/testkey.x509.pem
USER:$DEFAULT_SYSTEM_DEV_CERTIFICATE/testkey.x509.pem
USERDEBUG:$DEFAULT_SYSTEM_DEV_CERTIFICATE/testkey.x509.pem
Thefilealsoallowstheuseofenvironmentvariablesthroughthetraditional$specialcharacter.Thedefaultlocationforthepemfilesisbuild/target/product/security.However,youshouldneverusethesekeysforauserreleasebuild.ThesekeysaretheAOSPtestkeysandarepublic!Bydoingso,anyonecanusethesystemkeytosigntheirappandgainsystemprivilege.Thekeys.conffileisonlyusedduringthebuildandisnotlocatedonthesystem.
www.it-ebooks.info
seapp_contextsSofar,wehavelookedathowafinishedmac_permssions.xmlfileassignstheseinfovalue.Nowweshouldaddresshowthelabelingisactuallyconfiguredandutilizesthisvalue.Thelabelingofapplicationsismanagedinanotherconfigurationfile,seapp_contexts.Likemac_permissions.xml,itisloadedtothedevice.However,thedefaultlocationis/seapp_contexts.Theformatofseapp_contextsisthekey=valuepairmappingsperline,adheringtothefollowingrules:
Inputselectors:
isSystemServer(boolean)user(string)seinfo(string)name(string)sebool(string)
Inputselectorrules:
isSystemServer=truecanonlybeusedonce.AnunspecifiedisSystemServerdefaultstofalse.Anunspecifiedstringselectorwillmatchanyvalue.Auserstringselectorthatendsin*willperformaprefixmatch.user=_appwillmatchanyregularappUID.user=_isolatedwillmatchanyisolatedserviceUID.Allspecifiedinputselectorsinanentrymustmatch(logicalAND).Matchingiscase-insensitive.Precedencerulesinorder:
isSystemServer=truebeforeisSystemServer=falseSpecifieduser=stringbeforeunspecifieduser=stringFixedtheuser=stringbeforetheuser=prefix(endingin*)Longeruser=prefixbeforeshorteruser=prefixSpecifiedseinfo=stringbeforeunspecifiedseinfo=string.Specifiedname=stringbeforeunspecifiedname=string.Specifiedsebool=stringbeforeunspecifiedsebool=string.
Outputs:
domain(string):Itspecifiestheprocessdomainfortheapplication.type(string):Itspecifiesthedisklabelfortheapplications’privatedatadirectory.levelFrom(string;oneofnone,all,app,oruser):ItgivestheMLSspecifier.level(string):ItshowsthehardcodedMLSvalue.
Outputrules:
Onlyentriesthatspecifydomain=willbeusedforappprocesslabeling.Onlyentriesthatspecifytype=willbeusedforappdirectorylabeling.
www.it-ebooks.info
levelFrom=userisonlysupportedfor_appor_isolatedUIDs.levelFrom=apporlevelFrom=allisonlysupportedfor_appUIDs.levelmaybeusedtospecifyafixedlevelforanyUID.
Duringapplicationspawn,thisfileisusedbytheselinux_android_setcontext()andselinux_android_setfilecon2()functionstolookuptheproperapplicationdomainorfilesystemcontext,respectively.Thesourceforthesecanbefoundinexternal/libselinux/src/android.candarerecommendedreads.Forexample,thisentryplacesallapplicationswithUIDbluetoothinthebluetoothdomainwithadatadirectorylabelofbluetooth_data_file:
user=bluetoothdomain=bluetoothtype=bluetooth_data_file
Thisexampleplacesallthirdpartyor“default”applicationsintoaprocessdomainofuntrusted_appandadatadirectoryofapp_data_file.ItadditionallyusesMLScategoriesoflevelFrom=apptohelpprovideadditionalMLS-basedseparations.
user=_appdomain=untrusted_apptype=app_data_filelevelFrom=app
Currently,thisfeatureisexperimentalasthisbreakssomeknownapplicationcompatibilityissues.Atthetimeofthiswriting,thiswasahotitemoffocusforbothGoogleandNSAengineers.Sinceitisexperimental,let’svalidateitsfunctionalityandthendisableit.
Wehavenotinstalledanythirdpartyapplicationsyet,sowe’llneedtodosoinordertoexperiment.FDroidisausefulplacetofindthirdpartyapplications,solet’sdownloadsomethingfromthereandinstallit.Wecanusethe0xbenchmarkapplicationlocatedathttps://f-droid.org/repository/browse/?fdid=org.zeroxlab.zeroxbenchmarkwithanAPKathttps://f-droid.org/repo/org.zeroxlab.zeroxbenchmark_9.apk,asfollows:
$wgethttps://f-droid.org/repo/org.zeroxlab.zeroxbenchmark_9.apk
$adbinstallorg.zeroxlab.zeroxbenchmark_9.apk
567KB/s(1193455bytesin2.052s)
pkg:/data/local/tmp/org.zeroxlab.zeroxbenchmark_9.apk
Success
TipChecklogcatfortheinstalltimeseinfovalue:
$adblogcat|grepSELinux
I/SELinuxMMAC(2557):package(org.zeroxlab.zeroxbenchmark)installedwith
seinfo=default
FromyourUDOO,launchthe0xbenchmarkAPK.Weshouldseeitrunningwithitslabelinps:
$adbshellps-Z|grepuntrusted
u:r:untrusted_app:s0:c40,c256u0_a40178902285org.zeroxlab.zeroxbenchmark
Noticethelevelportionofthecontextstrings0:c40,c256.Thesecategorieswerecreatedwiththelevel=appsettingfromseapp_contexts.
www.it-ebooks.info
Todisableit,wecouldsimplyremovethekey-valuepairforlevelfromtheentryinseapp_contexts,orwecouldleveragetheseboolconditionalassignment.Let’susetheBooleanapproach.Modifythesepolicyseapp_contextsfilesotheexistinguntrusted_appentryismodified,andanewoneisadded.Changeuser=_appdomain=untrusted_apptype=app_data_filetouser=_appsebool=app_leveldomain=untrusted_apptype=app_data_filelevelFrom=app.
Buildthatwithmmmexternal/sepolicy,asfollows:
Error:
out/host/linux-x86/bin/checkseapp-p
out/target/product/udoo/obj/ETC/sepolicy_intermediates/sepolicy-o
out/target/product/udoo/obj/ETC/seapp_contexts_intermediates/seapp_contexts
out/target/product/udoo/obj/ETC/seapp_contexts_intermediates/seapp_contexts
.tmp
Error:Couldnotfindselinuxboolean"app_level"online:42infile:
out/target/product/udoo/obj/ETC/seapp_contexts_intermediates/seapp_contexts
Error:Couldnotvalidate
Well,therewasabuilderrorcomplainingaboutnotfindingtheselinuxBooleanonline42ofseapp_contexts.Let’sattempttocorrecttheissuebydeclaringtheBoolean.Inapp.te,add:boolapp_levelfalse;.Nowpushthenewlybuiltseapp_contextsandsepolicyfiletothedeviceandtriggeradynamicreload:
$adbpush$OUT/root/sepolicy/data/security/current/
$adbpush$OUT/root/seapp_contexts/data/security/current/
$adbshellsetpropselinux.reload_policy1
WecanverifythattheBooleanexistsby:
$adbshellgetsebool-a|grepapp_level
app_level-->off
Duetodesignlimitations,weneedtouninstallandreinstalltheapplication:
$adbuninstallorg.zeroxlab.zeroxbenchmark
Re-installandcheckthecontextoftheprocessafterlaunchingit:
$adbshellps-Z|grepuntrusted
u:r:untrusted_app:s0:c40,c256u0_a40178902285org.zeroxlab.zeroxbenchmark
Great!Itfailed.Aftersomedebugging,wediscoveredthesourceoftheissueisthatthepath/data/securityisnotworldsearchable,causingaDACpermissionsfailure.
NoteWefoundthisbyprintingofftheresultanderrorcodesinandroid.cwherewesawthefopenonseapp_contexts_file[]array(filesinpriorityorder)whilecheckingtheresultoffp=fopen(seapp_contexts_file[i++],"r")inselinux_android_seapp_context_reload()andusingselinux_log()todumpthedatatologcat.
$adbshellls-la/data|grepsecurity
drwx------systemsystem1970-01-0400:22security
www.it-ebooks.info
RememberthesetselinuxcontextoccursaftertheUIDswitch,soweneedtomakeitsearchableforothers.WecanfixthepermissionsontheUDOOinit.rcscriptbychangingdevice/fsl/imx6/etc/init.rc.Specifically,changethelinemkdir/data/security0700systemsystemtomkdir/data/security0711systemsystem.Buildandflashthebootimage,andtrythecontexttestagain.
$adbuninstallorg.zeroxlab.zeroxbenchmark
$adbinstall~/org.zeroxlab.zeroxbenchmark_9.apk
<launchapk>
$adbshellps-Z|greporg.zeroxlab.zeroxbenchmark
u:r:untrusted_app:s0u0_a4033242285org.zeroxlab.zeroxbenchmark
Sofar,we’vedemonstratedhowtousethesebooloptiononseapp_contextstodisabletheMLScategories.It’simportanttonotethatwhenchangingcategoriesortypesonAPKs,itisrequiredtoremoveandinstalltheAPK,oryouwillorphantheprocessfromitsdatadirectorybecauseitwon’thaveaccesspermissionsundermostcircumstances.
Next,let’stakethisAPK,uninstallit,andassignitauniquedomainbychangingitsseinfostring.Typically,youusethisfeaturetotakeasetofapplicationssignedwithacommonkeyandgetthemintoacustomdomaintodocustomthings.Forexample,ifyou’reanOEM,youmayneedtoallowcustompermissionstothirdpartyapplicationsthatarenotsignedwithanOEMcontrolledkey.StartbyuninstallingtheAPK:
$adbuninstallorg.zeroxlab.zeroxbenchmark
Createanewentryinmac_permissions.xmlbyadding:
<signersignature="@BENCHMARK">
<allow-all/>
<seinfovalue="benchmark"/>
</signer>
Nowweneedtogetapemfileforkeys.conf.SounpackagetheAPKandextractthepubliccertificate:
$mkdirtmp
$cdtmp
$unzip~/org.zeroxlab.zeroxbenchmark_9.apk
$cdMETA-INF/
$$opensslpkcs7-informDER-in*.RSA-outCERT.pem-outformPEM-
print_certs
We’llhavetostripanycruftfromthegeneratedCERT.pemfile.Ifyouopenitup,youshouldseetheselinesatthetop:
subject=/C=UK/ST=ORG/L=ORG/O=fdroid.org/OU=FDroid/CN=FDroid
issuer=/C=UK/ST=ORG/L=ORG/O=fdroid.org/OU=FDroid/CN=FDroid
-----BEGINCERTIFICATE-----
MIIDPDCCAiSgAwIBAgIEUVJuojANBgkqhkiG9w0BAQUFADBgMQswCQYDVQQGEwJV
SzEMMAoGA1UECBMDT1JHMQwwCgYDVQQHEwNPUkcxEzARBgNVBAoTCmZkcm9pZC5v…
Theyneedtoberemoved,soremoveonlythesubjectandissuerlines.ThefileshouldstartwithBEGINCERTIFICATEandendwithENDCERTIFICATEscissorlines.
www.it-ebooks.info
Let’smovethistoanewfolderinourworkspacecalledcertsandmovethecertificateintothisfolderwithabettername:
$mkdirUDOO_SOURCE_ROOT/certs
$mvCERT.pemUDOO_SOURCE_ROOT/certs/benchmark.x509.pem
Wecansetupourkeys.confbyadding:
[@BENCHMARK]
ALL:certs/benchmark.x509.pem
Don’tforgettoupdateseapp_contextsinordertousethenewmapping:
user=_appseinfo=benchmarkdomain=benchmark_app
type=benchmark_app_data_file
Nowdeclarethenewtypestobeused.Thedomaintypeshouldbedeclaredinafilecalledbenchmark_app.teinsepolicy:
#Declarethenewtype
typebenchmark_app,domain;
#Thismacroaddsittotheuntrustedappdomainsetandgivesitsome
allowrules
#forbasicfunctionalityaswellasobjectaccesstothetypeinargument
2.
untrustedapp_domain(benchmark_app,benchmark_app_data_file)
Also,addthebenchmark_app_data_fileinfile.te:
typebenchmark_app_data_file,file_type,data_file_type,
app_public_data_type;
TipYoumaynotalwayswantalloftheseattributes,especiallyifyou’redoingsomethingsecuritycritical.Makesureyoulookateachattributeandmacroandseeitsusage.Youdon’twanttoopenupanunintendedholebyhavinganoverlypermissivedomain.
Rebuildthepolicy,pushtherequiredpieces,andtriggerareload.
$mmmexternal/sepolicy/
$adbpush$OUT/system/etc/security/mac_permissions.xml
/data/security/current/
$adbpush$OUT/root/sepolicy/data/security/current/
$adbpush$OUT/root/seapp_contexts/data/security/current/
$adbshellsetpropselinux.reload_policy1
StartashellandgreplogcattoseetheseinfovaluethebenchmarkAPKisinstalledas.TheninstalltheAPK:
$adbinstall~/org.zeroxlab.zeroxbenchmark_9.apk
$adblogcat|grep-iSELinux
Onthelogcatoutput,youshouldsee:
I/SELinuxMMAC(2564):package(org.zeroxlab.zeroxbenchmark)installedwith
seinfo=default
www.it-ebooks.info
Itshouldhavebeenseinfo=benchmark!Whatcouldhavehappened?
Theproblemisinframeworks/base/services/java/com/android/server/pm/SELinuxMMAC.java.Itlooksin/data/security/mac_permissions.xml;sowecanjustpushmac_permissions.xml.Thisisanotherbuginthedynamicpolicyreloadandhastodowithhistoricalchangesinthisloadingprocedure.Theculpritiswithintheframeworks/base/services/java/com/android/server/pm/SELinuxMMAC.javafile:
privatestaticfinalFile[]INSTALL_POLICY_FILE={
newFile(Environment.getDataDirectory(),"security/mac_permissions.xml"),
newFile(Environment.getRootDirectory(),
"etc/security/mac_permissions.xml"),
null};
Togetaroundthis,remountsystemandpushittothedefaultlocation.
$adbremount
$adbpush$OUT/system/etc/security/mac_permissions.xml
/system/etc/security/
Thisdoesnotrequireasetpropselinux.reload_policy1.UninstallandreinstallthebenchmarkAPK,andcheckthelogs:
I/SELinuxMMAC(2564):package(org.zeroxlab.zeroxbenchmark)installedwith
seinfo=default
OK.Itstilldidn’twork.Whenweexaminedthecode,themac_permissions.xmlfilewasloadedduringpackagemanagerservicestart.Thisfilewon’tgetreloadedwithoutareboot,solet’suninstallthebenchmarkAPK,andreboottheUDOO.Afterit’sbeenbootedandadbisenabled,triggeradynamicreload,installtheAPK,andchecklogcat.Itshouldhave:
I/SELinuxMMAC(2559):package(org.zeroxlab.zeroxbenchmark)installedwith
seinfo=benchmark
Nowlet’sverifytheprocessdomainbylaunchingtheAPK,checkingps,andverifyingitsapplicationprivatedirectory:
<launchapk>
$adbshellps-Z|greporg.zeroxlab.zeroxbenchmark
u:r:benchmark_app:s0u0_a4534932285org.zeroxlab.zeroxbenchmark
$adbshellls-Z/data/data|greporg.zeroxlab.zeroxbenchmark
drwxr-x--xu0_a45u0_a45u:object_r:benchmark_app_data_file:s0
org.zeroxlab.zeroxbenchmark
Thistime,allthetypescheckout.Wesuccessfullycreatedanewcustomdomain.
www.it-ebooks.info
SummaryInthischapter,weinvestigatedhowtoproperlylabelapplicationprivatedatadirectoriesaswellastheirruntimecontextsviatheconfigurationfilesandSELinuxpolicy.Wealsolookedintothesubsystemsandcodetomakeallofthisworkaswellassomebasicthingsthatmaygowrongalongtheway.Inthenextchapter,wewillexpandonhowthepolicyandconfigurationfilesgetbuiltbypeeringintotheSEforAndroidbuildsystem.
www.it-ebooks.info
Chapter11.LabelingPropertiesInthischapter,wewillcoverhowtolabelpropertiesviatheproperty_contextsfile.
PropertiesareauniqueAndroidfeaturewelearnedaboutinChapter3,AndroidIsWeird.Wewanttolabelthesetorestrictsettingofourpropertiestoonlythedomainsthatshouldsetthem,preventingaclassicDACrootattackfrominadvertentlychangingthevalue.Inthischapter,wewilllearnto:
CreatenewpropertiesLabelnewandexistingpropertiesInterpretanddealwithpropertydenialsEnumeratespecialAndroidpropertiesandtheirbehaviors
www.it-ebooks.info
Labelingviaproperty_contextsAllpropertiesarelabeledusingtheproperty_contextsfile,anditssyntaxissimilartofile_contexts.However,insteadofworkingonfilepaths,itworksonpropertynamesorpropertykeys(propertiesinAndroidareakey-valuestore).Thepropertykeysthemselvesaretypicallydelimitedwithperiods(.).Thisisanalogoustofile_contexts,excepttheslash(/)becomesaperiod.Somesamplepropertiesandtheirentriesinproperty_contextswouldlooklikethefollowing:
ctl.ril-daemonu:object_r:ctl_rildaemon_prop:s0
ctl.u:object_r:ctl_default_prop:s0
Noticehowallctl.propertiesarelabeledwiththectl_default_proptype,butctl.ril-daemonhasadifferenttypelabelofctl_rildaemon_prop.Thesearerepresentativeofhowyoucanstartgenericallyandmovetomorespecificvalues/typesasnecessary.
Additionally,anythingnotexplicitlylabeleddefaultstodefault_propthrougha“matchall”expressioninproperty_contexts:
#defaultpropertycontext
*u:object_r:default_prop:s0
www.it-ebooks.info
PermissionsonpropertiesOnecanviewthecurrentpropertiesonthesystem,andcreatenewoneswiththecommandlineutilitiesgetpropandsetprop,asshowninthefollowingcodesnippet:
root@udoo:/#getprop
...
[sys.usb.state]:[mtp,adb]
[wifi.interface]:[wlan0]
[wlan.driver.status]:[unloaded]
RecallfromChapter3,AndroidIsWeird,thatpropertiesaremappedintoeveryone’saddressspace,thusanyonecanreadthem.However,noteveryonecanset(write)them.TheDACpermissionmodelforpropertiesishardcodedintosystem/core/init/property_service.c:
/*Whitelistofpermissionsforsettingpropertyservices.*/
struct{
constchar*prefix;
unsignedintuid;
unsignedintgid;
}property_perms[]={
{"net.rmnet0.",AID_RADIO,0},
{"net.gprs.",AID_RADIO,0},
{"net.ppp",AID_RADIO,0},
...
{"persist.service.bdroid.",AID_BLUETOOTH,0},
{"selinux.",AID_SYSTEM,0},
{"persist.audio.device",AID_SYSTEM,0},
{NULL,0,0}
YoumusthavetheUIDorGIDintheproperty_permsarraytosetanypropertythattheprefixmatcheswith.Forinstance,inordertosettheselinux.properties,youmustbeUIDAID_SYSTEM(uid1000)orroot.Yes,rootcanalwayssetaproperty,andthisisakeybenefittoapplyingSELinuxtoAndroidproperties.Unfortunately,thereisnowaytogetprop-Ztolistthepropertiesandtheirlabels,likewithls-Zandfiles.
www.it-ebooks.info
RelabelingexistingpropertiesInordertobecomemorecomfortablewithlabelingproperties,let’srelabelthewifi.interfaceproperty.First,let’sverifyitscontextbycausingadenialandviewingthedeniallog,asshowninthefollowingcode:
root@udoo:/#setpropwifi.interfacewlan0
avc:denied{set}forproperty=wifi.interfacescontext=u:r:shell:s0
tcontext=u:object_r:default_prop:s0tclass=property_service
AninterestingactionoccurredwhenweexecutedthesetpropcommandovertheUDOOserialconsole.TheAVCdenialrecordwasprintedout.Thisisbecausetheserialconsoleincludesanythingprintedfromthekernelusingprintk().Whathappenshereistheinitprocess,whichcontrolssetpropsasdetailedinChapter3,AndroidIsWeird,writesamessagetothekernellog.Thislogmessageshowsupwhenweexecuteoursetpropcommand.Ifyourunthisthroughadbshell,you’llseethemessageontheserialconsole,butnotintheadbconsole.Todothis,however,youmustrebootyoursystembecauseSELinuxonlyprintsdenialrecordsoncewhileinpermissivemode.
Thecommandusingadbshellisasfollows:
$adbshellsetpropwifi.interfacewlan0
Thecommandusingtheserialconsoleisasfollows:
root@udoo:/#avc:denied{set}forproperty=wifi.interface
scontext=u:r:shell:s0tcontext=u:object_r:default_prop
usb2-1.3:devicedescriptorread/64,error-110
Fromthedenialoutput,wecanseethatthepropertytypelabelisdefault_prop.Let’schangethistowifi_prop.
Westartbyeditingproperty.teinthesepolicydirectorytodeclarethenewtypetolabelthesepropertiesbyappendingthefollowingline:
typewifi_prop,property_type;
Withthetypedeclared,thenextstepistoapplythelabelbymodifyingproperty_contextsbyaddingthefollowing:
#wifiproperties
wifi.u:object_r:wifi_prop:s0
Buildthepolicy,asfollows:
$mmmexternal/sepolicy
Pushthenewproperty_contextsfile:
$adbpushout/target/product/udoo/root/property_contexts
/data/security/current
51KB/s(2261bytesin0.042s)
Triggeradynamicreload:
www.it-ebooks.info
$adbshellsetpropselinux.reload_policy1
#setpropwifi.interfacewlan0
avc:denied{set}forproperty=wifi.interfacescontext=u:r:shell:s0
tcontext=u:object_r:default_prop:s0tclass=property_service
Ok,thatdidn’twork!Theproperty_contextsfilemustbein/data/security,not/data/security/current.
Todiscoverthis,searchthelibselinux/src/android.cfile.Thereisnomentionofproperty_contextsinthisfile;thus,itmustbementionedelsewhere.Thisleadsustosearchsystem/core,whichcontainsthepropertyserviceforusesofthatfile.Thematchesareoncodeininit.ctoloadthefilefromprioritylocations.
$grep-rnproperty_contexts*
init/init.c:745:{SELABEL_OPT_PATH,"/data/security/property_contexts"},
init/init.c:746:{SELABEL_OPT_PATH,"/property_contexts"},
init/init.c:760:ERROR("SELinux:Couldnotloadproperty_contexts:%s\n",
Let’spushtheproperty_contextsfiletotheproperlocationandtryagain:
$adbpushout/target/product/udoo/root/property_contexts/data/security
51KB/s(2261bytesin0.042s)
$adbshellsetpropselinux.reload_policy1
root@udoo:/#setpropwifi.interfacewlan0
avc:receivedpolicyloadnotice(seqno=3)
init:sys_prop:permissiondenieduid:0name:wifi.interface
Wow!Itfailedyetagain.Thisexercisewasmeanttopointouthowtrickythiscanbeifyouforgettodosomething.Noinformativedenialmessagesweredisplayed,onlyanindicatorthatitwasdenied.Thisisbecausethesepolicyfilethatcontainsthetypedeclarationforwifi_propwasneverpushed.Thiscausescheck_mac_perms()insystem/core/init/property_service.ctofailintheselinux_check_access()functionbecauseitcannotfindthetypetocomputetheaccesscheckagainst,eventhoughthelookupinproperty_contextssucceeded.Therearenoverboseerrorlogsfromthis.
Wecancorrectthisbyensuringthatthesepolicyispushedaswell:
$adbpushout/target/product/udoo/root/sepolicy/data/security/current/
550KB/s(87385bytesin0.154s)
$adbshellsetpropselinux.reload_policy1
root@udoo:/#setpropwifi.interfacewlan0
avc:receivedpolicyloadnotice(seqno=4)
avc:denied{set}forproperty=wifi.interfacescontext=u:r:shell:s0
tcontext=u:object_r:wifi_prop:s0tclass=property_service
Nowweseeadenialmessage,asexpected,butthelabelofthetarget(orproperty)isu:object_r:wifi_prop:s0.
Nowwiththetargetpropertylabeled,youcanallowaccesstoit.Notethatthisisacontrivedexample,andintherealworld,youprobablywouldnotwanttoallowaccessfromshelltomostproperties.Thepolicyshouldalignwithyoursecuritygoalsandthepropertyofleastprivilege.
Wecanaddanallowruleinshell.teinthefollowingway:
www.it-ebooks.info
#wifiprop
allowshelldomainwifi_prop:property_serviceset;
Compilethepolicy,pushittothephone,andtriggeradynamicreload:
$mmmexternal/sepolicy/
$adbpushout/target/product/udoo/root/sepolicy/data/security/current/
547KB/s(87397bytesin0.155s)
$adbshellsetpropselinux.reload_policy1
Nowattempttosetthewifi.interfacepropertyandnoticethelackofdenial.
root@udoo:/#setpropwifi.interfacewlan0
avc:receivedpolicyloadnotice(seqno=5)
www.it-ebooks.info
CreatingandlabelingnewpropertiesAllpropertiesaredynamicallycreatedinthesystemusingsetpropcallsorfunctioncallsthatdotheequivalentfromC(bionic/libc/include/sys/system_properties.h)andJava(android.os.SystemProperties).NotethattheSystem.getProperty()andSystem.setProperty()Javacallsworkonapplicationprivatepropertystoresandarenottiedintotheglobalone.
ForDACcontrols,youneedtomodifyproperty_perms[]asnotedearliertohavepermissionsfornon-rootuserstocreateorsettheproperty.Notethatrootcanalwayssetandcreate,unlessconstrainedbySELinuxpolicy.
Supposewewanttocreatetheudoo.nameandudoo.ownerproperties;weonlywanttherootuserandshelldomaintoaccessthem.Wecouldcreatethemlikethis:
root@udoo:/#setpropudoo.nameudoo
avc:denied{set}forproperty=udoo.namescontext=u:r:shell:s0
tcontext=u:object_r:default_prop:s0tclass=property_service
root@udoo:/#setpropudoo.ownerWilliam
Noticethedenialshowstheseasbeingdefault_proptype.Tocorrectthis,wewouldrelabelthese,exactlyaswedidintheprecedingsection,Relabelingexistingproperties.
www.it-ebooks.info
SpecialpropertiesInAndroid,therearesomespecialpropertiesthathavedifferentbehaviors.Weenumeratethepropertynamesandmeaningsintheproceedingsections.
www.it-ebooks.info
ControlpropertiesPropertiesthatstartwithctlarereservedascontrolpropertiesforcontrollingservicesthroughinit:
start:Startsaservice(setpropctl.start<servicename>)stop:Stopsaservice(setpropctl.stop<servicename>)restart:Restartsaservice(setpropctl.restart<servicename>)
www.it-ebooks.info
PersistentpropertiesAnypropertystartingwiththeprefixpersistpersistsacrossrebootsandisrestored.Thedataissavedto/data/propertyinfilesofthesamenameastheproperty.
root@udoo:/#ls/data/property/
persist.gps.oacmode
persist.service.bdroid.bdaddr
persist.sys.profiler_ms
persist.sys.usb.config
www.it-ebooks.info
SELinuxpropertiesTheselinux.reload_policypropertyisspecial.Aswehaveseen,itsuseisfortriggeringadynamicreloadevent.
www.it-ebooks.info
SummaryInthischapter,wehaveexaminedhowtocreateandlabelnewandexistingpropertiesandsomeoftheodditiesthatoccurwhendoingso.WehavealsoexaminedthehardcodedDACpermissiontableforpropertiesinproperty_service.c,aswellasthehardcodedspecialtypropertieslikethectl.family.Inthenextchapter,welookathowthetoolchainbuildsandcreatesallthepolicyfileswehavebeenusing.
www.it-ebooks.info
Chapter12.MasteringtheToolChainSofar,wehavetakenadeepdiveintothecodeandpoliciesthatdriveSEforAndroidtechnologies,butthebuildsystemandtoolsareoftenoverlooked.Masteringthetoolchainwillhelpyouimproveyourdevelopmentpractices.Inthischapter,wewilllookatallthecomponentsoftheSEforAndroidbuildandhowtheywork.Wewillcoverthefollowingtopics:
BuildingspecifictargetsThesepolicyAndroid.mkfileCustombuildpolicyconfigurationBuildtools:
check_seapp
insertkeys.py
checkpolicy
checkfc
sepolicy-check
sepolicy-analyze
www.it-ebooks.info
Buildingsubcomponents–targetsandprojectsSofar,wehaverunsomemagicalcommandssuchasmm,mmm,andmakebootimagetoactuallybuildvariousportionsoftheSEforAndroidcode.Googleofficiallydescribessomeofthesetoolsinthedocumentsathttps://source.android.com/source/building-running.html,butmostcommandsarenotlisted.Nonetheless,http://elinux.org/Android_Build_Systemhasawriteupthatismorecomprehensive.
InGoogle’s“buildingandrunning”documentation,theydescribethetargetasthedevice,whichisultimatelywhatyoulunchfor.WhenbuildingAndroid,thelunchcommandsetsupenvironmentvariablesforthemakecommandyouexecutelater.Itsetsupthebuildsystemtooutputthecorrectconfigurationforthetargetdevice.Thisconceptofatargetisnotwhatwillbediscussedinthischapter.Instead,whentargetismentionedherein,itmeansaspecificmaketarget.However,intheeventofneedingtomentionthetargetdevice,thecompletephrase“targetdevice”willbeused.Whilesomewhatconfusing,thisterminologyisstandardandwillbeunderstoodbyengineersinthefield.
Wehaveissuedmakeafewtimes,optionallyprovidingatargetasanargumentandanoption,forexamplethe-j16option.Somethinglikemakeormake-j16essentiallybuildsallofAndroid.Optionally,youcanspecifyatargetorlistoftargetsascommandarguments.Anexampleofthisiswhenboot.imgwasbuilt.Theboot.imgfilecanbebuiltandrebuiltbyspecifyingthebootimagetarget.Thecommandweuseforthispurposeismakebootimage.Ithelpstoexpeditebuildsbyrebuildingonlytheportionsofthesystemthatareneeded.Butwhatifyouonlyneedtorebuildaparticularfile?Perhaps,youonlywanttorebuildsepolicy.Youcanspecifythatasthetargettobuild,asinmakesepolicy.Thisleadstothequestion,“Whatabouttheotherfilessuchasmac_permissions.xml,seapp_contexts,andsoon?”Theycanbebuiltinthesameway.Themoreintriguingquestionis,“Howdoesoneknowwhatthetargetnameis?Isitalwaysthefileoutputname?”
Android’sbuildsystemisconstructedontopofGNUmake(http://www.gnu.org/software/make/).ThecoreoftheAndroidbuildsystem’smakefilessystemcanbefoundinbuild/core,andthedocumentationcanbefoundintheNDK(https://developer.android.com/tools/sdk/ndk/index.html).ThemajortakeawayfromthatreadingisthatatypicalAndroid.mkfiledefinessomethingcalledLOCAL_MODULE:=mymodulename,andsomethingcalledmymodulenameisbuilt.ThetargetnamesaredefinedbytheseLOCAL_MODULEstatements.Let’slookattheAndroid.mkforexternalsepolicy,andfocusonthesepolicyportionofit,asthereareotherlocalmodulesortargetsdefinedinthatMakefile.ThefollowingisanexamplefromAndroid4.3:
include$(CLEAR_VARS)
LOCAL_MODULE:=sepolicy
LOCAL_MODULE_CLASS:=ETC
LOCAL_MODULE_TAGS:=optional
LOCAL_MODULE_PATH:=$(TARGET_ROOT_OUT)
www.it-ebooks.info
...
OnecanfindallthemodulesforwithinanAndroid.mkfilebyjustlookingforlinesthatbeginwithLOCAL_MODULEdeclarationsandarewholewordmatches:
$grep-w'^LOCAL_MODULE'Android.mk
LOCAL_MODULE:=sepolicy
LOCAL_MODULE:=file_contexts
LOCAL_MODULE:=seapp_contexts
LOCAL_MODULE:=property_contexts
LOCAL_MODULE:=selinux-network.sh
LOCAL_MODULE:=mac_permissions.xml
LOCAL_MODULE:=eops.xml
Regularexpressionsdictatethat^isthebeginningoftheline,andthegrepmanpagestatesthat-wprovideswholewordsearch.
TheprecedinglistiscomprehensivefortheversionofAndroidweareusingontheUDOO.However,youshouldrunthecommandonyourexactversionoftheMakefiletogetanideaofwhatthingscanbebuilt.
Androidhassomeadditionaltoolsthatareseparatefrombuildingtargetsandgetaddedtoyourenvironmentwhenyouusesourcebuild/envsetup.sh.Thesearemmandmmm.Theybothperformthesametask,whichistobuildallthetargetsspecifiedinanAndroid.mkfile,however,differingthattheydonotbuildanyoftheirdependencies.ThetwocommandsonlydifferinwheretheysourcethelocationoftheAndroid.mktoscourforbuildtargets.Themmcommandusesthecurrentworkingdirectory,whereasmmmusesasuppliedpath.Also,agreatoptionforeithercommandis-B,whichforcesarebuild.Anengineercansavealotoftimebyusingthemm(m)commandsovermake<target>.Thefullmakecommandwastesalotoftimefiguringoutthedependencytree,soexecutingmmmpath/to/projectonapreviouslybuiltsourcetree(ifyouknowthatallyourchangesarewithinaproject)cansaveafewminutes.However,sinceitdoesn’tbuildthedependencies,you’llneedtoensurethattheyarealreadybuiltandhavenodependentchanges.
www.it-ebooks.info
Exploringsepolicy’sAndroid.mkTheprojectlocatedatexternal/sepolicyusesanAndroid.mkfile,likeanyotherAndroidproject,tobuildtheiroutputs.Let’sdissectthisfileandseewhatitdoes.
www.it-ebooks.info
BuildingsepolicyWe’llstartinthemiddlebylookingatthetargetforsepolicy.ItstartsoffwithfairlyboilerplateAndroid.mkstuff:
...
include$(CLEAR_VARS)
LOCAL_MODULE:=sepolicy
LOCAL_MODULE_CLASS:=ETC
LOCAL_MODULE_TAGS:=optional
LOCAL_MODULE_PATH:=$(TARGET_ROOT_OUT)
include$(BUILD_SYSTEM)/base_rules.mk…
Thenextportionisabitmorelikestandardmake.Itstartsoffbydeclaringatargetfilethatgetsbuiltintotheintermediateslocation.TheintermediateslocationisdefinedbytheAndroidbuildsystem.ItthenassignsthevaluesofMLS_SENSandMLS_CATStosomelocalvariablesforlateruse.Thelastlineisthemostinteresting.Itusesamakefunction,calledbuild_policy,andtakesfilenamesasarguments:
...
sepolicy_policy.conf:=$(intermediates)/policy.conf
$(sepolicy_policy.conf):PRIVATE_MLS_SENS:=$(MLS_SENS)
$(sepolicy_policy.conf):PRIVATE_MLS_CATS:=$(MLS_CATS)
$(sepolicy_policy.conf):$(callbuild_policy,security_classes
initial_sidsaccess_vectorsglobal_macrosmls_macrosmls
policy_capabilitieste_macrosattributesbools*.terolesusers
initial_sid_contextsfs_usegenfs_contextsport_contexts)
...
Next,wedefinetherecipeforbuildingthisintermediatetarget,policy.conf.Theinterestingbitsoftherecipearethem4commandandthesedcommand.
NoteFormoreinformationonm4,seehttp://www.gnu.org/software/m4/manual/m4.html,andformoreinformationonsed,refertohttps://www.gnu.org/software/sed/manual/sed.html.
SELinuxpolicyfilesgetprocessedusingm4.m4isamacroprocessorlanguagethatisoftenusedasafrontendtoacompiler.Them4commandtakessomeofthevaluessuchasPRIVATE_MLS_SENSandPRIVATE_MLS_CATSandpassesthemthroughasmacrodefinitions.Thisisanalogoustothegcc-Doption.Itthentakesthedependenciesforthetargetasinputviathemakeexpansion,$^,andoutputsthemtothetargetnameusingthemakeexpansionof$@.Italsotakesthatoutputandgeneratesa.dontauditversion.Thatversionhasallofthedontauditlinesdeletedfromthepolicyfileusingsed.TheMLSvaluestellSELinuxhowmanycategoriesandsensitivitiestogenerate.Thesemustbestaticallydefinedinthepolicyblobthatisloadedintothekernel,asfollows:
...
@mkdir-p$(dir$@)
$(hide)m4-Dmls_num_sens=$(PRIVATE_MLS_SENS)-D
mls_num_cats=$(PRIVATE_MLS_CATS)-s$^>$@
$(hide)sed'/dontaudit/d'$@>[email protected]…
www.it-ebooks.info
Thenextportiondefinestherecipeforbuildingtheactualtarget,namedfromLOCAL_MODULE_POLICY,evenifthisisnotobvious.LOCAL_BUILT_MODULEexpandstotheintermediatefiletobebuilt,sepolicyinthiscase.ItfinallygetscopiedbytheAndroidbuildsystemasLOCAL_INSTALLED_MODULEbehindthescenes.Thistargetdependsontheintermediatepolicy.conffileandoncheckpolicy.Itusescheckpolicytotransformthem4expandedpolicy.confandpolicy.conf.dontauditintotwosepolicyfiles,sepolicyandsepolicy.dontaudit.TheactualtoolthatisusedtocompiletheSELinuxstatementsinbinaryformtoloadtothekernelischeckpolicy,asfollows:
...
$(LOCAL_BUILT_MODULE):$(sepolicy_policy.conf)
$(HOST_OUT_EXECUTABLES)/checkpolicy
@mkdir-p$(dir$@)
$(hide)$(HOST_OUT_EXECUTABLES)/checkpolicy-M-c$(POLICYVERS)-o$@$<
$(hide)$(HOST_OUT_EXECUTABLES)/checkpolicy-M-c$(POLICYVERS)-o$(dir
$<)/$(notdir$@).dontaudit$<.dontaudit…
Finally,itendsbysettingalocalvariable,built_policy,foruseelsewherewithintheAndroid.mkfile,andclearspolicy.conftoavoidpollutingtheglobalnamespaceofmake,asshown:
...
built_sepolicy:=$(LOCAL_BUILT_MODULE)
sepolicy_policy.conf:=
...
Additionally,buildingsepolicyalsodependsonthePOLICYVERSvariable,whichisconditionallyassignedavalueof26ifnotset.Thisisthepolicyversionnumberusedbycheckpolicy,andaswesawearlierinthebook,wehadtooverridethisforourUDOO.
www.it-ebooks.info
ControllingthepolicybuildWesawthatthesepolicystatementcallsthebuild_policyfunction.WealsoseeitsuseinthatAndroid.mkfileforbuildingsepolicy,file_contexts,seapp_contexts,property_contexts,andmac_permissions.xml,soitreasonsthatitisfairlyimportant.Thisfunctionoutputsalistoffullyresolvedpathsusedforpolicyfiles.Thefunctiontakesasinputsavariableargumentlistoffilenamesandincludesregularexpressionsupport(note*.teinthebuild_policyfortargetsepolicy).Internally,thatfunctionusessomemagictoallowyoutooverrideorappendtothecurrentpolicybuildwithoutmodifyingtheexternal/sepolicydirectorydirectly.ThisismeantforOEMsanddevicebuilderstobeabletoaugmentpolicytocovertheirspecificdevices.
Whenbuildingapolicy,youcansetthefollowingmakevariables,typicallyinthedevice’sMakefile,tocontroltheresultingbuild.Thevariablesareasfollows:
BOARD_SEPOLICY_DIRS:ThisisthesearchpathforpotentialpolicyfilesBOARD_SEPOLICY_UNION:ThisisapolicyfileofnametoappendtoallfileswiththesamenameBOARD_SEPOLICY_REPLACE:Thisisapolicyfileusedtooverridethebaseexternal/sepolicypolicyfileBOARD_SEPOLICY_IGNORE:Thisisusedtoremoveaparticularpolicyfilefromthebuild,givenarepository’srelativepath
UsingtheUDOOasanexample,theproperwaytoauthorapolicywasnevertomodifyexternal/sepolicybuttocreateadirectoryindevice/fsl/udoo/sepolicy:
$mkdir<PATH>
ThenwemodifytheBoardConfig.mk:
$vimBoardConfig.mk
Next,weaddthefollowinglines:
BOARD_SEPOLICY_DIRS+=device/fsl/udoo/sepolicy
TipBeverycarefulwith+=asopposedto:=.Inlargeprojecttrees,someofthesevariablesmaybesethigherinthebuildtreebycommonBoardConfigs,andyoucouldwipeouttheirsettings.Typically,thesafestbetis+=.Forfurtherdetails,seeVariableAssignmentintheGNUmakemanual,athttp://www.gnu.org/software/make/manual/make.html.
Thiswilltellthebuild_policy()functioninAndroid.mktosearchnotonlyexternal/sepolicybutalsodevice/fsl/udoo/sepolicyforpolicyfiles.
Next,wecancreateafile_contextsfileinthisdirectory,andmoveourchangesforlabelingtothisdirectorybycreatinganewfile_contextsfileindevice/fsl/udoo/sepolicy.
Afterthis,weneedtoinstructthebuildsystemtocombine,orunion,ourfile_contexts
www.it-ebooks.info
filewiththeoneinexternal/sepolicy.WeaccomplishthisbyaddingthefollowingstatementtotheBoardConfig.mkfile:
BOARD_SEPOLICY_UNION+=file_contexts
Youcandothisforanypolicyfile,evencustomfiles.Itdoesamatchonthefilenamebybasenameonly(nodirectories).Forinstance,ifyouhadawatchdog.terulesfileyouwantedtoaddtothebasewatchdog.terulesfile,youcouldjustaddwatchdog.te,asshown:
BOARD_SEPOLICY_UNION+=file_contextswatchdog.te
Thisproducesanewwatchdog.tefileduringthebuildthatunionsyournewruleswiththeonesfoundinexternal/sepolicy/watchdog.te.
AlsonotethatyouaddnewfilesintothebuildwithBOARD_SEPOLICY_UNION,sotoadda.tefileforacustomdomain,suchascustom.te,youcould:
BOARD_SEPOLICY_UNION+=file_contextswatchdog.tecustom.te
Let’ssayyouwanttooverridetheexternal/sepolicywatchdog.tefilewithyourown.YoucanaddittoBOARD_SEPOLICY_REPLACE,asshown:
BOARD_SEPOLICY_REPLACE:=watchdog.te
Notethatyoucan’treplaceafilethatdoesnotexistinthebasepolicy.Also,youcan’thavethesamefileappearinUNIONandREPLACE,asit’sambiguous.Youcan’thavemorethanonespecificationofBOARD_SEPOLICY_REPLACEonthesamepolicyfile.
Supposewehaveahierarchicalbuildoccurringfortwofictitiousdevices,deviceXanddeviceY.Thetwodevices,deviceXanddeviceY,bothinheritBoardConfigCommon.mkfromdeviceA.DeviceAisnotarealdevice,butsinceXandYsharecommonalities,thecommonbitsarekeptindeviceA.
SupposetheBoardConfigCommon.mkfordeviceAcontainsthesestatements:
BOARD_SEPOLICY_DIRS+=device/OEM/A
BOARD_SEPOLICY_UNION+=file_contextscustom.te
SupposethatdeviceX’sBoardConfig.mkcontains:
BOARD_SEPOLICY_DIRS+=device/OEM/X
BOARD_SEPOLICY_UNION+=file_contextscustom.te
Finally,supposedeviceY’sBoardConfig.mkcontains:
BOARD_SEPOLICY_DIRS+=device/OEM/Y
BOARD_SEPOLICY_UNION+=file_contextscustom.te
TheresultingpolicysetsusedtobuilddeviceXanddeviceYarethefollowing:
DeviceXpolicyset:
device/OEM/A/file_contexts
device/OEM/A/custom.te
device/OEM/X/file_contexts
www.it-ebooks.info
device/OEM/X/custome.te
external/sepolicy/*(basepolicyfiles)
DeviceYalsocontains:
device/OEM/A/file_contexts
device/OEM/A/custom.te
device/OEM/Y/file_contexts
device/OEM/Y/custom.te
external/sepolicy/*(basepolicyfiles)
Inacommonscenario,youmightnotwanttheresultingpolicysetfordeviceYtocontaindevice/OEM/A/custom.te.ThisisausecaseforBOARD_SEPOLICY_IGNORE.Youcanusethistofilteroutspecificpolicyfiles.However,youhavetobespecificandusetherepository’srelativepath.Forexample,indeviceY’sBoardConfig.mk:
BOARD_SEPOLICY_IGNORE+=device/OEM/A/custom.te
Now,whenyoubuildapolicyfordeviceY,thepolicysetwillnotincludethatfile.BOARD_SEPOLICY_IGNOREcanalsobeusedwithBOARD_SEPOLICY_REPLACE,allowingmultipleusesinthedevicehierarchy,butonlyoneBOARD_SEPOLICY_REPLACEstatementtakeseffect.
www.it-ebooks.info
Diggingdeeperintobuild_policyNowthatwehaveseenhowtousesomenewmechanismstocontrolthepolicybuild,let’sactuallydissectwhereinthebuildprocesshappens.Asstatedearlier,thepolicybuildiscontrolledbytheAndroid.mkfile.Weencounteredcallstothebuild_policy()functionearlier,andthisispreciselywherethemagichappenswithrespecttoalloftheBOARD_SEPOLICY_*variablesweset.Examiningthebuild_policyfunction,weseereferencestothesepolicy_replace_pathsvariable,solet’sstartbylookingatthatvariable.
Thesepolicy_replace_pathsvariablebeginslifebygettingevaluatedwhentheMakefileisevaluated.Inotherwords,itisexecutedunconditionally.ThecodestartsoffbyloopingoveralltheBOARD_SEPOLICY_REPLACEfilesandcheckswhetheranyareinBOARD_SEPOLICY_UNION.Ifoneisfound,anerrorisprintedandthebuildfails,showingAmbiguousrequestforsepolicy$(pf).Appearsinboth
BOARD_SEPOLICY_REPLACEandBOARD_SEPOLICY_UNION,where$(pf)isexpandedtotheoffendingpolicyfile.Afterthat,itexpandstheBOARD_SEPOLICY_REPLACEentrieswiththosefoundonthesearchpathssetbyBOARD_SEPOLICY_DIRS,thusresultinginfullrelativepathsfromtherootoftheAndroidtree.ThenitfilterstheseentriesagainstBOARD_SEPOLICY_IGNORE,droppinganythingthatshouldbeignored.Itthenensuresthatonlyonefilecandidateforreplacementisfound.Otherwise,itissuestheappropriateerrormessage.Lastly,itensuresthatthefileexistsintheLOCAL_PATHorbasepolicy,andifnoneofthetwoisfound,itissuesanerrormessage:
...
#QuickedgecaseerrordetectionforBOARD_SEPOLICY_REPLACE.
#Buildsthesingularpathforeachreplacefile.
sepolicy_replace_paths:=
$(foreachpf,$(BOARD_SEPOLICY_REPLACE),\
$(if$(filter$(pf),$(BOARD_SEPOLICY_UNION)),\
$(errorAmbiguousrequestforsepolicy$(pf).Appearsinboth\
BOARD_SEPOLICY_REPLACEandBOARD_SEPOLICY_UNION),\
)\
$(eval_paths:=$(filter-out$(BOARD_SEPOLICY_IGNORE),\
$(wildcard$(addsuffix/$(pf),$(BOARD_SEPOLICY_DIRS)))))\
$(eval_occurrences:=$(words$(_paths)))\
$(if$(filter0,$(_occurrences)),\
$(errorNosepolicyfilefoundfor$(pf)in$(BOARD_SEPOLICY_DIRS)),\
)\
$(if$(filter1,$(_occurrences)),\
$(evalsepolicy_replace_paths+=$(_paths)),\
$(errorMultipleoccurrencesofreplacefile$(pf)in$(_paths))\
)\
$(if$(filter0,$(words$(wildcard$(addsuffix/$(pf),
$(LOCAL_PATH))))),\
$(errorSpecifiedthesepolicyfile$(pf)inBOARD_SEPOLICY_REPLACE,\
butnonefoundin$(LOCAL_PATH)),\
)\
)
Afterthis,callstobuildpolicycanusereplace_pathsasanexpandedlistoffilesthat
www.it-ebooks.info
willbereplacedduringthebuild.
Theargumentsofthebuild_policyfunctionarethefilenamesyouwishtoexpandintotheirAndroidroot-relativepathnames,usingthepowerprovidedbytheBOARD_SEPOLICY_*familyofvariables.Forinstance,acallto$(build_policy,file_contexts)inthecontextofourdevicesA,X,andYwouldresultinthis:
device/OEM/A/file_contexts
device/OEM/Y/file_contexts
Thebuild_policyfunctionisabittrickytoread.Manynestedfunctioncallsresultinthedeepestindentsrunningfirst.However,likeallcode,wereaditfromtoptobottomandlefttoright,sotheexplanationwillbeginthere.Thefunctionstartsbyloopingthroughallthefilespassedasarguments.ItthenexpandsthemagainsttheBOARD_SEPOLICY_DIRSonceforreplaceandonceforaunion.Thesepolicy_replace_pathsvariableiserrorcheckedtoensureafiledoesnotappearinbothlocations,replaceandunion.Forthereplacepathexpansion,itcheckswhethertheexpandedpathisinsepolicy_replace_dirs,andifitis,replacesit.Fortheunionportion,itjustexpandsthem.TheresultsoftheseexpansionsarethenfedthroughafilteronBOARD_SEPOLICY_IGNORE,thusdroppinganyoftheexplicitlyignoredpaths:
#Buildspathsforallrequestedpolicyfilesw.r.t
#bothBOARD_SEPOLICY_REPLACEandBOARD_SEPOLICY_UNION
#productvariables.
#$(1):thesetofpolicynamepathstobuild
build_policy=$(foreachtype,$(1),\
$(filter-out$(BOARD_SEPOLICY_IGNORE),\
$(foreachexpanded_type,$(notdir$(wildcard$(addsuffix/$(type),
$(LOCAL_PATH)))),\
$(if$(filter$(expanded_type),$(BOARD_SEPOLICY_REPLACE)),\
$(wildcard$(addsuffix$(expanded_type),$(sort$(dir
$(sepolicy_replace_paths))))),\
$(LOCAL_PATH)/$(expanded_type)\
)\
)\
$(foreachunion_policy,$(wildcard$(addsuffix/$(type),
$(BOARD_SEPOLICY_DIRS))),\
$(if$(filter$(notdir$(union_policy)),$(BOARD_SEPOLICY_UNION)),\
$(union_policy),\
)\
)\
)\
)
...
www.it-ebooks.info
Buildingmac_permissions.xmlThemac_permissions.xmlbuildisabittricky,aswesawinChapter10,PlacingApplicationsinDomains.First,mac_permissions.xmlcanbeusedwithalltheBOARD_SEPOLICY_*variablesintroducedthusfar.TheendresultisoneXMLfileadheringtotherulesofthosevariables.Additionally,therawXMLfilesareprocessedbyatoolcalledinsertkeys.py,locatedinsepolicy/tools.Theinsertkeys.pytooluseskeys.conftomaptagsintheXMLfilesignaturestanzawith.pemfilescontainingthecertificate.Thekeys.conffileisalsosubjecttouseinBOARD_SEPOLICY_*variables.Thebuildrecipefirstcallsbuild_policyonkeys.confandusesm4toconcatenatetheresults.Thus,m4declarationsinkeys.confwillberespected.However,thishasnotbeenused.Theinitialintentionwastousethem4-ssynclinessothatyoucanfollowtheinclusionchaininthekeys.conffilewhenconcatenatedbym4processing.Ontheotherhand,synclinesareprovidedbym4whenconcatenatingmanyfiles,andtheyprovidecommentedlinesadheringtothe#lineNUM"FILE"'lines.Theseareusefulbecausem4takesmultipleinputfilesandcombinesthemintoasingle,expandedoutputfile.Therewillbesynclinesindicatingthebeginningofeachofthosefiles,andtheycanhelpyoutrackdownissues.Continuingbacktothemac_permissions.xmlbuild,afterexpansionofkeys.confbym4,thisfile,alongwithallthemac_permissions.xmlfilesfromacalltobuild_policy()arefinallyfedtoinsertkeys.py.Theinsertkeys.pytoolthenusesthekeys.conffiletoreplaceallmatchingsignature=<TAG>lineswithanactualhex-encodedX509fromthePEMfile,thatis,signature=308E3600.Additionally,theinsertkeys.pytoolcombinestheXMLfilesintoonefile,andstripswhitespaceandcommentstoreduceitssizeondisk.Thishasnobuilddependenciesontheothermajorfilessuchassepolicy,seapp_contexts,property_contexts,andmac_permissions.xml.
www.it-ebooks.info
Buildingseapp_contextsTheseapp_contextsfileisalsosubjecttoalltheBOARD_SEPOLICY_*variables.Alloftheseapp_contextsfilesfromaresultantcalltobuild_policy()arealsofedthroughm4-stogetasingleseapp_contextsfilethatcontainssynclines.Again,likemac_permissions.xmlfile’sbuildofkeys.conf,m4hasn’tbeenusedotherthanforthesynclines.Thisresulting,concatenatedseapp_contextsfileisthenfedintocheck_seapp.ThistoolisauthoredintheCprogramminglanguageandbuiltintoanexecutableduringthebuild.Thesourcecanbefoundintools/check_seapp.Thistoolreadstheseapp_contextsfileandchecksitssyntax.Itverifiesthattherearenoinvalidkeyvaluepairs,thatlevelFromisavalididentifier,andthatthetypeanddomainfieldsarevalidforagivensepolicy.Thisbuildisdependentonsepolicyforthestricttypecheckingofdomainandtypefieldsagainstthepolicyfile.
www.it-ebooks.info
Buildingfile_contextsThefile_contextsfileisalsosubjecttoalloftheBOARD_SEPOLICY_*variables.Theresultingsetispassedthroughm4-s,andthesingleoutputisrunthroughthecheckfctool.Thecheckfctoolchecksthegrammarandsyntaxofthefileandalsoverifiesthatthetypesexistinthebuiltsepolicy.Becauseofthis,itisdependentonthesepolicybuild.
www.it-ebooks.info
Buildingproperty_contextsTheproperty_contextsbehavesexactlylikethefile_contextsbuild,exceptthatitchecksaproperty_contextsfile.Italsousescheckfc.
www.it-ebooks.info
CurrentNSAresearchfilesAdditionally,workonEnterpriseOperations(eops)isalreadyunderwayattheNSA.Asthisfeaturehasn’tbeenmergedintomainstreamAndroidandislikelytochangewildly,itwon’tbecoveredhere.However,thebestplaceforthebleedingedgeisalwaysthesourceandNSABitbucketrepositories.Theselinux-network.shalsofallsunderthiscategory;ithasn’tseenmainstreamadoptionyet,andwilllikelybedroppedfromAOSP(https://android-review.googlesource.com/#/c/114380/).
www.it-ebooks.info
StandalonetoolsTherearealsosomestandalonetoolsbuiltforAndroidpolicyevaluationthatyoumayfinduseful.Wewillexploresomeofthemandtheirusages.Mostofthestandarddesktoptoolsyou’llfindinotherreferencesstillworkonSEforAndroidSELinuxpolicy.Notethatifyourunanyofthefollowingtoolsandgetasegmentationfault,youwilllikelyneedtoapplythepatchfromthethreadathttp://marc.info/?l=seandroid-list&m=141684060409894&w=2.
www.it-ebooks.info
sepolicy-checkThistoolallowsyoutoseewhetheragivenallowruleexistsinapolicyfile.Thebasicsyntaxofitscommandisasfollows:
sepolicy-check-s<domain>-t<type>-c<class>-p<permission>-P
<policy_file>
Forinstance,ifyouwanttoseewhethersystem_appcanwritetosystem_data_fileforclassfile,youcanexecute:
$sepolicy-check-ssystem_app-tsystem_data_file-cfile-pwrite-P
$OUT/root/sepolicy
www.it-ebooks.info
sepolicy-analyzeThisisagoodtooltocheckforcommonissuesinSELinuxdevelopmentanditcatchessomeofthecommonpitfallsofnewSELinuxpolicywriters.Itcancheckforequivalentdomains,duplicateallowrules.Itcanalsoperformpolicytypedifferencechecks.
Thedomainequivalencecheckfeatureisveryhelpful.Itshowsyoudomainsyoumay(intheory)wanttobedifferent,eventhoughtheyconvergedintheimplementation.Thesetypeswouldbeidealcandidatestocoalesce.However,itmighthavealsoshownanissueinthedesignofthepolicythatshouldbecorrected.Inotherwords,youdidn’texpectthesedomainstobeequivalent.Invokingthecommandisasfollows:
$sepolicy-analyze-e-P$OUT/root/sepolicy
Theduplicateallowrulecheckswhetherallowrulesexistontypesthatalsoexistonattributesthatthetypeinheritsfrom.Theallowruleonthespecifictypeisacandidateforremoval,sincethereisalreadyanallowontheattribute.Toexecutethischeck,runthefollowingcommand:
$sepolicy-analyze-D-P$OUT/root/sepolicy
Thedifferenceisalsohandyisalsohandytoviewtypedifferenceswithinafile.Ifyouwanttoseewhatthedifferencebetweentwodomainsis,youcanusethisfeature.Thisisusefulforidentifyingpossibledomainstocoalesce.Toperformthischeck,executethefollowingcommand:
$sepolicy-analyze-d-P$OUT/root/sepolicy
www.it-ebooks.info
SummaryInthischapter,wecoveredhowthevariouscomponentsthatcontrolthepolicyonthedeviceareactuallybuiltandcreated,suchassepolicyandmac_permissions.xml.ThischapteralsopresentedtheBOARD_SEPOLICY_*variablesusedtomanageandbuildapolicyacrossdevicesandconfigurations.ThenwereviewedtheAndroid.mkcomponents,detailinghowtheheartofthebuildandconfigurationmanagementworks.
www.it-ebooks.info
Chapter13.GettingtoEnforcingModeAsanengineer,you’rehandedsomeAndroiddevice,andtherequirementistoapplySEforAndroidcontrolstothedevicetoenhanceitssecurityposture.Sofar,wehaveseenallthepiecesthatneedtobeconfiguredandhowtheyworktoenablesuchasystem.Inthischapter,we’lltakealltheskillscoveredtogetourUDOOinenforcingmode.Wewill:
Run,evaluate,andrespondtoauditlogsfromCTSDevelopsecurepolicyfortheUDOOSwitchtoenforcingmode
www.it-ebooks.info
UpdatingtoSEPolicymasterManychangestothesepolicydirectoryhaveoccurredintheAOSPmasterbranchsincethe4.3release.Atthetimeofthiswriting,themasterbranchoftheexternal/sepolicyprojectwasonGitcommitSHAb5ffb.Theauthorsrecommendattemptingtousethemostrecentcommit.However,forillustrativepurposes,wewillshowyouhowtooptionallycheckoutcommitb5ffbsoyoucanaccuratelyfollowtheexamplesinthischapter.
First,you’llneedtoclonetheexternal/sepolicyproject.Intheseinstructions,weassumeyourworkingdirectoryhastheUDOOsourcescontainedinthe./udoodirectory:
$gitclonehttps://android.googlesource.com/platform/external/sepolicy
$cdsepolicy
Ifyouwanttofollowtheexamplesinthischapterprecisely,you’llneedtocheckoutcommitb5ffbwiththefollowingcommand.Ifyouskipit,youwillendupusingthelatestcommitinthemasterbranch:
$gitcheckoutb5ffb
Now,we’llreplacetheUDOO4.3sepolicywithwhatwejustacquiredfromGoogle:
$cd..
$rm-rfudoo/external/sepolicy
$cp-rsepolicyudoo/external/sepolicy
Optionally,youcanremovethe.gitfolderfromthenewlycopiedsepolicywiththefollowingcommand,butthisisnotnecessary:
$rm–rfudoo/external/sepolicy/.git
Also,copytheaudit.tefileandrestoreit.
Additionally,restoretheauditdcommitfromtheNSABitbucketseandroidrepository.Foryourreference,it’scommitSHAd270aa3.
Afterthat,removeallreferencestosetoolfromudoo/build/core/Makefile.Thiscommandwillhelpyoulocatethem:
$grep-nwsetooludoo/build/core/Makefile
www.it-ebooks.info
PurgingthedeviceAtthispoint,ourUDOOismessy,solet’sreflashit,includingthedatadirectory,andstartafresh.Wewanttohaveonlythecodeandtheinitscriptchanges,withouttheadditionalsepolicy.Thenwecanauthorapolicyproperlyandapplyallthetechniquesandtoolswe’veencountered.We’llstartbyresettingtoastateanalogoustothecompletionofChapter4,InstallationontheUDOO.However,themajordifferenceisweneedtobuildauserdebugversionratherthananengineering(eng)versionforCTS.Theversionisselectedinthesetupscript,whichultimatelycallslunch.Tobuildthisversion,executethefollowingcommandsfromtheUDOOworkspace:
$.setupudoo-userdebug
$make-j82>&1|teelogz
Flashthesystem,boottotheSDcard,andwipeuserdatawiththefollowingcommands,assumingtheSDcardisinsertedintothehostanduserdataisnotmounted:
$mkdir~/userdata
$sudomount/dev/sdd4~/userdata
$cd~/userdata/
$sudorm-rf*
$cd..
$sudoumount~/userdata
www.it-ebooks.info
SettingupCTSYoumustpassCTSifyourorganizationseeksAndroidbranding.However,evenifyoudon’t,it’sagoodideatoruntheseteststohelpensureadevicewillbecompliantwithapplications.Basedonyoursecuritygoalsanddesires,youmayfailportionsofCTSifyou’renotseekingAndroidbranding.Forourcase,we’relookingatCTSasawaytoexercisethesystemanduncoverpolicyissuesthatpreventtheproperfunctioningoftheUDOO.Itssourceislocatedinthects/directory,butwerecommenddownloadingthebinarydirectlyfromGoogle.YoucangetmoreinformationandtheCTSbinaryitselffromhttps://source.android.com/compatibility/cts-intro.htmlandhttps://source.android.com/compatibility/android-cts-manual.pdf.
DownloadtheCTS4.3binaryfromtheDownloadstab.ThenselecttheCTSbinary.TheCompatibilityDefinitionDocument(CDD)isalsoworthreading.Itcoversthehigh-leveldetailsofCTSandcompatibilityrequirements.
DownloadCTSfromhttps://source.android.com/compatibility/downloads.htmlandextractit.SelecttheCTSversionthatmatchesyourAndroidversion.Ifyoudon’tknowwhichversionyourdeviceisrunning,youcanalwayscheckthero.build.version.releasepropertyfromtheUDOOwithgetpropro.build.version.release:
$mkdir~/udoo-cts
$cd~/udoo-cts
$wgethttps://dl.google.com/dl/android/cts/android-cts-4.3_r2-linux_x86-
arm.zip
$unzipandroid-cts-4.3_r2-linux_x86-arm.zip
www.it-ebooks.info
RunningCTSTheCTSexercisesmanycomponentsonthedeviceandhelpstestvariouspartsofthesystem.Agood,generalpolicyshouldallowproperfunctioningofAndroidandpassCTS.
FollowthedirectionsintheAndroidCTSusermanualtosetupyourdevice(seeSection3.3,Settingupyourdevice).Typically,youwillseesomefailuresifyoudon’tfollowallthestepsprecisely,asyoumaynothavetheaccessorthecapabilitiestoacquirealltheresourcesneeded.However,CTSwillstillexercisesomecodepaths.Ataminimum,werecommendgettingthemediafilescopiedandWi-Fiactive.Onceyourdeviceissetup,ensureadbisactiveandinitiatethetesting:
$./cts-tradefed
11-3010:30:08I/:Detectednewdevice0123456789ABCDEF
cts-tf>runcts--planCTS
cts-tf>
timepasseshere
11-3010:30:28I/TestInvocation:Startinginvocationfor'cts'onbuild
'4.3_r2'ondevice0123456789ABCDEF
11-3010:30:28I/0123456789ABCDEF:Createdresultdir2014.11.30_10.30.28
11-3010:31:44I/0123456789ABCDEF:Collectingdeviceinfo
11-3010:31:45I/0123456789ABCDEF:----------------------------------------
-
11-3010:31:45I/0123456789ABCDEF:Testpackageandroid.aadbstarted
11-3010:31:45I/0123456789ABCDEF:----------------------------------------
-
11-3010:32:15I/0123456789ABCDEF:
com.android.cts.aadb.TestDeviceFuncTest#testBugreportPASS
...
Theteststakemanyhourstoexecute,sobepatient;butyoucancheckthestatusofthetest:
cts-tf>li
CommandIdExecTimeDeviceState
18m:220123456789ABCDEFrunningctsonbuild4.3_r2
Pluginspeakerstoenjoythesoundsfromthemediatestsandringtones!Also,CTSrebootsthedevice.IfyourADBsessionisnotrestoredafterrebooting,ADBmaynotexecuteanytests.Usethe--disable-rebootoptionwhenrunningthects-tf>runcts--planCTS--disable-rebootplan.
www.it-ebooks.info
GatheringtheresultsFirst,we’llconsidertheCTSresults.Althoughweexpectsomefailures,wealsoexpecttheproblemwillnotgetworsewhenwegotoenforcingmode.Second,we’lllookattheauditlogs.Let’spullbothofthesefilesfromthedevice.
www.it-ebooks.info
CTStestresultsCTScreatesatestresultsdirectoryeachtimeitisrun.CTSisindicatingthedirectorynamebutnotthelocation:
11-3010:30:28I/0123456789ABCDEF:Createdresultdir2014.11.30_10.30.28
ThelocationismentionedbytheCTSmanualandcanbefoundundertheextractedCTSdirectoryinrepository/results,typicallyatandroid-cts/repository/results.ThetestdirectoriescontainanXMLtestreport,testResult.xml.Thiscanbeopenedinmostwebbrowsers.Ithasaniceoverviewofthetestsanddetailsofallexecutedtests.Thepass:failratioisourbaseline.Theauthorshad18,736pass,andonly53fail,whichisfairlygoodconsideringhalfofthosearefeatureissues,suchasnoBluetoothorreturningtrueforcamerasupport.
www.it-ebooks.info
AuditlogsWewillusetheauditlogstoaddressdeficienciesinourpolicy.Pulltheseoffthedeviceusingthestandardadbpullcommandswehaveusedthroughoutthebook.Sincethisisauserdebugbuildanddefaultadbterminalsareshelluid(notroot),startadbasrootwithadbroot.suisalsoavailableonuserdebugbuilds.
TipYoumaygetanerrorsaying/data/misc/audit/audit.logdoesnotexist.Thesolutionistorunadbasrootviatheadbrootcommand.Also,whenrunningthiscommand,itmayhang.Justgotosettings,disable,andthenenableUSBDebuggingunderDeveloperOptions.Thenkilltheadb-rootcommandandverifyyouhaverootbyrunningadbshell.Nowyoushouldbearootuseragain.
www.it-ebooks.info
AuthoringdevicepolicyRunbothaudit.logandaudit.oldthroughaudit2allowtoseewhat’sgoingon.Theoutputofaudit2allowisgroupedbysourcedomain.Ratherthangoingthroughitall,wewillhighlighttheunusualcases,startingwiththeinterpretedresultsofaudit2allow.Assumingyouareintheauditlogdirectory,performcataudit.*|audit2allow|less.Anypolicyworkwillbedoneinthedevice-specificUDOOsepolicydirectory.
www.it-ebooks.info
adbdThefollowingareouradbddenialsasfilteredthroughaudit2allow:
#=============adbd==============
allowadbdashmem_device:chr_fileexecute;
allowadbddumpstate:unix_stream_socketconnectto;
allowadbddumpstate_socket:sock_filewrite;
allowadbdinput_device:chr_file{writegetattropen};
allowadbdlog_device:chr_file{writereadioctlopen};
allowadbdlogcat_exec:file{readgetattropenexecuteexecute_no_trans};
allowadbdmediaserver:binder{transfercall};
allowadbdmediaserver:fduse;
allowadbdself:capability{net_rawdac_override};
allowadbdself:processexecmem;
allowadbdshell_data_file:file{executeexecute_no_trans};
allowadbdsystem_server:binder{transfercall};
allowadbdtmpfs:fileexecute;
allowadbdunlabeled:dirgetattr;
Thedenialsintheadbddomainarequitestrange.Thefirstthingthatcaughtoureyewastheexecuteon/dev/ashmem,whichisacharacterdriver.Typically,thisisonlyneededforDalvikJIT.Lookingattherawaudits(cataudit.*|grepadbd|grepexecute),weseethefollowing:
type=1400msg=audit(1417416666.182:788):avc:denied{execute}for
pid=3680comm="Compiler"
path=2F6465762F6173686D656D2F64616C76696B2D6A69742D636F64652D63616368652028
64656C6574656429dev=tmpfsino=412027scontext=u:r:adbd:s0
tcontext=u:object_r:tmpfs:s0tclass=file
type=1400msg=audit(1417416670.352:831):avc:denied{execute}for
pid=3753comm="Compiler"path="/dev/ashmem"dev=tmpfsino=1127
scontext=u:r:adbd:s0tcontext=u:object_r:ashmem_device:s0tclass=chr_file
Somethingwiththeprocesscommfieldofthecompilerisexecutingonashmem.OurguessisithassomethingtodowithDalvik,butwhyisitintheadbddomain?Also,whyisadbdwritingtotheinputdevice?Allthisisstrangebehavior.Typically,whenyouseethingslikethis,it’sbecausethechildrendidn’tendupintheproperdomain.Runthiscommandtocheckthedomainsandconfirmoursuspicions:
$adbshellps-Z|grepadbd
u:r:adbd:s0root200461/sbin/adbd
u:r:adbd:s0root2010120046ps
Wethenrunadbshellps-Z|grepadbdtoseewhichthingswererunningintheadbdomain,furtherconfirmingoursuspicions:
u:r:adbd:s0root200461/sbin/adbd
u:r:adbd:s0root2010120046ps
Thepscommandshouldnotberunningintheadbdcontext;itshouldberunninginshell.Thisconfirmedthatshellisnotintherightdomain:
$adbshell
www.it-ebooks.info
root@udoo:/#id
uid=0(root)gid=0(root)context=u:r:adbd:s0
Thefirstthingtocheckisthecontextonthefile:
root@udoo:/#ls-Z/system/bin/sh
lrwxr-xr-xrootshellu:object_r:system_file:s0sh->mksh
root@udoo:/#ls-Z/system/bin/mksh
-rwxr-xr-xrootshellu:object_r:system_file:s0mksh
Thebasepolicydefinesadomaintransitionwhenadbdloadstheshellusingexectogototheshelldomain.Thisisdefinedintheadbd.teexternalsepolicyasdomain_auto_trans(adbd,shell_exec,shell).
Obviously,anincorrectlabelhasbeenappliedtoshell,solet’slookatfile_contextsintheexternalsepolicytofindoutwhy.
$catfile_contexts|grepshell_exec
/system/bin/sh—u:object_r:shell_exec:s0
Thetwodashesmeanthatonlyregularfileswillbelabeledandsymboliclinkswillbeskipped.Weprobablydon’twanttolabelthesymlink,butratherthemkshdestination.Dothisbyaddingacustomfile_contextsentrytothedeviceUDOOsepolicyandaddingthefiletotheBOARD_SEPOLICY_UNIONconfig.Infile_contexts,add/system/bin/mksh—u:object_r:shell_exec:s0,andinsepolicy.mk,addBOARD_SEPOLICY_UNION+=file_contexts.
TipThroughouttheremainderofthechapter,wheneveryoucreateormodifypolicyfiles(forexample,contextfilesor*.tefiles),don’tforgettoaddthemtoBOARD_SEPOLICY_UNIONinsepolicy.mk.
Sincethisisafairlyfatalissuewiththepolicyandadbd,wewon’tworryaboutthedenialsfornow,withtheexceptionoftheunlabeled.Wheneveroneencountersanunlabeledfile,itshouldbeaddressed.Theavcdenialthatcausedthisisasfollows:
type=1400msg=audit(1417405835.872:435):avc:denied{getattr}for
pid=4078comm="ls"path="/device"dev=mmcblk0p7ino=2scontext=u:r:adbd:s0
tcontext=u:object_r:unlabeled:s0tclass=dir
Becausethisismountedat/deviceandAndroidmountsaretypicallyat/,weshouldlookatthemounttable:
root@udoo:/#mount|grepdevice
/dev/block/mmcblk0p7/deviceext4
ro,seclabel,nosuid,nodev,relatime,user_xattr,barrier=1,data=ordered00
Typically,mountcommandsareintheinitscriptsfollowingamkdir,orinanfstabfilewiththeinitbuilt-in,mount_all.Aquicksearchfordeviceandmkdirininit.rcfindsnothing,butwedofinditinfstab.freescale.Thedeviceisread-only,soweshouldbeabletogiveitatype,labelitwithfilecontexts,andapplythegetattrdomaintoitsdirectoryclass.Sinceit’sread-onlyandempty,nobodyshouldneedmorepermissions.Lookingatthemake_sd.shscript,wenoticethatpartition7oftheblockdeviceisthe
www.it-ebooks.info
venderdirectory.ThisisamisspellingofthecommonvendordirectorythatOEMsplaceproprietaryblobsin.Weplacefiletypesinfile.teandthedomainallowrulesindomain.te.
Infile.te,addthis:
typeudoo_device_file,file_type;
Indomain.te,addthefollowing:
allowdomainudoo_device_file:dirgetattr;
Infile_contexts,addthis:
/deviceu:object_r:udoo_device_file:s0
Ifthisdirectoryisnotempty,youmustmanuallyrunrestorecon-Ronittolabelexistingfiles.
IfyoupulltheauditlogsmultipletimesfromtheUDOO,youmayalsoendupwithdenialsshowingthatyoudidso,asadbdwillnotbeabletoaccessthem.Youmayseethis:
#=============adbd==============
allowadbdaudit_log:file{readgetattropen};
Thisrulecomesfromtheendofthetestwhenyouadbpulledtheauditlogs.Wecansafelydontauditthisandaddaneverallowtoensureitdoesn’taccidentallygetallowed.Theauditlogscontaininformationamalwarewritercouldusetonavigatethroughthepolicy,andthisinformationshouldbeprotected.Inadevicesepolicyfolder,addanadbd.tefileandunionitinthesepolicy.mkfile:
Inadbd.te,addthis:
#dontauditadbpullandadbshellcatofauditlogs
dontauditadbdaudit_log:filer_file_perms;
dontauditshellaudit_log:filer_file_perms;
Inauditd.te,addthis:
#Makesurenooneaddsanallowtotheauditlogs
#fromanythingbutsystemserver(readonly)and
#auditd,rwaccess.
neverallow{domain-system_server-auditd-init-kernel}audit_log:file
~getattr;
neverallowsystem_serveraudit_log:file~r_file_perms;
Ifauditd.teisstillinexternal/sepolicy,moveittodevice/fsl/udoo/sepolicyalongwithalldependenttypes.
Theneverallowentriesshowyouhowtousethecompliment,~,andsetdifference,-,operatorsforstrongassertionsorbrevity.Thefirstneverallowstartswithdomain,andallprocesstypes(domains)aremembersofthedomainattribute.Wepreventaccessthroughsetdifference,leavingthesetthatmustneverhaveaccess.Wethencomplimenttheaccessvectorsettoallowonlygetattrorstatonthelogs.Thesecondneverallowusescomplimenttoensuresystem_serverislimitedtoreadoperations.
www.it-ebooks.info
bootanimThebootanimdomainisassignedtothebootanimationservicethatpresentssplashscreensonboot,typicallythecarrier’sbranding:
#=============bootanim==============
allowbootaniminit:unix_stream_socketconnectto;
allowbootanimlog_device:chr_file{writeopen};
allowbootanimproperty_socket:sock_filewrite;
Anythingtouchingtheinitdomainisaredflag.Here,bootanimconnectstoaninitUnixdomainsocket.Thisisapartofthepropertysystem,andwecanseethatafterconnecting,itwritestothepropertysocket.ThesocketobjectanditsURIareseparate.Inthiscase,it’sthefilesystem,butitcouldbeananonymoussocket:
type=1400msg=audit(1417405616.640:255):avc:denied{connectto}for
pid=2534comm="BootAnimation"path="/dev/socket/property_service"
scontext=u:r:bootanim:s0tcontext=u:r:init:s0tclass=unix_stream_socket
Thelog_deviceisdeprecatedinnewversionsofAndroidandreplacedwithlogd.However,wearebackportinganewmastersepolicyto4.3,sowemustsupportthis.Thepatchthatremovedsupportisathttps://android-review.googlesource.com/#/c/108147/.
Ratherthanapplyareversepatchtotheexternalsepolicy,wecanjustaddtherulestoourdevicepolicyinadomain.tefile.WecansafelyallowtheseusingthepropermacrosandstylesinthedeviceUDOOsepolicyfolder.Inbootanim.te,addunix_socket_connect(bootanim,property,init),andindomain.te,addthis:
allowdomainudoo_device_file:dirgetattr;
allowdomainlog_device:dirsearch;
allowdomainlog_device:chr_filerw_file_perms;
www.it-ebooks.info
debuggerd#=============debuggerd==============
allowdebuggerdlog_device:chr_file{writereadopen};
allowdebuggerdsystem_data_file:sock_filewrite;
Thelogdevicedenialwasaddressedunderbootanimbyaddingtheallowrulesforalldomainstouselog_device.Thesystem_data_file:sock_filewriteisstrange.Inmostcircumstances,you’llalmostneverwanttoallowacross-domainwrite,butthisisspecial.Lookattherawdenial:
type=1400msg=audit(1417415122.602:502):avc:denied{write}forpid=2284
comm="debuggerd"name="ndebugsocket"dev=mmcblk0p4ino=129525
scontext=u:r:debuggerd:s0tcontext=u:object_r:system_data_file:s0
tclass=sock_file
Thedenialisonndebugsocket.Greppingforthisuncoversanamedtypetransition,whichpolicyversion23doesnotsupport:
system_server.te:297:type_transitionsystem_server
system_data_file:sock_filesystem_ndebug_socket"ndebugsocket";
Wehavetochangethecodetosetthepropercontextorjustallowit,whichwewill.Wewon’tgrantadditionalpermissionsbecauseitneveraskedforopen,andwe’recrossingdomains.Preventingfileopensacrossdomainsisideal,astheonlywaytogetthisfiledescriptoristhroughanIPCcallintotheowningdomain.Indebuggerd.te,addallowdebuggerdsystem_data_file:sock_filewrite;.
www.it-ebooks.info
drmserver#=============drmserver==============
allowdrmserverlog_device:chr_file{writeopen};
Thisistakencareofbydomain.terules,sowehavenothingtodohere.
www.it-ebooks.info
dumpstate#=============dumpstate==============
allowdumpstateinit:bindercall;
allowdumpstateinit:processsignal;
allowdumpstatelog_device:chr_file{writereadopen};
allowdumpstatenode:rawip_socketnode_bind;
allowdumpstateself:capabilitysys_resource;
allowdumpstatesystem_data_file:file{writerenamecreatesetattr};
Thedenialtoinit:bindercallondumpstateisstrangebecauseinitdoesn’tusebinder.Someprocessmuststayintheinitdomain.Let’scheckourprocesslistingforinit:
$adbshellps-Z|grepinit
u:r:init:s0root10/init
u:r:init:s0root22861zygote
u:r:init:s0radio27592286com.android.phone
Here,zygoteandcom.android.phoneshouldnotberunningasinit.Thismustbealabelingerrorontheapp_processfile,whichisthezygote.Thels-laZ/system/bin/app_processcommandrevealsu:object_r:system_file:s0app_process,soaddanentrytofile_contextstocorrectthis.Wecanfindthelabeltouseinzygote.teinthebasesepolicydefinedasthezygote_exectype:
#zygote
typezygote,domain;
typezygote_exec,exec_type,file_type;
Infile_contexts,add/system/bin/app_processu:object_r:zygote_exec:s0.
www.it-ebooks.info
keystore#=============keystore==============
allowkeystoreapp_data_file:filewrite;
allowkeystorelog_device:chr_file{writeopen};
Thelogdeviceistakencareofbythedomain.terules.Let’slookattherawapp_data_filedenial:
type=1400msg=audit(1417417454.442:845):avc:denied{write}for
pid=15339comm="onCtsTestRunner"
path="/data/data/com.android.cts.stub/cache/CTS_DUMP"dev=mmcblk0p4
ino=131242scontext=u:r:keystore:s0
tcontext=u:object_r:app_data_file:s0:c512,c768tclass=file
Categoriesaredefinedinthecontexts.ThismeansMLSsupportisactivatedforappdomains.Intheseapp_contextsbasesepolicy,weseethis:
user=_appdomain=untrusted_apptype=app_data_filelevelFrom=user
user=_appseinfo=platformdomain=platform_apptype=app_data_file
levelFrom=user
MLSseparationofapplicationdataisstillunderdevelopmentanddidn’tworkon4.3,sowecandisablethis.Wecanjustdeclaretheminadevice-specificseapp_contextsfile.Inseapp_contexts,adduser=_appdomain=untrusted_apptype=app_data_fileanduser=_appseinfo=platformdomain=platform_apptype=app_data_file.In4.3,anychangestocontextondatarequireafactoryreset.The4.4versionaddedsmartrelabelcapabilities.
www.it-ebooks.info
mediaserver#=============mediaserver==============
allowmediaserveradbd:binder{transfercall};
allowmediaserverinit:binder{transfercall};
allowmediaserverlog_device:chr_file{writeopen};
Thelogdevicewasaddressedinthedomain.terules.We’llskipinitandadbdtoo,sincetheirissuesweretriggeredbyimproperprocessdomains.It’simportantnottoaddallowrulesblindly,asmostoftheworkforexistingdomainscanbehandledwithsmalllabelchangesorafewrules.
www.it-ebooks.info
netd#=============netd==============
allownetdkernel:systemmodule_request;
allownetdlog_device:chr_file{writeopen};
Thelogdevicedenialofnetdwasaddressedbydomain.te.However,weshouldscrutinizeanythingrequestingacapability.Whengrantingcapabilities,thepolicyauthorneedstobeverycareful.Ifadomainisgrantedtheabilitytoloadasystemmoduleandthatdomainormodulebinaryitselfiscompromised,itcouldleadtotheinjectionofmalwareintothekernelvialoadablemodules.However,netdneedsloadablekernelmodulesupporttosupportsomecards.Addtheallowruletoafilecallednetd.teinthedeviceUDOOsepolicy.Innetd.te,addallownetdself:capabilitysys_module;.
www.it-ebooks.info
rild#=============rild==============
allowrildlog_device:chr_file{writeopen};
Thisistakencareofbydomain.terules,sowehavenothingtodohere.
www.it-ebooks.info
servicemanager#=============servicemanager==============
allowservicemanagerinit:bindertransfer;
allowservicemanagerlog_device:chr_file{writeopen};
Again,thelogdevicewashandledindomain.te.We’llskipinit,sinceitsissuesweretriggeredbyimproperprocessdomains.
www.it-ebooks.info
surfaceflinger#=============surfaceflinger==============
allowsurfaceflingerinit:bindertransfer;
allowsurfaceflingerlog_device:chr_file{writeopen};
Again,thelogdevicewashandledindomain.te.We’llskipinittoo,sinceitsissuesweretriggeredbyimproperprocessdomains.
www.it-ebooks.info
system_server#=============system_server==============
allowsystem_serveradbd:binder{transfercall};
allowsystem_serverdalvikcache_data_file:file{writesetattr};
allowsystem_serverinit:binder{transfercall};
allowsystem_serverinit:filewrite;
allowsystem_serverinit:process{setschedsigkillgetsched};
allowsystem_serverinit_tmpfs:fileread;
allowsystem_serverlog_device:chr_filewrite;
Sincelog_deviceistakencareofbydomain.te,andinitandadbdarepolluted,wewillonlyaddresstheDalvikcachedenial:
type=1400msg=audit(1417405611.550:159):avc:denied{write}forpid=2571
comm="er.ServerThread"name="system@[email protected]@classes.dex"
dev=mmcblk0p4ino=129458scontext=u:r:system_server:s0
tcontext=u:object_r:dalvikcache_data_file:s0tclass=file
type=1400msg=audit(1417405611.550:160):avc:denied{setattr}for
pid=2571comm="er.ServerThread"
name="system@[email protected]@classes.dex"dev=mmcblk0p4ino=129458
scontext=u:r:system_server:s0tcontext=u:object_r:dalvikcache_data_file:s0
tclass=file
Theexternalsepolicyseandroid-4.3branchalloweddomain.te:allowdomaindalvikcache_data_file:filer_file_perms;.Writeswereallowedbysystem_appwithsystem_app.te:allowsystem_appdalvikcache_data_file:file{writesetattr
};.WeshouldbeabletograntthiswriteaccessbecausetheremaybeaneedtoupdateitsDalvikcachefile.Indomain.te,addallowdomaindalvikcache_data_file:filer_file_perms;,andinsystem_server.te,addallowsystem_serverdalvikcache_data_file:file{writesetattr};.
www.it-ebooks.info
toolbox#=============toolbox==============
allowtoolboxsysfs:filewrite;
Typically,oneshouldnotwritetosysfs.Nowlookattherawdenialfortheoffendingsysfsfile:
type=1400msg=audit(1417405599.660:43):avc:denied{write}forpid=2309
comm="cat"path="/sys/module/usbtouchscreen/parameters/calibration"
dev=sysfsino=2318scontext=u:r:toolbox:s0tcontext=u:object_r:sysfs:s0
tclass=file
Fromhere,weproperlylabel/sys/module/usbtouchscreen/parameters/calibration.Weplaceanentryinfile_contextstolabelsysfs,declareatypeinfile.te,andallowtoolboxaccesstoit.Infile.te,addtypesysfs_touchscreen_calibration,fs_type,sysfs_type,mlstrustedobject;,andinfile_contexts,add/sys/module/usbtouchscreen/parameters/calibration—
u:object_r:sysfs_touchscreen_calibration:s0,andintoolbox.te,addallowtoolboxsysfs_touchscreen_calibration:filew_file_perms;.
www.it-ebooks.info
untrusted_app#=============untrusted_app==============
allowuntrusted_appadb_device:chr_filegetattr;
allowuntrusted_appadbd:binder{transfercall};
allowuntrusted_appadbd:dir{readgetattropensearch};
allowuntrusted_appadbd:file{readgetattropen};
allowuntrusted_appadbd:lnk_fileread;
...
untrusted_apphadmanydenials.Consideringthedomainlabelingissues,wewon’taddressmostofthesenow.However,youshouldlookoutformislabeledandunlabeledtargetfiles.Whilesearchingthedeniallogsasinterpretedbyaudit2allow,thefollowingwasfound:
allowuntrusted_appdevice:chr_file{readgetattr};
allowuntrusted_appunlabeled:dir{readgetattropen};
Forthechr_filedevice,wegetthis:
type=1400msg=audit(1417416653.742:620):avc:denied{read}forpid=3696
comm="onCtsTestRunner"name="rfkill"dev=tmpfsino=1126
scontext=u:r:untrusted_app:s0:c512,c768tcontext=u:object_r:device:s0
tclass=chr_file
type=1400msg=audit(1417416666.152:784):avc:denied{getattr}for
pid=3696comm="onCtsTestRunner"path="/dev/mxs_viim"dev=tmpfsino=1131
scontext=u:r:untrusted_app:s0:c512,c768tcontext=u:object_r:device:s0
tclass=chr_file
type=1400msg=audit(1417416653.592:561):avc:denied{getattr}for
pid=3696comm="onCtsTestRunner"path="/dev/.coldboot_done"dev=tmpfs
ino=578scontext=u:r:untrusted_app:s0:c512,c768
tcontext=u:object_r:device:s0tclass=file
Therefore,weneedtolabel/dev/.coldboot_done,/dev/rfkillproperly,and/dev/mxs_viim./dev/rfkillshouldbelabeledinlinewithwhatthe4.3policyhad:
file_contexts:/sys/class/rfkill/rfkill[0-9]*/state—
u:object_r:sysfs_bluetooth_writable:s0
file_contexts:/sys/class/rfkill/rfkill[0-9]*/type—
u:object_r:sysfs_bluetooth_writable:s0
The/dev/mxs_viimdeviceseemstobeagloballyaccessibleGPU.Werecommendathoroughreviewofthesourcecode,butfornow,wewilllabelitasgpu_device./dev/.coldboot_doneiscreatedbyueventdwhenthecoldbootprocesscompletes.Ifueventdisrestarted,itskipsthecoldboot.Wedon’tneedtolabelthis.ThisdenialiscausedbythesourcedomainMLSonatargetfilethatisnotasubsetofthecategoriesofthesourceanddoesnothavethemlstrustedsubjectattribute;itshouldgoawaywhenwedropMLSsupportfromapps.
Infile_contexts:
#touchscreencalibration
/sys/module/usbtouchscreen/parameters/calibration—
u:object_r:sysfs_touchscreen_calibration:s0
www.it-ebooks.info
#BTRFKillnode
/sys/class/rfkill/rfkill[0-9]*/state—u:object_r:sysfs_bluetooth_writable:s0
/sys/class/rfkill/rfkill[0-9]*/type—u:object_r:sysfs_bluetooth_writable:s0
www.it-ebooks.info
vold#=============vold==============
allowvoldlog_device:chr_file{writeopen};
Again,thelogdevicewashandledindomain.te.
www.it-ebooks.info
watchdogd#=============watchdogd==============
allowwatchdogddevice:chr_file{readwritecreateunlinkopen};
Therawdenialsfromwatchdogpaintininterestingportrait:
type=1400msg=audit(1417405598.000:8):avc:denied{create}forpid=2267
comm="watchdogd"name="__null__"scontext=u:r:watchdogd:s0
tcontext=u:object_r:device:s0tclass=chr_file
type=1400msg=audit(1417405598.000:9):avc:denied{readwrite}for
pid=2267comm="watchdogd"name="__null__"dev=tmpfsino=2580
scontext=u:r:watchdogd:s0tcontext=u:object_r:device:s0tclass=chr_file
type=1400msg=audit(1417405598.000:10):avc:denied{open}forpid=2267
comm="watchdogd"name="__null__"dev=tmpfsino=2580
scontext=u:r:watchdogd:s0tcontext=u:object_r:device:s0tclass=chr_file
type=1400msg=audit(1417405598.000:11):avc:denied{unlink}forpid=2267
comm="watchdogd"name="__null__"dev=tmpfsino=2580
scontext=u:r:watchdogd:s0tcontext=u:object_r:device:s0tclass=chr_file
type=1400msg=audit(1417416653.602:575):avc:denied{getattr}for
pid=3696comm="onCtsTestRunner"path="/dev/watchdog"dev=tmpfsino=1095
scontext=u:r:untrusted_app:s0:c512,c768
tcontext=u:object_r:watchdog_device:s0tclass=chr_file
Afileiscreatedandunlinkedbywatchdog,whichkeepsahandletoananonymousfile.Nofilesystemreferenceexistsaftertheunlink,butthefiledescriptorisvalidandonlywatchdogcanuseit.Inthiscase,wecanjustallowwatchdogthisrule.Inwatchdogd.te,addallowwatchdogddevice:chr_filecreate_file_perms;.Thisrule,however,causesaneverallowviolationinthebasepolicy:
out/host/linux-x86/bin/checkpolicy:loadingpolicyconfigurationfrom
out/target/product/udoo/obj/ETC/sepolicy_intermediates/policy.conf
libsepol.check_assertion_helper:neverallowonline5375violatedbyallow
watchdogddevice:chr_file{readwriteopen};
Errorwhileexpandingpolicy
Theneverallowruleisinthedomain.tebasepolicyasneverallow{domain-init-ueventd-recovery}device:chr_file{openreadwrite};.Forsuchasimplechange,we’lljustmodifythebasesepolicytoneverallow{domain-init-ueventd-recovery-watchdogd}device:chr_file{openreadwrite};.
www.it-ebooks.info
wpa#=============wpa==============
allowwpadevice:chr_file{readopen};
allowwpalog_device:chr_file{writeopen};
allowwpasystem_data_file:dir{writeremove_nameadd_namesetattr};
allowwpasystem_data_file:sock_file{writecreateunlinksetattr};
Again,thelogdevicewashandledindomain.te.Thesystemdataaccessesneedfurtherinvestigation,startingwiththerawdenials:
type=1400msg=audit(1417405614.060:193):avc:denied{setattr}for
pid=2639comm="wpa_supplicant"name="wpa_supplicant"dev=mmcblk0p4
ino=129295scontext=u:r:wpa:s0tcontext=u:object_r:system_data_file:s0
tclass=dir
type=1400msg=audit(1417405614.060:194):avc:denied{write}forpid=2639
comm="wpa_supplicant"name="wlan0"dev=mmcblk0p4ino=129318
scontext=u:r:wpa:s0tcontext=u:object_r:system_data_file:s0
tclass=sock_file
type=1400msg=audit(1417405614.060:195):avc:denied{write}forpid=2639
comm="wpa_supplicant"name="wpa_supplicant"dev=mmcblk0p4ino=129295
scontext=u:r:wpa:s0tcontext=u:object_r:system_data_file:s0tclass=dir
type=1400msg=audit(1417405614.060:196):avc:denied{remove_name}for
pid=2639co
Theoffendingfilewaslocatedusingls-laR:
/data/system/wpa_supplicant:
srwxrwx---wifiwifi2014-12-0106:43wlan0
Thissocketiscreatedbythewpa_supplicantitself.Relabelingitwithouttypetransitionsisimpossible,sowehavetoallowit.Inwpa.te,addallowwpasystem_data_file:dirrw_dir_perms;andallowwpasystem_data_file:sock_filecreate_file_perms;.Theunlabeleddevicehasalreadybeendealtwith;itwasonrfkill:
type=1400msg=audit(1417405613.640:175):avc:denied{read}forpid=2639
comm="wpa_supplicant"name="rfkill"dev=tmpfsino=1126scontext=u:r:wpa:s0
tcontext=u:object_r:device:s0tclass=chr_file
www.it-ebooks.info
SecondpolicypassAfterloadingthedraftedpolicy,thedevicestillhasdenialsonboot:
#=============init==============
allowinitrootfs:file{writecreate};
allowinitsystem_file:fileexecute_no_trans;
#=============shell==============
allowshelldevice:chr_file{readwritegetattr};
allowshellsystem_file:fileentrypoint;
Allofthesedenialsshouldbeinvestigatedbecausetheytargetsensitivetypes,tcontextspecifically.
www.it-ebooks.info
initTherawdenialsforinitareasfollows:
<5>type=1400audit(4.380:3):avc:denied{create}forpid=2268
comm="init"name="tasks"scontext=u:r:init:s0tcontext=u:object_r:rootfs:s0
tclass=file
<5>type=1400audit(4.380:4):avc:denied{write}forpid=2268comm="init"
name="tasks"dev=rootfsino=3080scontext=u:r:init:s0
tcontext=u:object_r:rootfs:s0tclass=file
Theseoccurbeforeinitremounts/asread-only.Wecansafelyallowthese,andsinceinitisrunningunconfined,wecanjustaddittoinit.te.Wecouldaddtheallowruletotheunconfinedset,butsincethatisgoingaway,let’sminimizethepermissiononlytoinit:
allowintrootfs:filecreate_file_perms;
NoteUnconfinedisnotcompletelyunconfined.RulesgetstrippedfromthisdomainasAOSPmovesclosertozerounconfineddomains.
Doingthis,however,causesanotherneverallowtofail.Wecanmodifyexternal/sepolicydomain.tetobypassthis.Changetheneverallowfromthis:
#Nothingshouldbewritingtofilesintherootfs.
neverallow{domain-recovery}rootfs:file{createwritesetattrrelabelto
appendunlinklinkrename};
Changeittothis:
#Nothingshouldbewritingtofilesintherootfs.
neverallow{domain-recovery-init}rootfs:file{createwritesetattr
relabeltoappendunlinklinkrename};
NoteIfyouneedtomodifyneverallowentriestobuild,youwillfailCTS.Theproperapproachistoremovethisbehaviorfrominit.
Additionally,weneedtoseewhatisloadedwithexecwithoutadomaintransition,causingtheexecute_no_transdenial:
<5>type=1400audit(4.460:6):avc:denied{execute_no_trans}forpid=2292
comm="init"path="/system/bin/magd"dev=mmcblk0p5ino=146
scontext=u:r:init:s0tcontext=u:object_r:system_file:s0tclass=file
<5>type=1400audit(4.460:6):avc:denied{execute_no_trans}forpid=2292
comm="init"path="/system/bin/rfkill"dev=mmcblk0p5ino=148
scontext=u:r:init:s0tcontext=u:object_r:system_file:s0tclass=file
Toresolvethis,wecanrelabelmagdwithitsowntypeandplaceitinitsownunconfineddomain.Aneverallowinthebasepolicyforcesustomoveeachexecutableintoitsowndomain.
www.it-ebooks.info
Createafilecalledmagd.te,addittoBOARD_SEPOLICY_UNION,andaddthefollowingcontentstoit:
typemagd,domain;
typemagd_exec,exec_type,file_type;
permissive_or_unconfined(magd);
Alsoupdatefile_contextstocontainthis:
/system/bin/magdu:object_r:magd_exec:s0
Repeatthestepsthatweredoneformagdforrfkill.Justreplacemagdwithrfkillintheprecedingexample.Latertestingrevealedanentry-pointdenialwherethesourcecontextwasinit_shellandthetargetwasrfkill_exec.Afteraddingtheshellrules,itwasdiscoveredthatrfkillisloadedusingexecfromtheinit_shelldomain,solet’salsoadddomain_auto_trans(init_shell,rfkill_exec,rfkill)totherfkill.tefile.Additionallygroupedwiththisdiscoverywasrfkillattemptingtoopen,read,andwrite/dev/rfkill.Sowemustlabel/dev/rfkillwithrfkill_device,allowrfkillaccesstoit,andappendallowrfkillrfkill_device:chr_filerw_file_perms;totherfkill.tefile.Createanewfiletodeclarethisdevicetype,calleddevice.te,andaddtyperfkill_device,dev_type;.Afterthat,labelitwithfile_contextsbyadding/dev/rfkillu:object_r:rfkill_device:s0.
www.it-ebooks.info
shellThefirstshelldenialwewillevaluateisthedenialonentrypoint:
<5>type=1400audit(4.460:5):avc:denied{entrypoint}forpid=2279
comm="init"path="/system/bin/mksh"dev=mmcblk0p5ino=154
scontext=u:r:shell:s0tcontext=u:object_r:system_file:s0tclass=file
Sincewedidnotlabelmksh,weneedtolabelitnow.Wecancreateanunconfineddomainforshellsspawnedbyinittoendupintheinit_shelldomain.Theconsolestillendsupintheshelldomainviaanexplicitseclabel,andotherinvocationsendupasinit_shell.Createanewfile,init_shell.te,andaddittoBOARD_SEPOLICY_UNION.
www.it-ebooks.info
init_shell.tetypeinit_shell,domain;
domain_auto_trans(init,shell_exec,init_shell);
permissive_or_unconfined(init_shell);
Updatefile_contextstoincludethis:
/system/bin/mkshu:object_r:shell_exec:s0;
Nowwewillhandleshellaccesstotherawdevice:
<5>type=1400audit(6.510:7):avc:denied{readwrite}forpid=2279
comm="sh"name="ttymxc1"dev=tmpfsino=122scontext=u:r:shell:s0
tcontext=u:object_r:device:s0tclass=chr_file
<5>type=1400audit(7.339:8):avc:denied{getattr}forpid=2279comm="sh"
path="/dev/ttymxc1"dev=tmpfsino=122scontext=u:r:shell:s0
tcontext=u:object_r:device:s0tclass=chr_file
Thisisjustamislabeledtty,sowecanlabelthisasatty_device.Addthefollowingentrytothefilecontexts:
/dev/ttymxc[0-9]*u:object_r:tty_device:s0
www.it-ebooks.info
FieldtrialsAtthispoint,rebuildthesourcetree,wipethedatafilesystem,flash,andre-runCTS.Repeatthisuntilalldenialsareaddressed.
Onceyou’redonewithCTSandinternalQAtrials,werecommendperformingafieldtrialwiththedeviceinpermissivemode.Duringthisperiod,youshouldbegatheringthelogsandrefiningpolicy.Ifthedomainsarenotstable,youcandeclarethemaspermissiveinthepolicyfileandstillputthedeviceinenforcingmode;enforcingsomedomainsisbetterthanenforcingnone.
www.it-ebooks.info
GoingenforcingYoucanpasstheenforcingmodeeitherusingbootloader(whichwillnotbecoveredhere)orwiththeinit.rcscriptearlyinboottime.Youcandothisrightaftersetcon:
setconu:r:init:s0
setenforce1
Oncethisstatementiscompiledintotheinit.rcscript,itcanonlybeundonewithasubsequentbuildandareflashofboot.img.Youcancheckthisbyrunningthegetenforcecommand.Also,asaninterestingtest,youcantrytoruntherebootcommandfromtherootserialconsoleandwatchitfail:
root@udoo:/#getenforce
Enforcing
root@udoo:/#reboot
reboot:Operationnotpermitted
www.it-ebooks.info
SummaryInthischapter,allofyourpreviousunderstandingofthesystemwasusedtodeveloprealSEforAndroidpolicyforabrandnewdevice.YouarenowempoweredwiththeknowledgeofhowtowriteSELinuxpolicyforAndroid,whereandhowthecomponentsofthesystemwork,andhowtoportandenablethesefeaturesonvariousAndroidplatforms.Sincethisisafairlynewfeaturethatinfluencesmanysysteminteractions,issuesthatwillrequirecodechangesaswellaspolicychangeswillarise.Understandingbothiscrucial.
Aspolicyauthorsandsecuritypersonnelingeneral,theresponsibilitytosecurethesystemrestsonourshoulders.Inmostorganizations,you’rerequiredtoworkinthedark.However,ifyoucan,doasmuchworkandaskasmanyquestionsasyouwanttointhemailinglist,andneveracceptthestatusquo.TheSEforAndroidandAOSPprojectswelcomealltocontribute,andbycontributing,youwillhelpmaketheprojectbetterandenhancethefeaturesetsforall.
www.it-ebooks.info
AppendixA.TheDevelopmentEnvironmentInordertobuildtheAndroid4.3sourcesprovidedbyUDOO,youneedanUbuntuLinuxsystemwithOracleJava6.Whileitmaybepossibletouseavariantofthissetup,Google’sstandardtargetdevelopmentplatformforAndroid4.3isUbuntu12.04.Therefore,wewillusethissetuptoensurethehighestprobabilityofsuccessinourexplorationofLinux,SELinux,Android,theUDOO,andSEforAndroid.
Inthisappendix,wewilldothefollowing:
DownloadandinstallUbuntu12.04usingavirtualmachine(VM)EnhanceourVM’sperformancebyinstallingtheVirtualBoxExtensionPackandVirtualBoxGuestAdditionsSetupadevelopmentenvironmentappropriateforbuildingtheLinuxkernelandUDOOsourcesInstallOracleJava6
TipIfyoualreadyuseUbuntuLinux12.04,youcanskiptotheTheBuildEnvironmentsection.IfyouintendtoinstallUbuntunatively(notinaVM),youshouldskiptotheUbuntuLinux12.04sectionandfollowthosedirections,ignoringtheVirtualBoxsteps.
www.it-ebooks.info
VirtualBoxThereareanumberofvirtualizationproductsavailableforrunningguestoperatingsystems,suchasUbuntuLinux,butforthissetupwewilluseVirtualBox.VirtualBoxisawidelyusedopensourcevirtualizationsystemavailableforMac,Linux,Solaris,andWindowshosts(amongothers).Itsupportsavarietyofguestoperatingsystems.VirtualBoxalsoallowstheuseofhardwarevirtualizationofmanymodern/commonprocessorfamiliestoincreaseperformancebyprovidingeachvirtualmachineitsownprivateaddressspace.
TheVirtualBoxdocumentationhasexcellentinstallationinstructionsforvariousplatforms,andwerecommendreferringtotheseforyourhostplatform.YoucanfindinformationaboutinstallingandrunningVirtualBoxforyourhostoperatingsystemathttp://www.virtualbox.org/manual/ch02.html.
www.it-ebooks.info
UbuntuLinux12.04(precisepangolin)ToinstallUbuntuLinux12.04,youwillfirstneedtodownloadanappropriatedistributionimage.Thesecanbefoundathttp://releases.ubuntu.com/12.04/.Whilethereareanumberofacceptableimagesthere,wewillinstallthe64-bitdesktopversionofthedistribution—http://releases.ubuntu.com/12.04/ubuntu-12.04.5-desktop-amd64.iso.Thehostmachinewe’reusinginthisexampleisa64-bitMacbookProrunningOSX10.9.2,sowe’retargetinga64-bitguestaswell.Ifyouhavea32-bitmachine,thebasicmechanicsofwhatwecoverwillbethesame;onlyafewdetailswillbedifferent,sowewillleavethoseforyoutodiscoverandresolve.
LaunchVirtualBoxonyourhost,waitfortheVMManagerwindowtoappear,andperformthefollowingsteps:
1. ClickonNew.2. FortheNameandOperatingSystemsettings,makethefollowingselections:
Name:SEforAndroidBookType:LinuxVersion:Ubuntu(64bit)
3. SetMemorySizetoavaluetoatleast16GB.Anythinglowerthanthiswillleadtounsuccessfulbuilds.
4. Tosetuptheharddrive,selectCreateavirtualharddrivenow.Setthisvaluetoatleast80GB.
5. ChoosetheHardDriveFileType,VDI(VirtualBoxDiskImage).6. Ensurestorageonthephysicalharddriveissettodynamicallyallocated.7. Whenpromptedforfilelocationandsize,namethenewvirtualharddriveSEfor
AndroidBook,andsetitssizeto80GB.
EnsuretheSEforAndroidBookVMisselectedintheleftpane.ClickonthegreenStartarrowtoperformaninitiallaunchoftheVM.Adialogwillappear,askingyoutoselectavirtualopticaldiskfile.Clickonthesmallfoldericonandlocatetheubuntu-12.04.5-desktop-amd64.isoCDimageyoudownloadedearlier.ThenclickonStart.
WhenthescreenturnsblackandshowsakeyboardimageatthebottomcenteroftheVMwindow,pressanykeytobegintheUbuntuinstallation.Assoonasyoudothis,thelanguageselectionscreenwillappear.Choosewhicheverlanguageismostappropriateforyou,butforthisexample,we’llselectEnglish.ThenselectInstallUbuntu.
Sometimes,youmayseeanunusual-lookingerrorprintedacrossyourVMwindow—somethinglikeSMBusbaseaddressuninitialized.ThismessageisshownbecauseVirtualBoxdoesn’tsupportaparticularkernelmodulethatisloadedbydefaultwithUbuntu12.04.However,thiswillnotcauseanydifficultyandisonlyacosmeticannoyance.Afterafewmoments,aniceGUIinstallationscreenwillappear,waitingforyoutochoosealanguageagain.We’llchooseEnglishagain.
OnthefollowingPreparingtoinstallUbuntuscreen,threechecklistitemsareshown.
www.it-ebooks.info
Youshouldhavealreadysatisfiedthefirstitem,sinceyourvirtualdriveismuchlargerthantheminimumrequirementforUbuntu.Tosatisfytheothers,ensureyourhostsystemispluggedinwithapowersupplyandhasanestablishednetworkconnection.Althoughthisisentirelyunnecessaryforourpurposeshere,wealmostalwaysmarktheDownloadupdateswhileinstallingandInstallthisthird-partysoftwareboxesbeforecontinuing.
OntheInstallationtypescreen,we’lltaketheeasypathandselectErasediskandinstallUbuntu.KeepinmindthatthiswillonlyerasethediskofyourVM’svirtualharddriveandleavesyourhostsystemintact.OntheErasediskandinstallUbuntuscreen,yourvirtualharddriveshouldalreadybeselected,soyouonlyneedtoclickInstallNow.
FromthispointforwardintheUbuntuinstallation,twoseparatetaskswillhappensimultaneously:inabackgroundthread,theinstallerwillpreparethevirtualdrivefortheinstallationofthebasesystem;secondly,youwillconfiguresomebasicaspectsofyournewsystem.Butfirst,youwillhavetoidentifyyourtimezonebyclickingontheappropriatepointontheworldmapbeforecontinuing.Thenidentifyyourkeyboardlayoutandcontinue.
Setupyourfirstuseraccount.Inthiscase,itwillbetheaccountweusedtodotheworkinthisbook,sowewillenterthefollowinginformation:
YourName:BookUserYourcomputer’sname:SE-for-AndroidPickausername:bookuserPasswordfields:(whateveryouprefer)
WewillalsoselectLoginautomatically.Whilewewouldnotnormallydothisforsecurityreasons,wewilldoitinourlocalVMforconvenience;butyoumayprotectthisaccountinwhicheverwayyouprefer.
OncetheUbuntuinstallationiscomplete,adialogaskingyoutorestartthecomputerwillappear.ClicktheRestartnowbutton,andafterafewmoments,aterminalpromptwillinformyoutoremoveallinstallationmediaandpressEnter.ToremovethevirtualinstallationCD,gotoDevices|CD/DVDDevices|RemovediskfromvirtualdriveusingtheVirtualBoxmenubar.ThenpressEntertorestarttheVM,butinterruptthebootprocessbyclosingtheVMwindow.Itwillaskyouifyouwanttopoweroffthemachine.JustclickOK.
www.it-ebooks.info
VirtualBoxextensionpackandguestadditionsTogetthebestperformancefromyourguestUbuntuVMandaccesstothevirtualUSBdevicesnecessaryforworkingwiththeUDOO,youwillneedtoinstalltheVirtualBoxextensionpackandguestadditions.
www.it-ebooks.info
VirtualBoxextensionpackDownloadtheextensionpackfromtheVirtualBoxwebsite,athttp://www.virtualbox.org/wiki/Downloads.TherewillbeadownloadlinkthereintendedforAllsupportedplatforms.Oncethisfileisdownloaded,you’llneedtoinstallit.Thisprocessisdifferentforeachtypeofhostsystem,butitisverystraightforward.ForLinuxandMacOSXhosts,simplydouble-clickingonthedownloadedextensionpackfilewilldothetrick.ForWindowssystems,youwillneedtoruntheinstalleryou’vedownloaded.
www.it-ebooks.info
VirtualBoxguestadditionsOnceyou’vecompletedtheinstallationoftheextensionpack,bootyourUbuntuLinux12.04VMfromVirtualBoxbyselectingtheVMfromtheleftpaneandclickingonStartinthetoolbar.OnceyourUbuntudesktopisactive,you’llnoticeitdoesnotfitintoyourVMwindow.ResizetheVMwindowtomakeitlarger,andtheVMscreenwillremainthesamesize.This,amongotherperformanceissues,willberesolvedbyinstallingtheVirtualBoxguestadditions.YoumayalsoseeawindowopenonyourvirtualdesktopindicatinganewversionofUbuntuisavailable.Donotupgrade;justclosethatwindow.
UsingtheVirtualBoxmenubar,gotoDevices|InsertGuestAdditionsCDImage….Shortlyafterward,adialogwillappear,askingwhetheryouwanttorunthesoftwareonthenewmediayoujustinserted.ClicktheRunbutton.Youwillthenneedtoauthenticateyouruserbyenteringyouruser’spassword(whichyouenteredduringsetup).Oncetheuserisauthenticated,ascriptwillautomaticallybuildandupdateseveralkernelmodules.Oncethescriptcompletes,reboottheVMbyclickingonthegearinthetop-rightcornerofthescreen,selectingShutdown…,andclickingonRestartinthedialogthatfollows.
WhentheVMreboots,thefirstthingyoushouldnoticeisthattheVMscreennowfitsintotheVMwindow.Moreover,ifyouresizetheVMwindow,theVMscreenresizeswithit.Thisisthesimplestwaytodetermineyou’vesuccessfullyinstalledtheVirtualBoxguestadditions.
www.it-ebooks.info
SavetimewithsharedfoldersAnotherthingyoucandotoboostyouraggregateperformancewhiledevelopingimagesfortheUDOOistosetupsharedfoldersbetweenyourhostsystemandyourUbuntuLinuxguestsystem.Inthisway,onceyou’vebuiltanewSDcardimagefortheUDOO,youcanmaketheimagedirectlyavailabletothehostthroughthesharedfolder.Thehostcanthenexecutethelong-runningcommandstoflashtheSDcardwithoutaddingtimetotheprocessbyslowingdownaccesstoyourhost’scardreaderthroughthevirtualizationlayer.Inthecaseofthesystemwe’reusingtowritethisbook,thereisasavingsofaround10minutesperimageflashed.
Tosetupasharedfolder,youmustbeginwiththeVirtualBoxManageropenandyourUbuntuVMpoweredoff.ClicktheSettingstoolbaricon.ThenselecttheSharedFolderstaboftheSettingsdialogthatopens.ClicktheAddSharedFoldericontotheright.EnterFolderPathtoafolderonyourhostthatyouwanttoshare.Inourcase,wecreatedanewfoldercalledvbox_sharetosharewithourVMguest.VirtualBoxwillgenerateFolderName,butmakesureyouselectAuto-mountbeforeclickingOK.WhenyoubootyourUbuntuVMfromnowon,thesharedfolderwillbeaccessibleinyourguestVMas/media/sf_<folder_name>.However,ifyouattempttolistthefilesinthatdirectoryfromyourguest,youwilllikelybedenied.Togainfullaccesstothisfolder(asinread-and-writeaccess)forourbookuser,we’llneedtoaddthatUIDtothevboxsfgroup:
$sudousermod-a-Gvboxsfbookuser
LogoutandlogintoyourguestagainorrestarttheguestVMtocompletetheprocess.
www.it-ebooks.info
ThebuildenvironmentToprepareoursystemtobuildtheLinuxkernel,Android,andAndroidapplications,weneedtoinstallandsetupsomekeypiecesofsoftware.ClicktheUbuntudashboardiconatthetopofthelaunchbarontheleftofyourscreen.Inthesearchbarthatappears,typetermandpressEnter.Aterminalwindowwillopen.Thenexecutethefollowingcommands:
$sudoapt-getupdate
$sudoapt-getinstallapt-filegit-coregnupgflexbisongperfbuild-
essentialzipcurlzlib1g-devlibc6-devlib32ncurses5-devia32-libs
x11proto-core-devlibx11-devia32-libsdialogliblzo2-devlibxml2-utils
minicom
TypeyandpressEnterwhenaskedwhetheryouwanttocontinue.
www.it-ebooks.info
OracleJava6DownloadthemostrecentJava6SEDevelopmentKit(version6u45)fromtheOracleJavaarchivewebsite,athttp://www.oracle.com/technetwork/java/javase/archive-139210.html.You’llneedthejdk-6u45-linux-x64.binversiontosatisfyGoogle’stargetdevelopmentenvironment.Onceitisdownloaded,executethefollowingcommandstoinstalltheJava6JDK:
$chmoda+xjdk-6u45-linux-x64.bin
$sudomkdir-p/usr/lib/jvm
$sudomvjdk-6u45-linux-x64.bin/usr/lib/jvm/
$cd/usr/lib/jvm/
$sudo./jdk-6u45-linux-x64.bin
$sudoupdate-alternatives--install"/usr/bin/java""java"
"/usr/lib/jvm/jdk1.6.0_45/bin/java"1
$sudoupdate-alternatives--install"/usr/bin/jar""jar"
"/usr/lib/jvm/jdk1.6.0_45/bin/jar"1
$sudoupdate-alternatives--install"/usr/bin/javac""javac"
"/usr/lib/jvm/jdk1.6.0_45/bin/javac"1
$sudoupdate-alternatives--install"/usr/bin/javaws""javaws"
"/usr/lib/jvm/jdk1.6.0_45/bin/javaws"1
$sudoupdate-alternatives--install"/usr/bin/jar""jar"
"/usr/lib/jvm/jdk1.6.0_35/bin/jar"1
$sudoupdate-alternatives--install"/usr/bin/javadoc""javadoc"
"/usr/lib/jvm/jdk1.6.0_45/bin/javadoc"1
$sudoupdate-alternatives--install"/usr/bin/jarsigner""jarsigner"
"/usr/lib/jvm/jdk1.6.0_45/bin/jarsigner"1
$sudoupdate-alternatives--install"/usr/bin/javah""javah"
"/usr/lib/jvm/jdk1.6.0_45/bin/javah"1
$sudormjdk-6u45-linux-x64.bin
www.it-ebooks.info
SummaryInthisappendix,wediscussedGoogle’stargetdevelopmentenvironmentforAndroidandshowedhowtocreateacompatibleenvironment,potentiallyinavirtualmachine.Youshouldfeelfreetomodifyotherelementsofyoursystem,buthavingtheelementsofthisappendixinstalledwillprovideyouwiththeminimallyviableenvironmentnecessarytoperformallthestepsoutlinedinChapter4,InstallationontheUDOO,andbeyond.
www.it-ebooks.info
IndexA
absoluteauthorityabout/Thecaseformore
AccessVectorCache/AccessVectorCacheaccessvectors
about/Accessvectorsimpersonate/Binderandsecuritycall/Binderandsecurityset_context_mgr/Binderandsecuritytransfer/Binderandsecurity
ActivityManagerService(AMS)about/Binderandsecurity
AndroidDAC,usingfor/Android’suseofDACsecuritymodel/Android’ssecuritymodel
Android.mk,sepolicyexploring/Exploringsepolicy’sAndroid.mksepolicy,building/Buildingsepolicypolicybuild,controlling/Controllingthepolicybuildbuild_policy,defining/Diggingdeeperintobuild_policymac_permissions.xml,building/Buildingmac_permissions.xmlseapp_contexts,building/Buildingseapp_contextsfile_contexts,building/Buildingfile_contextsproperty_contexts,building/Buildingproperty_contextsNSAresearchfiles/CurrentNSAresearchfiles
AndroidDebugBridge(adb)about/UDOOserialandAndroidDebugBridge
AndroidInterfaceDescriptionLanguage(AIDL)/Binder’sarchitectureAndroidRunTime(ART)/Zygote–applicationspawnAndroidversions
URL/ThepropertyserviceAndroidvulnerabilities
about/GlancingatAndroidvulnerabilitiesSkypevulnerability/SkypevulnerabilityGingerBreak/GingerBreakCVE-2010-EASY/RageagainstthecageMotoChopper/MotoChopper
AOSPdevicesURL/Upgrades–patchesgalore
applabelinglimitations/Limitationsonapplabeling
www.it-ebooks.info
applications/Android’ssecuritymodelauditddaemon/Theauditddaemonauditdinternals/Auditdinternalsauditlogs/Auditlogsauditsystem
about/Theauditsystemauditddaemon/Theauditddaemonauditdinternals/Auditdinternals
www.it-ebooks.info
BBell-LaPadula(BLP)model
about/MultilevelsecurityBinder
about/Binderarchitecture/Binder’sarchitecturefeatures/Binder’sarchitectureandsecurity/Binderandsecurity
binderpatchURL/Upgrades–patchesgalore
booleansdirectory/Thebooleansdirectorybuildenvironment
about/Thebuildenvironmentbuild_policy
defining/Diggingdeeperintobuild_policy
www.it-ebooks.info
Ccache_thresholdfile/AccessVectorCachecapabilitiesmodel
about/Capabilitiesmodelchconcommand/Examplesandtoolsclassdirectory/TheclassdirectoryCompatibilityDefinitionDocument(CDD)/SettingupCTSCompatibilityTestSuite(CTS)/ContextsCompatibilityTestSuitecompliance(CTS)
about/ThebooleansdirectoryURL/Thebooleansdirectory
contextsabout/Contextsdomains,mapping/Contexts
controlproperties/ControlpropertiesCTS
URL/Relabelingprocessessettingup/SettingupCTSrunning/RunningCTS
CTSbinaryURL/SettingupCTS
CTSresultsgathering/GatheringtheresultsCTStestresults/CTStestresultsauditlogs/Auditlogs
CTStestresults/CTStestresultsCVE-2010-EASY/Rageagainstthecage
www.it-ebooks.info
D/datafilesystem
fixingup/Fixingup/dataDAC
used,forAndroid/Android’suseofDACdefinekeyword/Dynamicdomaintransitionsdevice
purging/Purgingthedevicedevicepolicy
authoring/Authoringdevicepolicyadbd/adbdbootanim/bootanimdebuggerd/debuggerddrmserver/drmserverdumpstate/dumpstateinstalld/installdkeystore/keystoremediaserver/mediaservernetd/netdrild/rildservicemanager/servicemanagersurfaceflinger/surfaceflingersystem_server/system_servertoolbox/toolboxuntrusted_app/untrusted_appvold/voldwatchdogd/watchdogdwpa/wpa
disablefileinterface/Thedisablefileinterfacedynamicdomaintransitions
about/Dynamicdomaintransitionsdynamictypetransitions/Dynamictypetransitionsdyntransition/ProcFS
www.it-ebooks.info
Eenforcefile/Theenforcenodeenforcing
about/Theenforcenodeenforcingmode
passing/Goingenforcingexistingproperties
relabeling/Relabelingexistingpropertiesexplicitcontexts
viaseclabel/Explicitcontextsviaseclabelextendedattributes
labelingwith/Labelingwithextendedattributes
www.it-ebooks.info
Ffieldtrials
about/Fieldtrialsfilesystem
locating/Locatingthefilesysteminterrogating/Interrogatingthefilesystemenforcefile/Theenforcenodedisablefileinterface/Thedisablefileinterfacepolicyfile/Thepolicyfilenullfile/Thenullfilemlsfile/Themlsfilestatusfile/ThestatusfileAccessVectorCache/AccessVectorCachebooleansdirectory/Thebooleansdirectoryclassdirectory/Theclassdirectoryinitial_contextsdirectory/Theinitial_contextsdirectorypolicy_capabilitiesdirectory/Thepolicy_capabilitiesdirectoryprocfs/ProcFS
filesystemslabeling/Labelingfilesystemsfs_use/fs_usefs_task_use/fs_task_usefs_use_trans/fs_use_transgenfscon/genfsconmountoptions/Mountoptionsextendedattributes/Labelingwithextendedattributesfile_contextsfile/Thefile_contextsfiledynamictypetransitions/Dynamictypetransitions
file_contextsbuilding/Buildingfile_contexts
file_contextsfile/Thefile_contextsfilefixup.py
URL/InterpretingSELinuxdeniallogsflashing
about/FlashingimageonanSDcardFLASK
about/Gettingbacktothebasicsfs_task_use/fs_task_usefs_use/fs_usefs_use_trans/fs_use_trans
www.it-ebooks.info
Ggenfscon/genfscongetenforcecommand,states
disabled/Fixingthepolicyversionpermissive/Fixingthepolicyversionenforcing/Fixingthepolicyversion
GingerBreak/GingerBreakgraphicalmenu
settings/Retrievingthesourcegroups
changing/Changingownersandgroups
www.it-ebooks.info
Iinitial_contextsdirectory/Theinitial_contextsdirectoryinitprocess
about/Init–thekingofdaemonsInterprocessCommunication(IPC)
about/Binder
www.it-ebooks.info
Kkernel
SELinux,enablingin/It’salivekernel-common
URL/Upgrades–patchesgalorekernel-commonproject
URL/Upgrades–patchesgalorekeys.conf/keys.conf
www.it-ebooks.info
Llabeling
viaproperty_contexts/Labelingviaproperty_contextslabels
about/Labelsusers/Usersroles/Rolestypes/Types
LinuxSecurityModule(LSM)about/Binderandsecurity
www.it-ebooks.info
Mmac_permissions.xml
building/Buildingmac_permissions.xmlmac_permissions.xmlfile
about/Themac_permissions.xmlfilemlsfile/ThemlsfileMotoChopper/MotoChoppermountoptions/Mountoptionsmulti-levelsecurity(MLS)/Themlsfilemultilevelsecurity(MLS)model
about/Multilevelsecurity
www.it-ebooks.info
NNationalSecurityAgency(NSA)
about/BinderandsecurityNSArepositories
URL/Upgrades–patchesgaloreNSAresearchfiles/CurrentNSAresearchfilesnullfile/Thenullfile
www.it-ebooks.info
OOracleJava6
about/OracleJava6OracleJavaarchive
URL/OracleJava6owners
changing/Changingownersandgroups
www.it-ebooks.info
Ppatches
about/Upgrades–patchesgalorepermissionbits
changing/Changingpermissionbitspermissions,onproperties
about/Permissionsonpropertiespermissive
about/Theenforcenodepersistentproperties/Persistentpropertiespetanalogy
URL/Puttingittogetherabout/Puttingittogether
policybuildcontrolling/Controllingthepolicybuild
policyfile/Thepolicyfilepolicyload
about/Policyloadpolicypass
about/Secondpolicypassinit/initshell/shellinit_shell.te/init_shell.te
policyversionfixing/Fixingthepolicyversion
policy_capabilitiesdirectory/Thepolicy_capabilitiesdirectoryprocesses
relabeling/RelabelingprocessesProcessID(PID)/Binder’sarchitecture,Init–thekingofdaemonsprocfs/ProcFSprojects
building/Buildingsubcomponents–targetsandprojectsproperties
creating/Creatingandlabelingnewpropertieslabeling/Creatingandlabelingnewproperties
propertyserviceabout/Thepropertyservice
property_contextslabelingvia/Labelingviaproperty_contextsbuilding/Buildingproperty_contexts
www.it-ebooks.info
RRadioInterfaceLayerDaemon(RILD)/Android’ssecuritymodel,Init–thekingofdaemonsREADME
testkey/Thecasetosecurethezygoteplatform/Thecasetosecurethezygoteshared/Thecasetosecurethezygotemedia/Thecasetosecurethezygote
role-basedaccesscontrols(RBAC)about/Roles
roles,labels/Roles
www.it-ebooks.info
Sseapp_contexts/seapp_contexts
building/Buildingseapp_contextssecurity
andBinder/Binderandsecuritysecurityid(sid)/Labelingfilesystemssecurityidentifier(sid)/Theinitial_contextsdirectorysecuritymodel
systemcomponentservices/Android’ssecuritymodelapplications/Android’ssecuritymodel
SELinuxabout/Gettingbacktothebasicsimplementing/Multilevelsecuritybenefits/Puttingittogetherbestpractices/Complexitiesandbestpracticescomplexities/Complexitiesandbestpracticesenabling,inkernel/It’salive
SELinuxdeniallogsinterpreting/InterpretingSELinuxdeniallogs
SELinuxFSabout/Policyload
SELinuxproperties/SELinuxpropertiessepolicy
building/Buildingsepolicysepolicy-analyzetool/sepolicy-analyzesepolicy-checktool/sepolicy-checkSEPolicymaster
updating/UpdatingtoSEPolicymastersetsockcreatecon()function/Init–thekingofdaemonssharedfolders
about/SavetimewithsharedfoldersSkypevulnerability/Skypevulnerabilitysource
retrieving/Retrievingthesourcespecialproperties
about/Specialpropertiescontrolproperties/Controlpropertiespersistentproperties/PersistentpropertiesSELinuxproperties/SELinuxproperties
standalonetoolsabout/Standalonetoolssepolicy-check/sepolicy-checksepolicy-analyze/sepolicy-analyze
www.it-ebooks.info
statusfile/Thestatusfilesubject
about/Gettingbacktothebasicsswitch
flipping/Flippingtheswitchsystemapps
about/Thecasetosecurethezygotesystemcomponentservices/Android’ssecuritymodelsystemserver
about/Android’ssecuritymodel
www.it-ebooks.info
Ttarget
about/Gettingbacktothebasicstargets
building/Buildingsubcomponents–targetsandprojectstools,filesystems
about/Examplesandtools/datafilesystem,fixingup/Fixingup/datasecurity/Asidenoteonsecurity
typeenforcement(TE)about/Types,Dynamicdomaintransitions
typefieldvalue,filesystemobjectabout/Thefile_contextsfile—/Thefile_contextsfile-d/Thefile_contextsfile-b/Thefile_contextsfile-s/Thefile_contextsfile-c/Thefile_contextsfile-l/Thefile_contextsfile-p/Thefile_contextsfile
types,labels/Types
www.it-ebooks.info
UUbuntuLinux12.04
about/UbuntuLinux12.04(precisepangolin)URL/UbuntuLinux12.04(precisepangolin)
UDOOdocumentationURL/Retrievingthesource
UDOOserialabout/UDOOserialandAndroidDebugBridge
user-basedaccesscontrols(UBAC)about/Users
users,labels/Usersuserspaceobjectmanager/Thestatusfile
www.it-ebooks.info
Vvariables
BOARD_SEPOLICY_DIRS/ControllingthepolicybuildBOARD_SEPOLICY_UNION/ControllingthepolicybuildBOARD_SEPOLICY_REPLACE/ControllingthepolicybuildBOARD_SEPOLICY_IGNORE/Controllingthepolicybuild
VirtualBoxabout/VirtualBoxURL/VirtualBoxextensionpack/VirtualBoxextensionpackguestadditions/VirtualBoxguestadditions
virtualmachine(VM)/Zygote–applicationspawn
www.it-ebooks.info
ZZygote
about/Zygote–applicationspawnzygote
securing/Thecasetosecurethezygotefortifying/Fortifyingthezygotesocket,plumbing/Plumbingthezygotesocketmac_permissions.xmlfile/Themac_permissions.xmlfilekeys.conf/keys.confseapp_contexts/seapp_contexts
zygotesocketplumbing/Plumbingthezygotesocket
www.it-ebooks.info