Exploring SE for Android

Transcription

Exploring SE for Android
www.it-ebooks.info
www.it-ebooks.info
ExploringSEforAndroid
www.it-ebooks.info
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
Summary
Index
www.it-ebooks.info
www.it-ebooks.info
ExploringSEforAndroid
www.it-ebooks.info
www.it-ebooks.info
ExploringSEforAndroid
Copyright©2015PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,
ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthe
publisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyofthe
informationpresented.However,theinformationcontainedinthisbookissoldwithout
warranty,eitherexpressorimplied.Neithertheauthors,norPacktPublishing,andits
dealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecaused
directlyorindirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthe
companiesandproductsmentionedinthisbookbytheappropriateuseofcapitals.
However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.
Firstpublished:February2015
Productionreference:1190215
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
BirminghamB32PB,UK.
ISBN978-1-78439-059-4
www.packtpub.com
www.it-ebooks.info
www.it-ebooks.info
Credits
Authors
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
www.it-ebooks.info
Foreword
ThefirsttalkofSELinuxonAndroidstartedalmostassoonasAndroidwasannounced.
Theinterestatthattimewasmainlyshownbyacademiccirclesanddevelopersof
SELinuxitself.AsalongtimeuserofSELinuxinserverdeployments,Iknewitsbenefits
fromasecuritypointofviewandalsoknewhowmuchAndroidcouldbenefitfromthem.
Atthattime,ImayhavebeencoyaboutthereasonsIwantedtocommitsomeoftheinitial
patchestotheSELinuxproject.LookingbackatthecodereviewsforthoseAndroidOpen
SourceProject(AOSP)changes,Inowrememberhowmuchresistancetherewasinthe
beginning.Spaceondeviceswasatapremium,anditwasconsideredavictoryifwe
couldsaveafewkilobytes.AndhereweretheSELinuxlibrariesandpoliciesthat
increasedthesystemsizebythirtykilobytes!Theperformanceimpacthadnotevenbeen
measuredatthattime.
TheworkcontinuedunabatedwithSELinuxcontributors,suchasStephenSmalley,
RobertCraig,JoshuaBrindle,andanauthorofthisbook,WilliamRoberts,aswellaswith
thehelpofmycoworkersGeremyCondraandNickKralevichatGoogle.Slowly,through
theherculeaneffortsofeveryoneinvolved,theprojectmaterializedandbecamemoreand
morecomplete.SinceAndroid4.4KitKat,SELinuxisshippedinenforcingmode,andall
Androiduserscanbenefitfromtheaddedprotectionthatitaffords.
Thetaledoesn’tendthere!Now,it’syourturntolearn.Thisbookisthefirstreference
availableforthespecificflavorofSELinuxfoundinAndroid.It’smysincerehopethat
thisbookimpartstheknowledgeyouneedtounderstandandcontributetoitscontinued
development.WilliamRobertshasbeensubmittingcodetoAOSPsincethebeginningof
SELinuxforAndroid,andhisandDr.Confer’sknowledgeiscontainedinthesepages.It’s
uptoyoutoreaditandhelpwritethenextchapterofthissaga.
KennyRoot
MountainView,CA
www.it-ebooks.info
www.it-ebooks.info
AbouttheAuthors
WilliamConferhasbeenengineeringembeddedandmobilesystemssince1997.Hehas
workedforSamsungMobileasamanagingstaffengineerandcurrentlyteachescomputer
scienceatSUNYPolytechnicInstitute.Heholdsapatentinlow-costcharacterrecognition
forextremelyresource-limiteddevicesandhasmultipleotherpatentspendingformobile
technologies.
Mywife,Ása,sacrificedendlesslytohelpgivemethespaceandtimeneededforthis
work,andIowehermorethanIcansay.MythreedaughtersalsoensuredIcouldn’t
alwaysbeworkingonthisbookanddistractedmeinthebestpossibleways.Icouldn’trest
ifIdidn’tthankallmyfall2014studentsfromSUNYPolytechnicInstitutewhoputup
withmewhenIwassidetrackedbythisbook.Finally,andmostimportantly,mygreatest
thanksgoestomycoauthor(andfriend,student,andteacher),WilliamRoberts,without
whomIwouldhavetohavefoundanother.
WilliamRobertsisasoftwareengineerwhoisfocusedonOS-levelsecurityandplatform
enhancements.HeisoneoftheengineerswhofoundedtheSamsungKNOXproductand
anearlyadopterofSEforAndroid.Hehasmadecontributionstoseveralopensource
projects,suchasSEforAndroid,theAndroidOpenSourceProject,theLinuxKernel,
CyanogenMod,andOpenSC.HisrecentinterestshavetakenhimtoSmartCard
technologiesandthevirtualizationofsmartcards.Inhissparetime,heworkswithDr.
ConferontheMiniatproject(http://www.miniat.org),avirtual,embeddedarchitecture
simulator.
IwouldliketothankDr.WilliamConfer,thecoauthor,forhelpingmewritethisbook;his
contributionswereinvaluable.Also,Iwouldliketothankmywifeforsupportingmeand
givingmethetimetodothis,eventhoughwewererenovatingthehouse.Also,Iwould
liketothankmyfamilyandfriendsfortheirencouragementalongtheway.
www.it-ebooks.info
www.it-ebooks.info
AbouttheReviewers
JoshuaBrindleistheCTOandcofounderofQuarkSecurityInc.,acompanyfocusedon
solvingmobileandcross-domainsecurityproblems.Joshuahas12yearsofprofessional
experienceintheareaofdevelopmentforgovernment,academic,andopensource
softwarethatfocusesonsecurityinLinux.Joshuahascontributedtonumerousopen
sourceprojects,bothasaprojectmaintainerandasadeveloper.Hisworkcanbefoundon
allSELinuxsystemsandnearlyallLinuxsystems.Joshua’srecentexperiencefocuseson
buildingsecuremobiledevicesusingtechnologiessuchasSecurityEnhancementsfor
Android,mobiledevice,andapplicationmanagement.
HiromuYakuraisastudentatNadaHighSchool,Japan.Heistheyoungestpersonto
holdthenationalinformationsecurityqualificationfromJapan.Hehasgivenlectures
aboutSEforAndroidatmanyconferences.Heisalsofamiliarwiththesecurity
competition,CapturetheFlag(CTF),andhasparticipatedinDEFCONCTF2014asa
teambinja.
Iwouldliketoexpressmygratitudetomyfamilyfortheirunderstandingandsupport.
www.it-ebooks.info
www.it-ebooks.info
www.PacktPub.com
www.it-ebooks.info
Supportfiles,eBooks,discountoffers,and
more
Forsupportfilesanddownloadsrelatedtoyourbook,pleasevisitwww.PacktPub.com.
DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFand
ePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandas
aprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwith
usat<service@packtpub.com>formoredetails.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signup
forarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooks
andeBooks.
https://www2.packtpub.com/books/subscription/packtlib
DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt’sonlinedigital
booklibrary.Here,youcansearch,access,andreadPackt’sentirelibraryofbooks.
www.it-ebooks.info
Whysubscribe?
FullysearchableacrosseverybookpublishedbyPackt
Copyandpaste,print,andbookmarkcontent
Ondemandandaccessibleviaawebbrowser
www.it-ebooks.info
FreeaccessforPacktaccountholders
IfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccess
PacktLibtodayandview9entirelyfreebooks.Simplyuseyourlogincredentialsfor
immediateaccess.
www.it-ebooks.info
www.it-ebooks.info
Preface
ThisbookintroducestheSecurityEnhancements(SE)forAndroidopensourceproject
andwalksyouthroughtheprocessofsecuringnewembeddedsystemswithSEfor
Android.Toourknowledge,thisbookisthefirstsourcetodocumentsuchaprocessinits
entiretysothatstudents,DIYhobbyists,andengineerscancreatecustomsystemssecured
bySEforAndroid.Generally,onlyoriginalequipmentmanufacturers(OEMs)dothis,and
quitecommonly,thetargetdeviceisaphoneortablet.Wetrulyhopeourbookwillchange
that,engagingawideaudienceindevelopmentsotheycanuseandunderstandthese
modernsecuritytools.
Weworkedveryhardtoensurethistextisnotjustastep-by-steptechnologybook.
Specifically,we’vechosenamodelthatdirectsyoutofailyourwaytosuccess.Youwill
firstgainappropriatetheoreticalunderstandingofhowsecurityisgainedandenforced.
Thenwewillintroduceasystemthathasneverbeensecuredthatway(notevenbyus,
priortowritingthisbook).Next,we’llguideyouthroughallourintelligentguesswork,
embracingunexpectedfailuresforthenewlyfoundidiosyncrasiestheyexpose,and
eventuallyenforcingourcustomsecuritypolicies.Itrequiresyoutolearntoresolve
differencesbetweenmajoropensourceprojectssuchasSELinux,SEforAndroid,and
GoogleAndroid,eachofwhichhasindependentgoalsanddeploymentschedules.This
preparesyoutosecureotherdevices,theprocessforwhichisalwaysdifferent,but
hopefully,willnowbemoreaccessible.
www.it-ebooks.info
Whatthisbookcovers
Chapter1,LinuxAccessControls,discussesthebasicsofDiscretionaryAccessControl
(DAC),howsomeAndroidexploitsleverageDACproblems,anddemonstratetheneed
formorerobustsolutions.
Chapter2,MandatoryAccessControlsandSELinux,examinesMandatoryAccessControl
(MAC)anditsmanifestationinSELinux.Thischapteralsoexplorestangiblepolicyto
controlSELinuxobjectinteraction.
Chapter3,AndroidIsWeird,introducestheAndroidsecuritymodelandinvestigates
binder,zygote,andthepropertyservice.
Chapter4,InstallationontheUDOO,walksthroughbuildinganddeployingAndroid
fromsourcetotheUDOO-embeddedboardandturnsonSELinuxsupport.
Chapter5,BootingtheSystem,followsthebootprocessfromthepolicyloading
perspectiveandcorrectsissuestogetSELinuxtoausablestateontheUDOO.
Chapter6,ExploringSELinuxFS,examinestheSELinuxFSfilesystemandhowitprovides
thekernel-to-userspaceinterfaceforhigher-levelidioms.
Chapter7,UtilizingAuditLogs,investigatestheauditsubsystem,revealinghowto
interpretSELinuxauditlogsforthebenefitofpolicywriting.
Chapter8,ApplyingContextstoFiles,teachesyouhowfilesystemsandfilesystemobjects
gettheirlabelsandcontexts,demonstratingtechniquestochangethem,includingdynamic
typetransitions.
Chapter9,AddingServicestoDomains,emphasizesprocesslabeling,notablytheAndroid
servicesrunandmanagedbyinit.
Chapter10,PlacingApplicationsinDomains,showsyouhowtoproperlylabeltheprivate
datadirectoriesofapplications,aswellasapplicationruntimecontextsviaconfiguration
filesandSELinuxpolicy.
Chapter11,LabelingProperties,demonstrateshowtocreateandlabelnewandexisting
properties,andsomeoftheanomaliesthatoccurwhendoingso.
Chapter12,MasteringtheToolChain,covershowthevariouscomponentsthatcontrol
policyonthedeviceareactuallybuiltandcreated.ThischapterreviewstheAndroid.mk
components,detailinghowtheheartofthebuildandconfigurationmanagementworks.
Chapter13,GettingtoEnforcingMode,utilizesalltheskillsyoulearnedintheearlier
chapterstorespondtoauditlogsfromCTSandgettheUDOOinenforcingmode.
Appendix,TheDevelopmentEnvironment,walksyouthroughthenecessarystepsof
settingupaLinuxenvironmentsuitableforyoutofollowalltheactivitiesinthisbook.
www.it-ebooks.info
www.it-ebooks.info
Whatyouneedforthisbook
Hardwarerequirementsinclude:
AUDOO-embeddeddevelopmentboard
An8GBMiniSDcard(whileyoucanuseacardwithgreatercapacity,wedonot
recommendedit)
Aminimumof16GBofRAM
Atleast80GBoffreeharddrivespace
Softwarerequirementsinclude:
AnUbuntu12.04LTSdesktopsystem
OracleJDK6.0version6u45
SomeadditionalmiscellaneousLinuxsoftwareisrequired,butthesearedescribedin
thebookandareavailableforfree.
www.it-ebooks.info
www.it-ebooks.info
Whothisbookisfor
Thisbookisintendedfordevelopersandengineerswhoaresomewhatfamiliarwith
operatingsystemconceptsasimplementedbyLinux.Theycouldbehobbyistswantingto
securetheirAndroid-poweredcreations,OEMengineersbuildinghandsets,orengineers
fromemergingareaswhereAndroidisseeinggrowth.AbasicbackgroundinC
programmingwillbehelpful.
www.it-ebooks.info
www.it-ebooks.info
Conventions
Inthisbook,youwillfindanumberoftextstylesthatdistinguishbetweendifferentkinds
ofinformation.Herearesomeexamplesofthesestylesandexplanationsoftheir
meanings.
Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,
pathnames,dummyURLs,userinput,andTwitterhandlesareshownasfollows:“Now
let’sattempttoexecutethehello.txtfileandseewhathappens.”
Ablockofcodeissetasfollows:
caseINTERFACE_TRANSACTION:
{
reply.writeString(DESCRIPTOR);
returntrue;
}
Anycommand-lineinputoroutputiswrittenasfollows:
$sutestuser
Password:
testuser@ubuntu:/home/bookuser$
Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen,
forexample,inmenusordialogboxes,appearinthetextlikethis:“Exittheconfiguration
menusbyselectingExituntilyouareaskedtosaveyournewconfiguration.”
Note
Warningsorimportantnotesappearinaboxlikethis.
Tip
Tipsandtricksappearlikethis.
www.it-ebooks.info
www.it-ebooks.info
Readerfeedback
Feedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthis
book—whatyoulikedordisliked.Readerfeedbackisimportantforusasithelpsus
developtitlesthatyouwillreallygetthemostoutof.
Tosendusgeneralfeedback,simplye-mail<feedback@packtpub.com>,andmentionthe
book’stitleinthesubjectofyourmessage.
Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingor
contributingtoabook,seeourauthorguideatwww.packtpub.com/authors.
www.it-ebooks.info
www.it-ebooks.info
Customersupport
NowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelp
youtogetthemostfromyourpurchase.
www.it-ebooks.info
Downloadingtheexamplecode
Youcandownloadtheexamplecodefilesfromyouraccountathttp://www.packtpub.com
forallthePacktPublishingbooksyouhavepurchased.Ifyoupurchasedthisbook
elsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilesemaileddirectlytoyou.
www.it-ebooks.info
Errata
Althoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdo
happen.Ifyoufindamistakeinoneofourbooks—maybeamistakeinthetextorthe
code—wewouldbegratefulifyoucouldreportthistous.Bydoingso,youcansaveother
readersfromfrustrationandhelpusimprovesubsequentversionsofthisbook.Ifyoufind
anyerrata,pleasereportthembyvisitinghttp://www.packtpub.com/submit-errata,
selectingyourbook,clickingontheErrataSubmissionFormlink,andenteringthe
detailsofyourerrata.Onceyourerrataareverified,yoursubmissionwillbeacceptedand
theerratawillbeuploadedtoourwebsiteoraddedtoanylistofexistingerrataunderthe
Erratasectionofthattitle.
Toviewthepreviouslysubmittederrata,goto
https://www.packtpub.com/books/content/supportandenterthenameofthebookinthe
searchfield.TherequiredinformationwillappearundertheErratasection.
www.it-ebooks.info
Piracy
PiracyofcopyrightedmaterialontheInternetisanongoingproblemacrossallmedia.At
Packt,wetaketheprotectionofourcopyrightandlicensesveryseriously.Ifyoucome
acrossanyillegalcopiesofourworksinanyformontheInternet,pleaseprovideuswith
thelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.
Pleasecontactusat<copyright@packtpub.com>withalinktothesuspectedpirated
material.
Weappreciateyourhelpinprotectingourauthorsandourabilitytobringyouvaluable
content.
www.it-ebooks.info
Questions
Ifyouhaveaproblemwithanyaspectofthisbook,youcancontactusat
<questions@packtpub.com>,andwewilldoourbesttoaddresstheproblem.
www.it-ebooks.info
www.it-ebooks.info
Chapter1.LinuxAccessControls
Androidisanoperatingsystemcomposedoftwodistinctcomponents.Thefirst
componentisaforkedmainlineLinuxkernelandsharesalmosteverythingincommon
withLinux.Thesecondcomponent,whichwillbediscussedlater,istheuserspace
portion,whichisverycustomandAndroidspecific.SincetheLinuxkernelunderpinsthis
systemandisresponsibleforthemajorityofaccesscontroldecisions,itisthelogical
placetobeginadetailedlookatAndroid.
Inthischapterwewill:
ExaminethebasicsofDiscretionaryAccessControl
IntroduceLinuxpermissionsflagsandcapabilities
Tracesyscallsaswevalidateaccesspolicies
Makethecaseformorerobustaccesscontroltechnology
DiscussAndroidexploitsthatleverageproblemswithDiscretionaryAccessControl
Linux’sdefaultandfamiliaraccesscontrolmechanismiscalledDiscretionaryAccess
Control(DAC).Thisisjustatermthatmeanspermissionsregardingaccesstoanobject
areatthediscretionofitscreator/owner.
InLinux,whenaprocessinvokesmostsystemcalls,apermissioncheckisperformed.As
anexample,aprocesswishingtoopenafilewouldinvoketheopen()syscall.Whenthis
syscallisinvoked,acontextswitchisperformed,andtheoperatingsystemcodeis
executed.TheOShastheabilitytodeterminewhetherafiledescriptorshouldbereturned
totherequestingprocessornot.Duringthisdecision-makingprocess,theOSchecksthe
accesspermissionsofboththerequestingprocessandthetargetfileitwishestoobtainthe
filedescriptorto.EitherthefiledescriptororEPERMisreturned,dependentonwhether
thepermissioncheckspassorfailrespectively.
Linuxmaintainsdatastructuresinthekernelformanagingthesepermissionfields,which
areaccessiblefromuserspace,andonesthatshouldbefamiliartoLinuxand*NIXusers
alike.Thefirstsetofaccesscontrolmetadatabelongstotheprocess,andformsaportion
ofitscredentialset.Thecommoncredentialsareuserandgroup.Ingeneral,weusethe
termgrouptomeanbothprimarygroupandpossiblesecondarygroup(s).Youcanview
thesepermissionsbyrunningthepscommand:
$ps-eopid,comm,user,group,supgrp
PIDCOMMANDUSERGROUPSUPGRP
1initrootroot...
2993system-service-rootrootroot
3276chromium-browsebookusersudofusebookuser
...
Asyoucansee,wehaveprocessesrunningastheusersrootandbookuser.Youcanalso
seethattheirprimarygroupisonlyonepartoftheequation.Processesalsohavea
secondarysetofgroupscalledsupplementarygroups.Thissetmightbeempty,indicated
bythedashintheSUPGRPfield.
www.it-ebooks.info
Thefilewewishtoopen,referredtoasthetargetobject,target,orobjectalsomaintainsa
setofpermissions.TheobjectmaintainsUSERandGROUP,aswellasasetofpermission
bits.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.txthasaUSERof
bookuserandGROUPasbookuser.Wecanalsoseethepermissionbitsorflagsonthelefthandsideoftheoutput.Therearesevenfieldstoconsideraswell.Eachemptyfieldis
denotedwithadash.Whenprintedwithls,thefirstfieldscangetconvolutedby
semantics.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.Itcontainsalltheimportantinformationfor
theaccesscontrols.Thesecondlineisjustatimestamplettingusknowwhenthefilewas
lastaccessed.Aswecansee,USERorUIDoftheobjectisbookuser,andGROUPis
bookuseraswell.Thepermissionflags,(0664/-rw-rw-r--),identifythetwowaysthat
permissionflagsarerepresented.Thefirst,theoctalform0664,condenseseachthree-flag
fieldintooneofthethreebase-8(octal)digits.Thesecondisthefriendlyform,-rw-rw-r-,equivalenttotheoctalformbuteasiertointerpretvisually.Ineithercase,wecanseethe
leftmostfieldis0,andtherestofourdiscussionswillignoreit.Thatfieldisforsetuid
andsetgidcapabilities,whichisnotimportantforthisdiscussion.Ifweconvertthe
remainingoctaldigits,664,tobinary,weget110110100.Thisbinaryrepresentation
directlyrelatestothefriendlyform.Eachtriplemapstoread,write,andexecute
permissions.OftenyouwillseethispermissiontriplerepresentedasRWX.Thefirsttriple
arethepermissionsgiventoUSER,thesecondarethepermissionsgiventoGROUP,andthe
thirdiswhatisgiventoOTHERS.TranslatingtoconventionalEnglishwouldyield,“The
user,bookuser,haspermissiontoreadfromandwritetohello.txt.Thegroup,
bookuser,haspermissiontoreadfromandwritetohello.txt,andeveryoneelsehas
permissiononlytoreadfromhello.txt.”Let’stestthiswithsomereal-worldexamples.
www.it-ebooks.info
Changingpermissionbits
Let’stesttheaccesscontrolsintheexamplerunningprocessesasuserbookuser.Most
processesruninthecontextoftheuserthatinvokedthem(excludingsetuidandgetuid
programs),soanycommandweinvokeshouldinheritouruser’spermissions.Wecan
viewitbyissuing:
$groupsbookuser
bookuser:bookusersudofuse
Myuser,bookuser,isUSERbookuser,GROUPbookuserandSUPGRPsudoandfuse.
Totestforreadaccess,wecanusethecatcommand,whichopensthefileandprintsits
contenttostdout:
$cathello.txt
Hello,"ExploringSEforAndroid"
Hereisasimpletextfilefor
yourenjoyment.
...
Wecanintrospectthesyscallsexecutedbyrunningthestracecommandandviewingthe
output:
$stracecathello.txt
...
open("hello.txt",O_RDONLY)=3
...
read(3,"Hello,\"ExploringSEforAndroid\"\n"...,32768)=365
...
Theoutputcanbequiteverbose,soIamonlyshowingtherelevantparts.Wecanseethat
catinvokedtheopensyscallandobtainedthefiledescriptor3.Wecanusethatdescriptor
tofindotheraccessesviaothersyscalls.Laterwewillseeareadoccurringonfile
descriptor3,whichreturns365,thenumberofbytesread.Ifwedidn’thavepermissionto
readfromhello.txt,theopenwouldfail,andwewouldneverhaveavalidfiledescriptor
forthefile.Wewouldadditionallyseethefailureinthestraceoutput.
Nowthatreadpermissionisverified,let’strywrite.Onesimplewaytodothisistowritea
simpleprogramthatwritessomethingtotheexistingfile.Inthiscase,wewillwritethe
linemynewtext\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,thenumberofbyteswrittento
hello.txt.Noerrorswerereported,sothepermissionsseeminchecksofar.
Nowlet’sattempttoexecutehello.txtandseewhathappens.Weareexpectingtoseean
error.Let’sexecuteitlikeanormalcommand:
$./hello.txt
bash:./hello.txt:Permissiondenied
Thisisexactlywhatweexpected,butlet’sinvokeitwithstracetogainadeeper
understandingofwhatfailed:
$strace./hello.txt
...
execve("./hello.txt",["./hello.txt"],[/*39vars*/])=-1EACCES
(Permissiondenied)
...
Theexecvesystemcall,whichlaunchesprocesses,failedwithEACCESS.Thisisjustthe
sortofthingonewouldhopeforwhennoexecutepermissionisgiven.TheLinuxaccess
controlsworkedasexpected!
Let’stesttheaccesscontrolsinthecontextofanotheruser.First,we’llcreateanewuser
calledtestuserusingtheaddusercommand:
$sudoaddusertestuser
[sudo]passwordforbookuser:
Addinguser`testuser'...
Addingnewgroup`testuser'(1001)...
Addingnewuser`testuser'(1001)withgroup`testuser'...
Creatinghomedirectory`/home/testuser'...
...
VerifytheUSER,GROUP,andSUPGRPoftestuser:
$groupstestuser
testuser:testuser
SincetheUSERandGROUPdonotmatchanyofthepermissionsona.S,allaccesseswillbe
subjecttotheOTHERSpermissionschecks,whichifyourecall,isreadonly(0664).
Startbytemporarilyworkingastestuser:
$sutestuser
Password:
testuser@ubuntu:/home/bookuser$
Asyoucansee,wearestillinbookuser’shomedirectory,butthecurrentuserhasbeen
changedtotestuser.
Wewillstartbytestingreadwiththecatcommand:
$stracecathello.txt
...
www.it-ebooks.info
open("hello.txt",O_RDONLY)=3
...
read(3,"mynewtext\n",32768)=12
...
Similartotheearlierexample,testusercanreadthedatajustfine,asexpected.
Nowlet’smoveontowrite.Theexpectationisthatthiswillfailwithoutappropriate
access:
$strace./mywritehello.txt
...
open("hello.txt",O_WRONLY)=-1EACCES(Permission
denied)
...
Asexpected,thesyscalloperationfailed.Whenweattempttoexecutehello.txtas
testuser,thisshouldfailaswell:
$strace./hello.txt
...
execve("./hello.txt",["./hello.txt"],[/*40vars*/])=-1EACCES
(Permissiondenied)
...
Nowweneedtotestthegroupaccesspermissions.Wecandothisbyaddinga
supplementarygrouptotestuser.Todothis,weneedtoexittobookuser,whohas
permissionstoexecutethesudocommand:
$exit
exit
$sudousermod-Gbookusertestuser
Nowlet’scheckthegroupsoftestuser:
$groupstestuser
testuser:testuserbookuser
Asaresultoftheprevioususermodcommandtestusernowbelongstotwogroups:
testuserandbookuser.Thatmeanswhentestuseraccessesafileorotherobject(such
asasocket)withthegroupbookuser,theGROUPpermissions,ratherthanOTHERS,will
applytoit.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.Theonlydifferenceisthatitcannowreadthe
filethroughtheaccesspermissionsofOTHERSandGROUP.
Testwritebyexecutingthefollowingcommand:
$strace./mywritehello.txt
...
open("hello.txt",O_WRONLY)=3
write(3,"mynewtext\n",12)=12
...
Thistime,testuserwasabletowritethefileaswell,insteadoffailingwiththeEACCESS
permissionerrorshownbefore.
Attemptingtoexecutethefileshouldstillfail:
$strace./hello.txt
execve("./hello.txt",["./hello.txt"],[/*40vars*/])=-1EACCES
(Permissiondenied)
...
TheseconceptsarethefoundationofLinuxaccesscontrolpermissionbits,usersand
groups.
www.it-ebooks.info
www.it-ebooks.info
Changingownersandgroups
Usinghello.txtforexploratoryworkintheprevioussections,wehaveshownhowthe
ownerofanobjectcanallowvariousformsofaccessbymanagingthepermissionbitsof
theobject.Changingthepermissionsisaccomplishedusingthechmodsyscall.Changing
theuserand/orgroupisdonewiththechownsyscall.Inthissection,wewillinvestigate
thedetailsoftheseoperationsinaction.
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,thefilepermissionsarenowsettoonlyallowreadandwriteaccessfor
bookuser.Athoroughreadercouldexecutethecommandsfromearliersectionsinthis
chaptertoverifythatpermissionsworkasexpected.
Changingthegroupcanbedoneinasimilarfashionwithchown.Let’schangethegroupto
testuser:
$chownbookuser:testuserhello.txt
chown:changingownershipof`hello.txt':Operationnotpermitted
Thisdidnotworkasweintended,butwhatistheissue?InLinux,onlyprivileged
processescanchangetheUSERandGROUPfieldsofobjects.TheinitialUSERandGROUP
fieldsaresetduringobjectcreationfromtheeffectiveUSERandGROUP,whicharechecked
whenattemptingtoexecutethatprocess.Onlyprocessescreateobjects.Privileged
processescomeintwoforms:thoserunningasthealmightyrootandthosethathavetheir
capabilitiesset.Wewilldiveintothedetailsofcapabilitieslater.Fornow,let’sfocuson
theroot.
Let’schangetheusertoroottoensureexecutingthechowncommandwillchangethe
groupofthatobject:
$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
www.it-ebooks.info
Thecaseformore
YoucanseetheGROUP(GID)isnowtestuser,andthingsseemreasonablysecurebecause
inordertochangetheuserandgroupofanobject,youneedtobeprivileged.Youcanonly
changethepermissionbitsonanobjectifyouownit,withtheexceptionoftherootuser.
Thismeansthatifyou’rerunningasroot,youcandowhateveryouliketothesystem,
evenwithoutpermission.Thisabsoluteauthorityiswhyasuccessfulattackoranerroron
arootrunningprocesscancausegravedamagetothesystem.Also,asuccessfulattackon
anon-rootprocesscouldalsocausedamagebyinadvertentlychangingthepermissions
bits.Forexample,supposethereisanunintendedchmod0666commandonyourSSH
privatekey.Thiswouldexposeyoursecretkeytoallusersonthesystem,whichisalmost
certainlysomethingyouwouldneverwanttohappen.Therootlimitationispartially
addressedbythecapabilitiesmodel.
www.it-ebooks.info
www.it-ebooks.info
Capabilitiesmodel
FormanyoperationsonLinux,theobjectpermissionmodeldoesn’tquitefit.Forinstance,
changingUIDandGIDrequiressomemagicalUSERknownasroot.Supposeyouhavea
longrunningservicethatneedstoutilizesomeofthesecapabilities.Perhapsthisservice
listenstokerneleventsandcreatesthedevicenodesforyou?Suchaserviceexists,andit’s
calledueventdorusereventdaemon.Thisdaemontraditionallyrunsasroot,which
meansifitiscompromised,itcouldpotentiallyreadyourprivatekeysfromyourhome
directoryandsendthembacktotheattacker.Thismightbeanextraordinaryexample,but
it’smeanttoshowcasethatrunningprocessesasrootcanbedangerous.Supposeyou
couldstartaserviceastherootuserandhavetheprocesschangeitsUIDandGIDto
somethingnotprivileged,butretainsomesmallersetofprivilegedcapabilitiestodoits
job?ThisisexactlywhatthecapabilitiesmodelinLinuxis.
ThecapabilitiesmodelinLinuxisanattempttobreakdownthesetofpermissionsthat
roothasintosmallersubsets.Thisway,processescanbeconfinedtothesetofminimum
privilegestheyneedtoperformtheirintendedfunction.Thisisknownasleastprivilege,a
keyideologywhensecuringsystemsthatminimizestheamountofdamageasuccessful
attackcando.Insomeinstances,itcanevenpreventasuccessfulattackfromoccurringby
blockinganotherwiseopenattackvector.
Therearemanycapabilities.Themanpageforcapabilitiesisthedefactodocumentation.
Let’stakealookattheCAP_SYS_BOOTcapability:
$mancapabilities
...
CAP_SYS_BOOT
Usereboot(2)andkexec_load(2).
Thismeansaprocessrunningwiththiscapabilitycanrebootthesystem.However,that
processcan’tarbitrarilychangeUSERSandGROUPasitcouldifitwasrunningasrootor
withCAP_DAC_READ_SEARCH.Thislimitswhatanattackercando:
<FROMMANPAGE>
CAP_DAC_READ_SEARCH
Bypassfilereadpermissionchecksanddirectoryreadandexecute
permissionchecks.
NowsupposethecasewhereourrestartprocessrunswithCAP_CHOWN.Let’ssayitusesthis
capabilitytoensurethatwhenarestartrequestisreceived,itbacksupafilefromeach
user’shomedirectorytoaserverbeforerestarting.Let’ssaythisfileis~/backup,the
permissionsare0600,andUSERandGROUParetherespectiveuserofthathomedirectory.
Inthiscase,wehaveminimizedthepermissionsasbestwecan,buttheprocesscouldstill
accesstheusersSSHkeysanduploadthoseeitherbyerrororattack.Anotherapproachto
thiswouldbetosetthegrouptobackupandruntheprocesswithGROUPbackup.
However,thishaslimitations.Supposeyouwanttosharethisfilewithanotheruser.That
userwouldrequireasupplementarygroupofbackup,butnowtheusercanreadallofthe
backupfiles,notjusttheonesintended.Anastutereadermightthinkaboutthebind
www.it-ebooks.info
mounts,howevertheprocessdoingthebindmountsandfilepermissionsalsorunswith
somecapability,andthussuffersfromthisgranularityproblemaswell.
Themajorissue,andthecaseforanotheraccesscontrolsystemcanbesummarizedbyone
word,granularity.TheDACmodeldoesn’thavethegranularityrequiredtosafelyhandle
complexaccesscontrolmodelsortominimizetheamountofdamageaprocesscando.
ThisisparticularlyimportantonAndroid,wheretheentireisolationsystemisdependent
onthiscontrol,andaroguerootprocesscancompromisethewholesystem.
www.it-ebooks.info
www.it-ebooks.info
Android’suseofDAC
IntheAndroidsandboxmodel,everyapplicationrunsasitsownUID.Thismeansthat
eachappcanseparateitsstoreddatafromoneanother.Theuserandgrouparesettothe
UIDandGIDofthatapplication,sonoappcanaccesstheprivatefilesofanapplication
withouttheapplicationexplicitlyperformingchmodonitsobjects.Also,applicationsin
Androidcannothavecapabilities,sowedon’thavetoworryaboutcapabilitiessuchas
CAP_SYS_PTRACE,whichistheabilitytodebuganotherapplication.InAndroid,ina
perfectworld,onlysystemcomponentsrunwithprivileges,andapplicationsdon’t
accidentallychmodprivatefilesforalltoread.Thisissuewasnotcorrectedbythecurrent
AOSPSELinuxpolicyduetoappcompatibility,butcouldbeclosedwithSELinux.The
properwaytosharedatabetweenapplicationsonAndroidisviabinder,andsharingfile
descriptors.Forsmalleramountsofdata,theprovidermodelsuffices.
www.it-ebooks.info
www.it-ebooks.info
GlancingatAndroidvulnerabilities
WithournewlyfoundunderstandingoftheDACpermissionmodelandsomeofits
limitations,let’slookatsomeAndroidexploitsagainstit.Wewillcoveronlyafew
exploitstounderstandhowtheDACmodelfailed.
www.it-ebooks.info
Skypevulnerability
CVE-2011-1717wasreleasedin2011.Inthisexploit,theSkypeapplicationleftaSQLite3
databaseworldreadable(somethinganalogousto0666permissions).Thisdatabase
containedusernamesandchatlogs,andpersonaldatasuchasnameande-mail.An
applicationcalledSkypwnedwasabletodemonstratethiscapability.Thisisanexample
ofhowbeingabletochangethepermissionsonyourobjectscouldbebad,especially
whenthecaseopensREADtoOTHERS.
www.it-ebooks.info
GingerBreak
CVE-2011-1823showcasesarootattackonAndroid.Thevolumemanagementdaemon
(vold)onAndroidisresponsibleforthemountingandunmountingoftheexternalSD
card.ThedaemonlistensformessagesoveraNETLINKsocket.Thedaemonnever
checkedwherethemessagesweresourcedfrom,andanyapplicationcouldopenand
createaNETLINKsockettosendmessagestovold.Oncetheattackeropenedthe
NETLINKsocket,theysentaverycarefullycraftedmessagetobypassasanitycheck.
Thechecktestedasignedintegerforamaximumbound,butnevercheckeditfor
negativity.Itwasthenusedtoindexanarray.Thisnegativeaccesswouldleadtomemory
corruptionand,withapropermessage,couldresultintheexecutionofarbitrarycode.The
GingerBreakimplementationresultedinanarbitraryusergainingrootprivileges,a
textbookprivilegeexecutionattack.Oncerooted,thedevice’ssandboxeswerenolonger
valid.
www.it-ebooks.info
Rageagainstthecage
CVE-2010-EASYisasetuidexhaustionviaforkbombattack.Itsuccessfullyattacksthe
adbdaemononAndroid,whichstartslifeasrootanddowngradesitspermissionsifrootis
notneeded.Thisattackkeepsadbasrootandreturnsarootshelltotheuser.InLinux
kernel2.6,thesetuidsystemcallreturnsanerrorwhenthenumberofrunningprocesses
RLIMIT_NPROCismet.Theadbdaemoncodedoesnotcheckthereturnofsetuid,which
leavesasmallracewindowopenfortheattacker.Theattackerneedstoforkenough
processestoreachRLIMIT_NPROCandthenkillthedaemon.Theadbdaemondowngrades
toshellUIDandtheattackerrunstheprogramasshellUSER,thusthekillwillwork.Atthis
point,theadbserviceisrespawned,andifRLIMIT_NPROCismaxedout,setuidwillfail
andadbwillstayrunningasroot.Then,runningadbshellfromahostreturnsaniceroot
shelltotheuser.
www.it-ebooks.info
MotoChopper
CVE-2013-2596isavulnerabilityinthemmapfunctionalityofaQualcommvideodriver.
AccesstotheGPUisprovidedbyappstodoadvancedgraphicsrenderingsuchasinthe
caseofOpenGLcalls.Thevulnerabilityinmmapallowstheattackertommapkerneladdress
space,atwhichpointtheattackerisabletodirectlychangetheirkernelcredential
structure.ThisexploitisanexamplewheretheDACmodelwasnotatfault.Inreality,
outsideofpatchingthecodeorremovingdirectgraphicsaccess,nothingbutprogramming
checksofthemmapboundscouldhavepreventedthisattack.
www.it-ebooks.info
www.it-ebooks.info
Summary
TheDACmodelisextremelypowerful,butitslackoffinegranularityanduseofan
extraordinarilypowerfulrootuserleavessomethingtobedesired.Withtheincreasing
sensitivityofmobilehandsetuse,thecasetoincreasethesecurityofthesystemiswellfounded.Thankfully,AndroidisbuiltonLinuxandthusbenefitsfromalargeecosystem
ofengineersandresearchers.SincetheLinuxKernel2.6,anewaccesscontrolmodel
calledMandatoryAccessControls(MAC)wasadded.Thisisaframeworkbywhich
modulescanbeloadedintothekerneltoprovideanewformofaccesscontrolmodel.The
veryfirstmodulewascalledSELinux.ItisusedbyRedHatandotherstosecuresensitive
governmentsystems.Thus,asolutionwasfoundtoenablesuchaccesscontrolsfor
Android.
www.it-ebooks.info
www.it-ebooks.info
Chapter2.MandatoryAccessControls
andSELinux
InChapter1,LinuxAccessControls,weintroducedsomeoftheshortcomingsofa
discretionaryaccesscontrolsystem.Inthesesystems,theownerofanobjecthasfull
controloveritspermissionsflagsandcandemonstrategreatercapabilities(forexample,
theabilitytochown)whenexecutingasrootorwithcertaincapabilities.Inthischapter,
wewill:
ExaminethefundamentalsofMAC
IntroducesomeindustrydriversforSELinux
Discusslabels,users,roles,andtypes
Exploretheimplementationoftangiblepolicytoallowandconstrainobject
interaction
IdealMACsystemsmaintainthepropertyofprovidingdefinitiveaccesscontrolson
kernelresources,suchasfiles,irrespectiveofanobject’sowner.Forinstance,withaMAC
system,theownerofanobjectmightnothavefullcontrolofitspermissions.InLinux,the
MACframeworkworksorthogonallytothecurrentDACcontrols.Thismeansthatthe
MACcontrolsdonotinterferewiththeDACcontrols.Inotherwords,toavoidpotential
conflictsbetweentheMACandDACsystems,thekernelvalidatesaccessusingtheDAC
permissionsbeforecheckingtheMACpermissions.IftheDACpermissionsresultina
permissionsviolation,thentheMACpermissionsareneverchecked.Thekernelwill
validateaccessagainsttheMACpermissionsprovideronlywhentheDACpermissions
pass.FailureateitherlevelwillresultinareturnofEACCESS.IftheDACandtheMAC
permissionspass,thenthekernelresource(forexample,afiledescriptor)issentbackto
userspace.
InLinux,aframeworkcalledtheLinuxSecurityModule(LSM)frameworkwasmerged
duringtheLinux2.6.xseriesofkernels.Thisframeworkallowsyoutoenablethe
mandatoryaccesscontrolsystemsinabuildtimeselectionbytetheringtheLSMhooksto
thesecurityprovider.SecurityEnhancedLinux(SELinux)isthefirstconsumerofthis
MACsecurityframeworkwithinthekernelandisanimplementationofamandatory
accesscontrolsystem.SELinuxshipsinawidevarietyofLinuxsystems,suchasRedHat
EnterpriseLinux(RHEL)andconsequentlyFedora.Recently,ithasbegunshipping
withAndroid.ThesourcecodeforSELinuxcanbefoundintheLinuxsourcecodetree
underkernel/security/selinuxforthosewishingtoreviewit.
www.it-ebooks.info
Gettingbacktothebasics
SELinuxisareimplementationofadesignengineeredbytheU.S.governmentandThe
UniversityofUtahknownastheFLUXAdvancedSecurityKernel(FLASK).The
SELinuxandFLASKarchitectureprovideacentralpolicyfileutilizedwhiledetermining
theresultsofaccesscontroldecisions.Thiscentralpolicyisinawhitelistform.This
meansthatallaccesscontrolrulesmustbedefinedexplicitlybythepolicyfile.This
policyfileisabstractedandservedbyasoftwarecomponentcalledasecurityserver.
WhentheLinuxkernelneedstomakeanaccesscontroldecisionandSELinuxisenabled,
thekernelinteractswiththesecurityserverbymeansoftheLSMhooks.
Inarunningsystem,aprocessistheactiveentitythatgetstimeontheCPUtoperform
tasks.Theusermerelyinvokestheseprocessestodotheworkontheirbehalf.Thisisan
importantconcept.Aswetypethisbook,wetrustthatthewordprocessorsrunningonour
machineswithourcredentialsaren’topeningourSSHkeysandembeddingtheminthe
documentmetadata.Rightnow,theprocessisincontrolofthecomputingresources,not
theuser.Theprocessistherunningentity,itistheprocessthatmakessystemcallstothe
kernelforresources,notthephysicalhumanbeing.Withthisinmind,theveryfirstactor
inthisSELinuxsystemistheprocess,typicallyreferredtoasthesubject.Itisthesubject
thataccessesfiles.Itisthesubjectthatthesecurityserverwillusetomakeaccess
decisionson.
Consequently,thesubjectutilizeskernelresources.Thiskindofkernelresourceisan
exampleofatarget.Thesubjectperformsactionsonthetarget.Naturally,oneshouldask,
“Whatactionsdoesasubjectperform?”Theseareknownasaccessvectorsandtypically
correlatetothenameofthesyscallperformed.Forexample,thesubjectcouldperforman
openonthetarget.Itisimportanttonotethattargetscouldbeprocessesaswell.For
instance,ifthesystemcallisptrace,thesubjectcouldbesomethingalongthelinesofa
debugger,andthetargetwouldbetheprocessyouwishtodebug.Asubjectisfrequentlya
process,butatargetcouldbeaprocess,socket,file,orsomethingelse.
www.it-ebooks.info
www.it-ebooks.info
Labels
SELinuxprovidessemanticsfordescribingpoliciesrelatedtothetargetsandsubjects
usinglabels.Labelsarethemetadataassociatedwithanobjectthatmaintainsthesubject’s
andtarget’saccessinformation.Thedataassociatedwiththisobjectisastring.Returning
tothedebuggerexample,thegdbprocessmighthaveasubjectlabelstringofdebugger,
andthetargetmighthavealabelofdebugee.Theninthesecuritypolicy,somesemantic
couldbeusedtoexpressthatprocesseswiththesubjectlabeldebuggerareallowedto
debugapplicationswithtargetlabeldebugee.
Fortunately,andperhapsunfortunately,SELinuxdoesnotusesuchsimplelabels.Infact,
thelabelsaremadeupoffourcolon-delimitedfields:user,role,type,andlevel.This
additionalcomplexityaffordsveryflexiblecontroloptions.
www.it-ebooks.info
Users
Theveryfirstfieldinalabelidentifiestheuser.Theuserfieldisusedaspartofthedesign
foruser-basedaccesscontrols(UBAC).However,thisisnottypicallyassociatedwith
humanusersasitiswiththeconceptofusersinDAC.SELinuxuserstypicallydefinea
groupoftraditionalusers.Acommonexampleistoidentifyallnormalusersasthe
SELinuxuser,user_u.Perhapsaseparateuserforsystemprocesses,suchassystem_u.By
conventioninthedesktopSELinuxcommunity,userportionsofthestringaresuffixed
witha_u.
www.it-ebooks.info
Roles
Thesecondfieldinalabelisrole.Theroleisusedaspartofthedesignforrole-based
accesscontrols(RBAC).Rolesareusedtoprovideadditionalgranularitytotheuser.For
instance,supposewehavetheuserfield,sysadm_u,reservedforadministrators.The
administratormightbeinseparatetasks,anddependingonthetasks,therole(and
therefore,privileges)ofusersinsysadm_umaychange.Forexample,whenan
administratorneedstomountandunmountfilesystems,therolefieldmightchangeto
mount_admin_r.Whenanadministratorissettingtheiptablesrules,therolemight
changetonet_admin_r.Rolesallowtheisolationofprivilegeswithinthescopeofthe
tasksbeingperformed.
www.it-ebooks.info
Types
Typeisthethirdfieldofthecolon-delimitedlabel.Thetypefieldisevaluatedduringthe
typeenforcement(TE)portionofSELinux’saccesscontrolmodel.TEisthemajor
componentthatdrivesSELinux’ssecuritycapabilities,anditisatthispointwherethe
policystartstotakeeffect.
SELinuxisbasedonawhitelistsystemwhereeverythingisdeniedbydefaultandrequires
explicitapprovalfromthepolicyforaninteractiontooccur.Thisapprovalisinitially
determinedfromthepolicyviaanallowrulethatreferencesboththesubject’sandtarget’s
type.SELinuxtypescanalsobeassignedattributes.Attributesallowyoutogive
numeroustypesacommonsetofrules.Attributescanhelpminimizetheamountoftypes,
andcanbeusedinfashionsimilartothatofaninheritancemodel.
www.it-ebooks.info
www.it-ebooks.info
Accessvectors
Dataisaccessedbyprocessesviasystemcallsandpossibleuserdefinedaccessmethods.
Theuserdefinedaccessmethodsareusuallycontrolledviaauserspaceobjectmanager.
Theseaccesspaths,alsoknownasvectors,makeupasetofactionsthatcanbeappliedto
theobject.Forinstance,ifaprocessopensafile,writessomedataintothefile,andthen
readsitback,theaccessvectorsexercisedwouldbeopen,read,andwrite.Ifaprocess
debugsanotherprocess,theaccessvectorwouldbeptrace.
www.it-ebooks.info
www.it-ebooks.info
Multilevelsecurity
SELinuxalsosupportsamultilevelsecurity(MLS)model,whichpayshomagetothe
Bell-LaPadula(BLP)model,butalternatemodelscouldbeused.TheBLPmodelwas
createdtoformalizetheDepartmentofDefense’ssecuritypolicies.Forexample,aperson
withasecretclearanceshouldnotbeabletoreadtop-secretmaterial.However,let’s
supposethispersonhasabrilliantideathatultimatelyneedstobeprotectedatthetopsecretlevel;thatdatacouldthenbe“up-classified”totop-secret.Thisisreferredtoas“no
readuporwritedown”.
TheSELinuximplementationofthisfieldhassubfields.Thefirstfieldissensitivity,and
willalwaysbepresent.Inthecontextofthepreviousexample,pertinentsensitivities
includesecretandtopsecret.Thesecondsubfieldiscategory,andmightnotbepresent.
Thesefieldsalsomakesenseinthecontextofgovernmentclassification.Thedataitself
mightbecompartmentalized,sowhilethesensitivityisthesame,suchastopsecret,the
datashouldonlybedisseminatedtopeoplewithinthesamecompartmentorcategory.
Sensitivitiesaredefinedinahierarchicalfashionviathedominancekeyword.Inatypical
policy,s0isthelowestsensitivityandsNwheren>0isthehighest.Thus,s1hasa
greatersensitivitythans0.Categoriesaresets.Thecontrolsassociatedwiththelevel,
whichiscomprisedofsensitivitiesandpotentiallycategories,followsettheoryconcepts,
suchasdominanceandequality.InMLSsecurity,allinteractionsareallowedbydefault,
unliketypeenforcement.Boththesensitivityandthecategorycanberanged,and
categoriescanbeenumerated.Thus,alabelmighthavesomenumberofsensitivitiesand
differentnumberofcategories.
www.it-ebooks.info
www.it-ebooks.info
Puttingittogether
SELinuxlabelsarequiteflexibleandsometimescomplex.It’softenbeneficialtostart
withacontrivedexamplethatfocusesontypeenforcement.Later,wecanaddadditional
fieldslaterastheneedforfinergranularitybecomesmoreapparent.Conveniently,youcan
projectthismodeltoscenariosineverydaylifetoprovidesomesenseoftangibilitytothe
material.DanWalsh,aprominentSELinuxfigure,postedablogpostusingpetsasan
analogy.Let’scontinueonwiththatpremise,butwewillmakesomemodificationsaswe
goanddefineourownexamples.It’sbesttostartwithsimpletypeenforcementasitisthe
easiesttounderstand.
Note
YoucanreadDanWalsh’soriginalblogpostintroducingthepetanalogyat
http://opensource.com/business/13/11/selinux-policy-guide.
Supposeweownacatandadog.Wedon’twantthecattoeatdogfood.Wedon’twantthe
dogtoeatcatfood.Atthispoint,wehavealreadyidentifiedtwosubjects,acatandadog,
andtwotargets,catfoodanddogfood.Wealsohaveidentifiedanaccessvector,eating.
Wecanuseallowrulestoimplementourpolicy.Possiblerulescouldlooklikethis:
allowcatcat_chow:foodeat;
allowdogdog_chow:foodeat;
Let’susethisexampletostartanddefineabasicsyntaxforexpressingtheaccesscontrols
wewouldliketoenforce.Thefirsttokenisallow,statingwewishtoallowaninteraction
betweenasubjectandatarget.Thedogisassignedthetype,dog,andthecat,cat.Thecat
foodisassignedthetypecat_chow,andthedogfood,dog_chow.Theaccessvectorinthis
caseiseat.Withthisbasicsyntax,whichisalsovalidSELinuxsyntax,werestrictthe
animalstothefoodtheyshouldeat.Noticethe:foodannotationafterthetype.Thisisthe
classfieldofthetargetobject.Forinstance,theremightalsobedog_chowtreatand
cat_chowclassesthatcouldindicateourdesiretoallowaccesstotreatsinafashionthatis
potentiallydifferentfromthewayweallowaccesstofoodsthatarenottreats.
Let’ssaywegettwomoredogs,andourscenariohasthreedogs.Thedogsareofdifferent
sizes:small,medium,andlarge.Wewanttomakesurenoneofthesenewdogseatothers’
food.Wecoulddosomethinglikecreateanewtypeforeachofthedogsandpreventdogs
fromeatingthefoodofotherdogs.Itwouldlooksomethinglikethis:
allowcatcat_chow:foodeat;
allowdog_smalldog_small_chow:foodeat;
allowdog_mediumdog_medium_chow:foodeat;
allowdog_largedog_largechow:foodeat;
Thiswouldwork;however,thetotalnumberoftypeswouldbedifficulttomanage,and
thatwouldcontinuetogrowifweallowthelargedogtoeatthesmallerbreeds’food.
WhatwecoulddoisuseMLSsupporttoassignasensitivitytoeachtargetordogfood
bowl.Let’sassumethefollowing:
Thecat’sfoodbowlhassensitivity,tiny
www.it-ebooks.info
Thesmalldog’sfoodbowlhassensitivity,small
Themedium-sizeddog’sfoodbowlhassensitivity,medium
Thelargedog’sfoodbowlhassensitivity,large
Wealsoneedtomakesurethatthesubjectsarelabeledwiththepropersensitivityaswell:
Thecatshouldhavesensitivity,tiny
Thesmalldogshouldhavesensitivity,small
Themedium-sizeddogshouldhavesensitivity,medium
Thelargedogshouldhavesensitivity,large
Atthispoint,weneedtointroduceadditionalsyntaxtoallowtheinteractions,sinceby
default,MLSallowseverythingandTEdenieseverything.We’llusemlsconstrain,to
restrictinteractionswithinthesystem.Therulecouldlooklikethis:
mlsconstrainfoodeat(l1eql2);
Thisconstraintonlyallowssubjectstoeatfoodwiththesamesensitivitylevel.SELinux
definesthekeywordsl1andl2.Thel1keywordisthelevelofthetargetandl2isthe
levelofthesource.Becausetherulesarepartofawhitelist,thisalsopreventssubjects
fromeatingfoodthatdoesnothavetheequivalentsensitivitylevel.
Now,let’ssaywegetyetanotherlargedog.Nowwehavetwolargebreeddogs.However,
theyhavedifferentdietsandneedtoaccessdifferentfoods.Wecouldaddanewtypeor
modifyanexistingtype,butthiswouldhavethesamelimitationsthatledustouse
sensitivitiestopreventaccess.Wecouldaddanothersensitivity,butitmightgetconfusing
thattherearelarge1andlarge2sensitivities.Atthispoint,categorieswouldallowusto
getabitmoregranularinourcontrols.Supposeweaddacategorydenotingthebreed.Our
MLSportionofourlabelwouldlooksomethinglikethis:
large:golden_retriever
large:black_lab
Thesecouldbeusedtopreventtheblacklabfromeatingthegoldenretriever’sfood.Now
supposeyou’resurprisedwithanotherdog,aSaintBernard.Let’ssaythisnewBernard
caneatanylargedog’sfood,buttheotherlargedogscan’teathisfood.Wecouldlabelthe
foodbowlsandthedogs.
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.IftheSaintBernardranoutoffoodand
wenttotheBlackLab’sdish,theSaintBernardwouldnotbeabletoeatfromitsincethe
levelsarenotequal(Dog:large:saint_bernard,black_lab,golden_retrieverisnot
www.it-ebooks.info
thesameasdog_chow:large:black_lab).Remember,thelevelsaresets,soweneedto
introducesomenotionthatifthesubjectssetdominatesthetargetset,thatinteraction
shouldbeallowed.
Thiscouldbeaccomplishedwiththedomkeyword:
mlsconstrainfoodeat(l1doml2);
Thedominatekeyword,dom,differsfromequality,indicatingl1isasupersetofl2In
otherwords,thelevelsassociatedwiththetarget,l2,areamongthepotentiallylargerset
oflevelsassociatedwiththesubject,l1.Atthispoint,weareabletokeepallthefood
separatedandusedhoweverweseefit.
Aftergettingallthesedogs,yourealizeit’stimetofeedthem,soyougetabagofdog
foodandputsomeineachbowl.However,beforeyoucanadddogfoodtothebowls,we
needsomeallowrulesandlabelsthatwillletyou.Remember,SELinuxisawhitelistbasedsystem,andeverythingmustbeexplicitlyallowed.
Wewilllabelthehumanwiththehumanlabelanddefinesomerules.Ohyeah…don’t
forgettofeedthecat,aswell:
allowhumandog_chow:foodput;
allowhumancat_chow:foodput;
Wewillalsoneedtolabelhumanwithallthesensitivitiesandcategories,butthiswould
becomecumbersomewhenweneedtoaddadditionaldogs,breeds,andbreedsizestoour
system.Wecouldjustbypasstheconstraintifthetypeishuman.Withthisapproach,we
alwaystrusthumantoputthecorrectfoodintheappropriatebowl:
mlsconstrainfoodeat(l1doml2);
mlsconstrainfoodput(t1==human);
NotetheadditionofputintheaccessvectorsoftheMLSconstraint.Viola!Thehuman
cannowfeedhisever-growingpackofanimals.
Soyourbirthdayrollsaround,andyoureceiveanautomaticdogfeederasapresent.You
labelthefooddispenser,dispenserandmodifytheMLSconstraints:
mlsconstrainfoodeat(l1doml2);
mlsconstrainfoodput(t1==humanort1==dispenser);
Again,weseeaneedtocondensethenumberoftypesandgetorganizedtopreventhaving
toduplicatelines.Thisiswhereattributesarequitehandy.Wecanassignanattributeto
ourhumananddispensertypesbyfirstdefiningtheattribute:
attributefeeder;
Thenwecanaddittothetype:
typeattributehuman,feeder;
typeattributedispenser,feeder;
Thiscouldalsobedoneattypedeclaration:
typehuman,feeder;
www.it-ebooks.info
typedispenser,feeder;
Atthispoint,wecouldmodifytheMLSstatementstolooklikethis:
mlsconstrainfoodeat(l1doml2);
mlsconstrainfoodput(t1==feeder);
Nowlet’ssupposeyouhireamaidservice.Youwanttoensureanyonesentbythemaid
serviceisabletofeedyourpets.Forthatmatter,let’sletyourfamilymembersfeedthem,
aswell.Thiswouldbeagoodusecasefortheusercapabilities.Wewilldefinethe
followingusers:adults_u,kids_u,andmaid_u.Thenwe’llneedtoaddaconstraint
statementtoallowinteractionsbytheseusers:
mlsconstrainfoodput(u1==adults_uoru1==maid_u);
Thiswouldpreventthekidsfromfeedingthedogs,butletthemaidsandadultsfeedthem.
Nowsupposeyouhireagardener.Youcouldcreateyetanotheruser,gardener_u,oryou
couldcollapsetheusersintoafewclassesanduseroles.Let’ssupposewecollapse
gardener_uandmaid_uintostaff_u.Thereisnoreasonthegardenershouldbefeeding
thedog,sowecoulduserole-basedtransitionstomovethestaffbetweentheirduties.For
instance,supposestaffcanperformmorethanoneservice,thatis,thesamepersonmight
gardenandclean.Inthiscase,theymighttakeontheroleofgardener_rormaid_r.We
couldusetherolecapabilityofSELinuxtomeetthisneed:
mlsconstrainfoodput(u1==adults_uor(u1==staff_uandr1==
animal_care_r);
Staffmayonlyfeedthedogswhenthey’reintheanimal_care_rrole.Howtogetintoand
backoutofthatroleisreallytheonlycomponentmissing.Youneedtohaveawelldefinedsystemforhowthestaffcanmoveintotheanimalcareroleandtransitionback
out.ThesetransitionsinSELinuxoccureitherautomaticallyviadynamicroletransitions
orviasourcecodemodifications.We’llassumethatanyhumanentity(gardener,adults,
kids)allstartinthehuman_rrole.
Dynamicroletransitionsworkwithatwo-partrule,thefirstpartallowsthetransitionto
occurviaanallowrule:
allowhuman_ranimal_care_r;
Theroletransitionstatementsareasfollows:
role_transitionhuman_rdog_chowanimal_care_r;
role_transitionhuman_rcat_chowanimal_care_r;
Thiswouldbeagoodcasetoattributethedog_chowandcat_chowtypestoanew
attribute,animal_chow,andrewritetheprecedingroletransitionsto:
typeattributedog_chow,animal_chow;
typeattributecat_chow,animal_chow;
role_transitionhuman_ranimal_chowanimal_care_r;
Withtheseroletransitions,youcanonlygofromthehuman_rroletoanimal_care_r.You
wouldneedtodefinetransitionstogetbackaswell.It’salsoimportanttonotethatyou
www.it-ebooks.info
mightdefineotherroles.Supposeyoudefinetherolegardener_r,andwhensomeoneis
inthatrole,theycannottransitiontoanimal_care_r.Supposeyourjustificationforthis
policyisthatgardenersmightworkwithchemicalsunsafeforpets,sotheywouldneedto
washtheirhandsbeforefeedingpets.Insuchasituation,theyshouldonlybeableto
transitiontoanimal_care_rfromthehand_wash_rrole.
www.it-ebooks.info
www.it-ebooks.info
Complexitiesandbestpractices
Asyoucannowappreciate,SELinuxiscomplex,andcanbethoughtofasageneral
purpose“metaprogrammingpolicylanguage”.You’reliterallyprogrammingwhat
interactionsareallowedtooccurinaverycomplexOSsuchasLinux,wherethe
interactionsthemselvesareoftencomplex.Justlikeaprogramminglanguage,youcando
thingswithdifferentstylesandmethodsthatwillyielddifferingresults.Perhapsusinga
switch()inthatprogramwillmakeitcleanerandeasiertounderstandratherthanan
else-ifblock,eventhoughfunctionallyyouwillendupwiththesamething.SELinuxis
thesame;youcanoftenaccomplishthingswithoneportionoftheenforcement
mechanismsthatwouldbemoreappropriatelyaccomplishedusinganalternate
mechanism.Inlaterchapters,wewillcovertheprocessoflabelingthetargetandsubject,
oneofthemoredifficultpartsofthesystem.
Whensomeoneauthorsaprogram,theyoftenhaveasetofrequirementsinplacethatthe
softwareshouldperform.Thesearetherequirementsofthesoftware.InSELinux,you
shoulddothesamething.Youshouldgatherthesecurityrequirementsandunderstandthe
threatmodelsyouwishtoprotectyourselffrom.AwelldesignedSELinuxpolicywould
meetthesegoals.Agreatdesignwoulddoitinawaythatiseasytoextend.That’s
ultimatelywherecarefulandjudicioususeofthecombinationofUBAC,RBAC,TE,and
MLSwillhelpachievetherequirementsanddesigngoals.
www.it-ebooks.info
www.it-ebooks.info
Summary
Inthischapter,wecoveredthemajorworkingportionsofSELinuxthatincludetype
enforcement,multilevelandmulticategorysecurity,aswellasusersandroles.
Additionally,wesawhowtoapplythesetechnologiestoimplementincreasinglycomplex
accesspoliciestoatangibleexample.Inthenextchapter,wewillmoveoutsideofthe
kernelanddiscoverhowAndroidworksinitsveryuniqueuserspace.
www.it-ebooks.info
www.it-ebooks.info
Chapter3.AndroidIsWeird
Itreallyis.AlthoughitisbuiltonthefamiliarLinuxkernel,Androidhasacompletely
customuserspace,andwhilemanyofitsfunctionalitiesarerewritesoftheirGNU
cousins,someareeitherneworhavesignificantlydifferentfunctionsthantheirdesktop
counterparts.Becauseofthesedifferences,thesesystemshadtobemodifiedtosupport
SELinux.Inthischapter,wewill:
IntroducetheAndroidsecuritymodel
Investigatebinder,zygote,andthepropertyservice
CoverwhichSELinuxelementswereaddedtocomplementthesesystemsandwhy
Thecoverageofthesesystemswillbemoderate,butwewillpresentmoreintricatedetails
ofeachsystemlater,whenappropriate,inourexploratoryinvestigationofSEforAndroid.
www.it-ebooks.info
Android’ssecuritymodel
Android’scoresecuritymodelisbasedonLinuxDAC,includingcapabilities.Android,
however,usestheLinuxconceptofUID/GIDinaverynon-traditionalway.Eachprocess
onthesystemhasitsownUIDratherthantheUIDofwhoeverlaunchedit.TheseUIDs
(generallyunique)providesandboxingandprocessisolation.Thereareafew
circumstances,though,whereprocessescanshareUIDsandGIDs.Typically,whena
processsharesaUIDwithanotherprocess,itisbecausetheybothneedthesamesetof
permissionsonthesystemandsharedata.ThesamecouldbepossibleforGIDs.However,
someGIDsinAndroidareactuallyusedtogainpermissiontoaccessunderlyingsystems,
suchastheSDcardfilesystem.Inanutshell,theUIDisusedtoisolateprocessesandnot
thehumanusersofthesystem.Infact,Androiddidn’thavesupportformultiplehuman
usersuntilitsJellyBean4.3release.Itwasalwaysintendedfordeviceswithasingle
humanuser…atleastinoperation.
Withinthissecuritymodel,therearetwoprocessclasses.Thefirstiscalledsystem
componentservices.Thesearetheservicesdeclaredinthesysteminitscripts.Theytend
tobehighlyprivilegedandthusalmostnevershareaUIDwithanotherprocess.An
examplesystemcomponentservicewouldbetheRadioInterfaceLayerDaemon
(RILD).RILDisresponsibleforprocessingmessagesbetweenAndroiduserspaceandthe
modemonthedevice.Becauseofthenatureofwhatitdoes,ittypicallyrunsasUIDroot.
Thereisnorequirementthatprocessesbepurenativecode.Systemserverhasnon-native
components,runsasthesystemUID,andishighlyprivileged.Almostallofthesesystems
shareacommontheme;theyhaveaUIDthatiseitherrootorissettotheownerofmany
sensitivekernelobjects,suchassockets,pipes,andfiles.
Thesecondclassisapplications.ApplicationsaretypicallywritteninJava,althoughthisis
notarequirement;thisissimilartohowsystemcomponentservicesaretypicallywritten
innativecodewithoutitbeingarequirement.TheseapplicationshaveUIDsassigned
automaticallywhentheyareinstalled,andtheseUIDsarereservedbythesystemforthis
purpose.ThepackagemanagerisresponsibleforissuingUIDstoapplications.These
UIDshavenotiestoanythingsensitiveordangerousonthesystem,andtheapplications
runwithnocapabilities.Inordertoaccessasystemresource,anapplicationmusthaveits
supplementarygroupappendedtooritmustbearbitratedbyaseparateprocess.
Asimpleexampleofutilizingthesupplementarygroupisseenwhenanapplicationneeds
tousetheSDcard.ForapplicationstoaccesstheSDcard,theymusthaveSDCARD_RWin
theirsupplementaryGIDs.ThesepermissionsareenforcedwithstandardLinuxDAC
permissionsbythekernel.Thesupplementarygroupisassignedbythepackagemanager
duringtheapplication’sinstallationbasedonadeclaredpermission.Applicationsin
Androidmustdeclaresomethingcalleduses-permissionintheapplication’smanifest.
ThispermissionappearsasastringwhichismappedtoasupplementaryGID.This
mappingismaintainedinafileinthesystem,specifically
/system/etc/permissions/platform.xml.Youwillseeanapplicationofthese
permissionstringsinalaterchapter.
www.it-ebooks.info
Thesecondwayanapplicationgainsaccesstoasystemresourceisthroughanother
process.Theapplicationwishingtouseasystemresourcemustgetanotherprocesstodo
thisonitsbehalf.Mostrequestsarehandledbyaprocessknownasthesystemserver.
Thesystemservercheckswhethertheapplicationmakingthearbitrationrequesthad
declaredamatchingpermissionstringinitsmanifestfile.Ifitdid,it’sallowedtoproceed,
otherwiseasecurityexceptionisthrown.EvenarbitratedaccessesinAndroiduseaDAC
model,inessence.Whiletheobjectownercontrolstheaccessrulesontheobjectvia
permissionstrings,anyconsumeroftheprotectedobjectcanjustrequestthepermission
stringtogetaccess.Essentially,anyonecanwriteanapplicationrequestingany
permissionstringstheywant.Whileinstallinganapplication,theuserispresentedwith
thelistofpermissionsrequestedbytheapplication,whichtheychoosetoacceptorreject
enmasse.Iftheuser’sintentistoinstalltheapplication,allrequestedpermissionsmustbe
granted.Iftheuserisnotcareful,theymightinadvertentlyallowthatapplicationtoaccess
protectedobjectsinawaythatcanthreatenthesecurityofthedevice,applications,oruser
data.Theownersofthedevicesshouldalwaysensuretheyarecomfortablewiththe
applicationusingthedeclaredpermissions.
Note
Forexamplesorfurtherdiscussion,referto
http://developer.android.com/guide/topics/security/permissions.html.
www.it-ebooks.info
www.it-ebooks.info
Binder
ThearbitratedaccessmethoddiscussedbeforerequiressomeformofInterprocess
Communication(IPC),andwhileAndroiddoesuseUnixdomainsockets,italsobrings
itsownIPCmechanismthatisusedmorewidelythroughoutthesystem.ThisIPC
mechanismiscalledbinderandisthecoreIPCmechanismintheAndroidoperating
system.IthashistoricalrelevancefromtheBeOSandPalmOSimplementationsof
OpenBinder,andsincetheinitialAndroiddevelopmentteamwascomprisedofmany
OpenBinderengineers,binderwentwiththemtoAndroid.However,Androidhasa
complete,fromscratchrewriteofthebindercodebasethatisspecifictoLinux.
Note
BinderiscurrentlynotcompletelymainstreamedintotheLinuxkernel,andmanyof
Android’skernelchangesarestillstaged.
Thereissomecontroversyaroundbinderanditsmainlineadoption.Somepeopleargue
againsttheamountofheavyliftingitdoeswithinthedriverincontrasttocompeting
implementationssuchasdbus.However,itwilllikelybealongtimebeforeweseethe
resolutionofthisdebate.RegardlessofwhetherbinderstaysanAndroid-specific
technology,ismainstreamedintheLinuxkernel,oriseventuallyreplacedbyanother
technologyinAndroid,binderisheretostayfortheforeseeablefuture.
www.it-ebooks.info
Binder’sarchitecture
BinderIPCfollowsaclient/serverarchitecture.Aservicepublishesaninterfaceand
clientsconsumefromthatinterface.Clientscanbindtoservicesviaoneofthetwo
methods:knownaddressorservicename.
Eachbinderinterfaceinthesystemisknownasabindernode.Eachbindernodehasan
address.Whenclientswanttouseaninterface,theymustbindtoabindernodeviathis
address.ThisisanalogoustobrowsingawebpageviaitsIPaddress.However,unlikean
IPaddressthatisusuallyfixedforlongdurationsoftime,thebinderaddresscouldchange
basedonrestartsofthepublishingserviceorontheservicestartuporderattheboottime
ofthedevice.Theorderofprocessesisn’tquiteguaranteed,thusthepublishingofprocess
servicescanresultinadifferentbindertoken(asimplebinderobjecttoshareamong
processes)beingassigned.Also,thisindirectionallowstheruntimeabilitytoreseat
serviceimplementationsusingjustthepublishedservicenameswithoutthenecessityto
utilizethetoken.
ThewaythisredirectionfunctionsissimilartohowDNSprovidestheresolutionfrom
nametoIPaddressfornetworkeddeviceaccesses.Binderhassomethingcalledthe
contextmanager(alsoknownastheservicemanager).Thecontextmanagerlivesata
fixednodeaddressof0.Publishingservicessendanameandabindertokentothecontext
manager,andthen,whenclientsneedtofindaservicebyname,theycheckbindernode0
andresolvethenametothebindertoken.Abindertokenisthepropernameforthis
address,orID,thatuniquelyaddressesabinderinterface.Afteraclientbindstothebinder
object,whichisaprocessthatimplementsthebinderinterface,theprocessesthenperform
bindertransactionsusingawell-establishedbinderprotocol.Thisprotocolallows
synchronoustransactionsanalogtoamethodcall.
Sincebinderisakerneldriver,ithassomenicefeaturesthatdeterminewhatonecando
acrosstheinterface.Forstarters,itallowsthetransmissionoffiledescriptors.Italso
managesathreadpoolfordispatchingservicemethods.Additionally,itemploysan
approachreferredtoaszerocopywherebybinderdoesnotcopyanyofthetransaction
databetweenprocesses…itsharestheminstead.Binderalsoaffordsreferencecountingof
objectsandletsservicesquerytheclientapplication’sLinuxcredentialslikeUID,GID,
andProcessID(PID).Binderalsoallowstheserviceandclienttoknowwhentheother
hasterminatedviaitslinktodeathfunctionality.
TypicallyinAndroid,youdon’tworkwithbinderdirectly.Instead,youworkwitha
serviceratherviaaserviceanditsAndroidInterfaceDescriptionLanguage(AIDL)
interface.ThefinalchapterwillprovidedetailedexamplesofAIDLinpracticeforour
customSEforAndroidsystem,butinthemeantime,thefollowingisasimpleexampleof
anAIDLinterfaceprovidingthemeansforremoteprocessestoexecutethe
getAccountName()andputAccountName()functions:
packagecom.example.sample;
interfaceIRemoteInterface{
StringgetAccountName();
www.it-ebooks.info
booleanputAccountName(inStringname);
}
ThebeautyinworkingwithanAIDLinterfaceisthatitisusedtogenerateasignificant
amountofcodetomanagedataandprocessesthatwouldotherwisehavetobedoneby
hand.Forexample,thefollowingisonlyasmallportionofthecodegeneratedfromthe
precedingAIDLsample:
@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
Binderandsecurity
Thesecurityimplicationsofbinderarequitelarge.Youshouldbeabletocontrolwho
becomesthecontextmanager,asaroguecontextmanagercouldcompromisethewhole
systembysendingclientstorogueservices,ratherthantheproperones.Outsideofthat,
youmightwanttocontrolwhichclientscanbindtowhichbinderobjects.Lastly,you
mightwishtocontrolwhetherfiledescriptorscanbesentviabinder.Thebinderalsohas
thecapabilitytoallowsomeonetofakecredentialsovertheinterface,whichisdesignedto
beusedforgood.Forexample,someprivilegedsystemprocesses,suchasActivity
ManagerService(AMS),performoperationsonbehalfofotherprocesses.The
credentialsexposedinthiskindofmasqueradingareoftheprocessyouaredoingthework
for,notoftheprivilegedentity.Thisisanalogoustoapowerofattorney,usedwhen
someoneisactingonyourbehalf.
Android’sbinderIPCmechanismwastraditionallycontrolledwithDACpermissions.
However,aswesawinChapter1,LinuxAccessControls,thesepermissionshavesome
flaws.ItfollowsthatbinderneedstobemodifiedtosupportSELinuxbecausethebinder
driverdoesnototherwiseimplementhookstoanyadditionalsecuritymodules.Todothis,
apatchwassenttoGooglebyStephenSmalleyimplementingthesefeatures.Thepatch
implementsnewhooksforconsumersofwhatisknownastheLinuxSecurityModule
(LSM)framework.ThisframeworkallowsLSMssuchasSELinuxtobeinvokedandthen
makeaccessdecisions.Thedetailsofthispatchareoutsidethescopeofthisbook.It
sufficesthatbinderwaspatched,andSELinuxcannowcontrolitscapabilitieswithMAC.
Note
StephenSmalleyisacomputersecurityresearcherattheTrustedSystemsResearch
organizationoftheUnitedStatesNationalSecurityAgency(NSA)andleadstheSE
Androidproject.ThepatchhesenttoGoogletomodifythebinderforSELinuxhookscan
beviewedathttps://android-review.googlesource.com/45984.
BecauseoftheintegrationofSELinuxandbinder,SEforAndroidhasanadditionalclass
withaccessvectors(afancywayofsaying,“thingsitcando.”)Inpreviousexamplesfrom
Chapter2,MandatoryAccessControlsandSELinux,thetargetclassisfood.Similarly,the
SELinuxclassforbinderisbinder.Itdefinestheaccessvectorslistedinthefollowing
bullets.Ifyourecall,theaccessvectorforfoodinChapter2,MandatoryAccessControls
andSELinux,waseat.Thefollowingaccessvectorsareavailableforbinder:
impersonate:Thiscreatesfakecredentialsoverabinderinterface
call:Thisbindsaclienttoabinderinterfaceandusesit
set_context_mgr:Thissetsthecontextmanager
transfer:Thistransfersafiledescriptor
www.it-ebooks.info
www.it-ebooks.info
Zygote–applicationspawn
Non-nativeapplicationsinAndroidhistoricallymakeuseoftheDalvikvirtualmachine
(VM)andrunaproprietarybytecodecalledDEX.Applicationsarealsospawnedfroma
commonprocesscalledzygotethroughamechanismcalledforkandspecialize.Zygote
itselfisaprocessthathastheDalvikVMandsomecommonclasses,suchas
java.util.*,loadedintotheVM.Forkandspecializeisthemechanismofgoingfroma
zygotetoachildprocessofzygotethatexecutessomeapplicationcode.
Note
VersionsofAndroidsinceAndroid4.4arereplacingthiswiththeAndroidRunTime
(ART).ItisspeculatedthatAndroidLwillnotusetheDalvikVMatall.
Thefirstpartofthisprocessinvolvesasocketconnection.Zygotelistensoverthissocket
foranapplication’sspawnrequests.Someoftheargumentsincludethepackagenameof
theapplicationthatshouldbeloadedandaflagthatindicateswhethertheapplicationis
thesystemserverornot.Oncethespawncommandisreceived,theforkcanproceed.
Note
Agreatwaytostarttracingbackthisinitialsocketconnectioniswiththeapp_process
tool.ThiscommandstartsaprocesswithDalvik.Formoreinformation,navigateto
frameworks/base/cmds/app_process/app_main.cpp.
Afterthefork,thenowparentzygotereturnstolistenonthesocketformorerequests.The
childprocessisexecutingandafewthingsneedtohappen.Thefirstthingthatneedsto
happenisaUIDandGIDswitch.ZygoterunswiththeUIDroot,andthustomeetthe
Androidsecuritymodel,itmustsetthechildprocessUIDsandGIDstosomethingother
thanroot.ThechildprocesswillsetUIDandGIDasdefinedbythepackagemanagerand
thesupplementaryGIDs.Italsosetstheprocess’resourcelimitsandschedulingpolicy.
Thenitclearsthecapabilitysetoftheapplicationtozero(nocapabilities).Inthecaseof
thesystemserver,thecapabilitysetisnotclearedbutrathersetasoneofthearguments
sentoverthesocket.Afterthispoint,thechildprocessruns.Codefurtheralonginthe
zygoteloadstheclass,andothersysteminteractions,suchasintentdelivery,areusedto
startanactivity.Thesepartsofzygotearebeyondthescopeofthisbook.
www.it-ebooks.info
www.it-ebooks.info
Thepropertyservice
ThepropertyserviceinAndroidprovidesasharedmappingofkey-valuepairsbetweenall
processes.AllprocessesonanAndroidsystemsharesomepagesofmemorydedicatedto
thissystem.However,themappinginallprocessesisREADONLYwiththeexceptionofinit
processes,whichhaveaREAD/WRITEmapping.Thepropertyservicesystemresideswithin
init,anditisthissystem’sjobtoupdateoraddvaluestothiskey-valuemap.Inorderto
changeavalue,youmustgothroughpropertyservice,butanyonecanreadavalue.It’s
imperativethatifyouusepropertyservice,youdonotstoresensitiveinformation.Itis
primarilyintendedtobeusedforsmallvalues,notagenericlarge-valuestore.What
followsisonlyaverybasicintroductiontothepropertyservice.Athoroughinvestigation
willbeconductedlater.
Tosetaproperty,youmustsendarequestusingaUnixdomainsockettotheproperty
service.Propertyservicewillthenparsetherequestandsetthevalueifthepermissions
allowittodoso.Propertieshaveperiod-delimitedsegments,likepackagenames,that
havepermissionsassignedtoitstaticallyatbuildtime.Thepermissionsandproperty
servicecodecanbefoundtogetheratsystem/core/property_service.c.Thearguments
expectedoverthisinterfaceincludeacommand,thepropertyname,andtheproperty
value.Forthosewhoarecurious,thesearealldefinedinthestructureprop_msg,whichis
definedinbionic/libc/include/sys/_system_properties.h.Uponreceivingthe
message,thepropertyservicechecksthepeersocket’scredentialsagainstthestaticmapof
permissions.IftheUIDisroot,itcanwritetoanything,otherwiseitmustbeamatchfor
eitherUIDorGID.InverynewAndroidversions,orthosewiththepatchappliedfrom
https://android-review.googlesource.com/#/c/98428/,boththepermissioncheckingand
hardcodedDAChavebeenreplacedbySELinuxcontrols.
SincethepermissiontosetavalueiscontrolledbyuserspaceusingDAC,itfollowsthat
thepropertysetmechanismssharetheinherentrootingvulnerabilityflaw.Withthisin
mind,thepropertyservicecodewasaugmentedinSELinux.Sincethisisauserspace
process,itusestheSELinuxAPIthroughthekerneltoprogramsomethingcalledauser
spaceobjectmanager.ThisjustmeanstheuserspaceapplicationcheckswithSELinuxin
thekerneltoensureitcanperformanactivity…inthiscase,setonaproperty.
www.it-ebooks.info
www.it-ebooks.info
Summary
Androidhassomeveryuniqueproperties.FromitsuseofthecommonUIDandGID
modeltopromoteitssecuritygoals,toitscustombinderIPCmechanism,thesesystems
haveimplicationsonthesecurityandfunctionalityofthedevice.Inthenextchapter,these
systemswillcomebackintoplayaswegettheUDOOupandrunningandenableSEfor
Androidonit.
www.it-ebooks.info
www.it-ebooks.info
Chapter4.InstallationontheUDOO
Inordertocontinueourexploration,wewillneedtogetatangiblesysteminplacetowork
with.Inthischapter,wewill:
BuildAndroid4.3fortheUDOOfromsource
FlashanSDcardwithourbootimages
GettheUDOOrunningwhilecapturinglogs
EstablishanadbconnectiontotheUDOO
RebuildthekernelwithSELinuxsupport
VerifyourSELinuxUDOOimageworksasexpected
WewillstartwiththepubliclyavailableUDOOAndroid4.3JellyBeansourcecode,
whichcanbedownloadedfromhttp://www.udoo.org/downloads/.Itisassumedyouhavea
UDOOandhaveverifiedthatitisfunctional.Itisrecommendedyoufollowthe
instructionsontheUDOOwebsiteforgettingstartedwiththeAndroid4.3prebuiltimage
asaninitialtest(formoreinformation,refertohttp://www.udoo.org/getting-started/).
YouwillalsoneedanappropriatedevelopmentsystemforworkingwithAndroidanda
UDOO,butthedetailsofthisarebeyondthescopeofthischapter.Anappendixhasbeen
provideddetailingthesetupofastandardUbuntuLinux12.04systemtoensureyouhave
thehighestprobabilityofsuccessduplicatingtheworkinthisbook.
www.it-ebooks.info
Retrievingthesource
Let’sstartthisexercisebydownloadingtheAndroid4.3Jellybeansourcecodefromthe
downloadlinksgivenintheprecedingsection,andextractthedownloadintoaworkspace
usingthefollowingcommands:
$mkdir~/udoo&&cd~/udoo
$tar-xavf~/Downloads/UDOO_Android_4.3_Source_v2.0.tar.gz
Oncethisisdone,youshouldreviewtheUDOOdocumentationandtheAndroidsource
codebuildinginstructionsatthefollowingURLs:
http://www.elinux.org/UDOO_compile_android_4-2-2_from_sources
http://source.android.com/source/initializing.html
TheinstructionsprovidedbytheprecedingURLdiscusshowtobuildAndroidwithOpen
JDK7.However,theseinstructionsareforthecurrentreleaseofAndroid(Lpreview)and
arenot100percentrelevant.ForAndroid4.3,youmustbuildwithOracleJava6,whichis
archivedbyOracleandfoundat
http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archivedownloads-javase6-419409.html.
ItisassumedthatyouhaveaduplicateofthesystemdetailedintheAppendix,The
DevelopmentEnvironment.Thatappendix,amongotherthings,walksyouthroughthe
setupofOracleJava6asyouronlyJavainstance.However,forthosewhoprefertowork
fromtheirexistingsystems,particularlythosewithmultipleJavaSDKs,pleasekeepin
mindyouwillneedtoensureyoursystemisusingtheOracleJava6toolswhenworking
throughtherestofthisbook.
FinishsettingupyourenvironmentbychangingtotherootofyourUDOOsourcetreeand
executethefollowingcommand:
$.setupudoo-eng
Oncetheenvironmentisconfigured,weneedtobuildthebootloader:
$cdbootable/bootloader/uboot-imx
$./compile.sh-c
Agraphicalmenuwillappear.Ensurethesettingsareasfollows:
DDRSize:Select1Giga,bussize64,andactiveCS\1(256Mx4)
BoardType:SelectUDOO
CPUtype:Selectquad-coreordual-coreoption,dependentonwhichsystemyou
have.Wehappentobeusingthequad-coresystem.
OStype:SelectAndroid
Environmentdevice:MustselectSD/MMC
Extraoptions:CLEANshouldbeselected
Compileroptions: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-eabiobjcopy-Osrecu-bootu-boot.srec
/home/bookuser/udoo/prebuilts/gcc/linux-x86/arm/arm-eabi-4.6/bin/arm-eabiobjcopy--gap-fill=0xff-Obinaryu-bootu-boot.bin
Justtobesafe,verifyyourbuildwassuccessfulbyusinglsu-boot.bintoensurethe
bootloaderimagenowexists.Now,buildAndroidusingthefollowingcommand:
$croot
$make–j42>&1|teelogz
ThefirstcommandissomethingthatwassourcedinthesetupscriptsforAndroidand
takesusbacktotherootofourprojecttree.Thesecondcommand,make,buildsthe
system.YoushouldsettheoptionforjtotwiceyourCPU/corecountinmostcases.
Becausemanyofyoumighthaveadual-coremachine,we’lluse–j4.Oneoftheauthors
ofthisbookuses8CPUcores,forexample,andusestheflag-j16.Thefileredirection
andteecommandscapturethebuildoutputtoafile.Thisisimportanttohelpanddebug
anybuildissues.Thisbuild,dependingonyoursystemcantakealong,longtime.Onthe
previouslymentioned8-coresystemwith16GBRAM,thistookalittleover35minutes.
Onothersystems,we’veexperiencedbuildtimesover3hours.
Inthiscase,capturingthelogsprovedveryuseful.Thebuildterminatedwithanerror,and
bysearchingthelogsforerror,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.We
canalsoopentheAndroidmakefile,external/mtd-utils/mkfs.ubifs/Android.mk,and
determinethelikelylibrariesinvolvedfromthelineLOCAL_LDLIBS:=-lz-llzo2-lmluuid-m64.SearchingrevealsthespecificUbuntupackagewe’remissing;wewillinstall
themandbuildagain.The$characterattheendofthesearchstringensuresweonlyget
resultsendinginuuid/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
www.it-ebooks.info
FlashingimageonanSDcard
Withthebootloader,Androiduserspace,andLinuxkernelbuilt,it’stimetoinsertanSD
cardandflashtheimages.InsertanSDcardintoyourhostcomputer,andensureit’s
unmounted.InUbuntu,removablemediaaremountedautomatically,soyou’llneedto
findthe/dev/sd*devicethatisyourflashdrive,andumountit.Fortheremainderofthe
text,wewilluse/dev/sddastheflashdrive,butitisimportanttousethecorrectdevice
foryoursystem.IfyouhaveusedthisSDcardforinstallingUDOObefore,thecardwill
containmultiplepartitions,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
Tip
Youmustusethe-Eparameteronsudotopreservealltheexportedvariablesfromthe
Androidbuild.YoumustbeinthesameterminalsessionyoubuiltAndroidin.Otherwise
youwillseetheerrorNoOUTexportvariablefound!Setupnotcalledin
advance….
Oncethiscompletes(itwilltakeawhile),it’simportanttoflushtheblockdevicecaches
backtothediskwiththecommand,sudosync.Then,youcanremovetheSDcard,insert
itintotheUDOO,andboot!
www.it-ebooks.info
www.it-ebooks.info
UDOOserialandAndroidDebugBridge
NowthattheUDOOisbootingintoAndroid,wewanttomakesurewecanaccessitusing
theserialportaswellastheAndroidDebugBridge(adb).You’llneedtheUDOOserial
driversappropriateforyoursystem.ThedetailsofthisforMac,Linux,andWindowscan
befoundat
http://www.udoo.org/ProjectsAndTutorials/connecting-via-serial-cable/.
Theserialportisthefirstformofcommunicationthatwillcomefromthesystem,anditis
initializedbythebootloader.Itisacriticallinkfordebugginganykernelorsystem
issuesthatyouencounterlateron.It’salsorequiredinordertoconfiguretheUSBportto
allowadbconnectionsacrossCN3(theUSBOTGportontheUDOO).Toconfigurethe
port,weneedtoconfigureanduseminicomtoconnectashelltothedevice.Startby
pluggingamicroUSBcablefromCN6(themicroUSBportclosesttothepowerbutton)
tothehostmachine.Next,let’sfindtheserialconnectionbylookingthroughdmesgforthe
connectionmessageofaTTYoverUSB.
$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,andtypefto
togglethehardwareflowcontroloff:
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,byremovingandreplacing
theJ16jumper.NowpluginamicroUSBcablefromthehosttoCN3.Youshouldnow
seeaUSBdeviceaswellasadb:
$lsusb
Bus001Device009:ID18d1:4e42GoogleInc.
$adbdevices
Listofdevicesattached
0123456789ABCDEFoffline
YouneedtoselectAllowUSBdebuggingwhenthepromptappearsontheUDOO
Androidside.Whenyoudothis,thedeviceshouldgofromofflinetoonline;thiswayyou
canuseadb.
Nowtesttheconnectionandgrabthescreenshotoveradb:
$adbshell
root@udoo:/#
$adbshellscreencap-p|perl-pe's/\x0D\x0A/\x0A/g'>screen.png
Thisisthescreenshot:
Atthispoint,wehaveaworkingdevelopmentsystem.Wehaveearlybootlogsanda
rescueshellthroughtheserialconsole.Wealsohaveanadbbridgewithwhichwecanuse
thestandardAndroiddebuggingtools!There’snothinglefttodobutgetthissystem
www.it-ebooks.info
securedwithSELinux!
www.it-ebooks.info
www.it-ebooks.info
Flippingtheswitch
NowthatweareenablingSELinuxontheUDOO,weneedtoverifyitisn’tturnedon.The
waytodothisistochecktheknownfilesystemtypesinthe/procfilesystem.SELinux
hasitsownpsuedo-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,andeventuallyyouwillbe
greetedwithagraphicaleditingscreen:
$makemenuconfig
First,youwillneedtoenableAuditingsupport,asthisisadependencyofSELinux.
UnderGeneralsetup|AuditingSupport,enableAuditSupportandEnablesystemcallauditing.Usetheupanddownarrowkeystohighlightanentry,andpressthe
spacebartoenableit.Whenanitemisenabled,youwillseeanasterisk(*)nexttoit:
www.it-ebooks.info
GobacktothemainmenubyselectingExit…it’snotveryintuitive.EntertheFile
systemsmenu,andforeachofthethreefilesystems,Ext2,Ext3,andExt4,ensurethat
ExtendedattributesandSecurityLabelsareenabled.Then,gobacktothemainmenu
byselectingExit:
Fromthatscreen,exitbacktothemainmenuandgotoSecurityOptions.Onceinthe
SecurityOptionssubmenu,enabletheEnabledifferentsecuritymodelsandSocketand
NetworkingSecurityHooksoptions:
www.it-ebooks.info
Oncetheseareenabled,moreoptionswillappear.EnableNSASELinuxSupportand
ensuretheotherselectionsandvaluesfromthefollowingscreenshotareduplicated:
Finally,setDefaultsecuritymoduletoSELinux:
OnceyouselectDefaultsecuritymodule,anewwindowwillappearfromwhichyoucan
selectSELinux.ExittheconfigurationmenusbyselectingExituntilyouareaskedto
saveyournewconfiguration:
Savethenewconfigurationandwritethesechangestotheoriginatingkernelconfiguration
file.Otherwise,itwillbeoverwrittenonsubsequentbuilds.Todothis,we’llneedto
discoverwhichconfigurationfilewasusedinthedefaultbuild,whichwebuiltearlier
beforewemadeourownconfigurationwithmakemenuconfig:
$grepdefconfiglogzmake-Ckernel_imximx6_udoo_android_defconfig
www.it-ebooks.info
ARCH=armCROSS_COMPILE=`pwd`/prebuilts/gcc/linux-x86/arm/arm-eabi4.6/bin/arm-eabi-
Youcanseethatimx6_udoo_android_defconfigwasusedasthedefaultconfiguration.
Copyyourcustomconfigurationandbuildagain:
$cp.configarch/arm/configs/imx6_udoo_android_defconfig
$croot
$make–j4bootimage2>&1|teelogz
AquicksanitycheckofthelogfileisalwaysagoodideatoverifySELinuxwasactually
builtintothekernel:
$grep-iselinuxlogz
HOSTCCscripts/selinux/mdp/mdp
HOSTCCscripts/selinux/genheaders/genheaders
GENsecurity/selinux/flask.hsecurity/selinux/av_permissions.h
CCsecurity/selinux/avc.o
...
Now,withabuiltkernelsupportingSELinux,inserttheSDcardintothehostandrunthe
followingcommands:
$sudo-E./make_sd.sh/dev/sdd
$sudosync
Tip
Don’tforgettoumountanyautomountedpartitionsfromtheSDcardaswedidbefore.
PlugtheSDcardintotheUDOO,andfireitup.Youshouldseelogsovertheserial
consoleaswedidbefore:
Eventually,theserialconnectionshouldtakeustoarootshell.
www.it-ebooks.info
www.it-ebooks.info
It’salive
HowdoweknowthatwehavesuccessfullyenabledSELinuxinthekernel?Earlierinthis
chapter,youranthecommand,adbshellcat/proc/filesystems.We’regoingtodo
thesamethingandlookforanewfilesystemcalledselinuxfs.Ifthatispresent,it
indicateswehaveenabledSELinuxsuccessfully.Runthefollowingcommandintheserial
terminal:
#cat/proc/filesystems|grepselinux
nodevselinuxfs
Wecanseethatselinuxfsispresent!Anothercommonpracticeistocheckdmesgforany
SELinuxoutput.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
www.it-ebooks.info
Summary
Thiswasaveryexcitingchapter.YoulearnedhowtoenableSELinuxinthekernel
configuration,bootthe“secured”system,andhowtoverifyitspresence.Wealsolearned
howtoflashandbuildimagesfortheUDOOingeneralandhowtoconnecttoitviaserial
andadbconnections.Inthenextchapters,wewillfocusonhowtomaketheUDOO
usablewithSEforAndroidcapabilities.
www.it-ebooks.info
www.it-ebooks.info
Chapter5.BootingtheSystem
NowthatwehaveanSEforAndroidsystem,weneedtoseehowwecanmakeuseofit,
andgetitintoausablestate.Inthischapter,wewill:
Modifythelogleveltogainmoredetailswhiledebugging
Followthebootprocessrelativetothepolicyloader
InvestigateSELinuxAPIsandSELinuxFS
Correctissueswiththemaximumpolicyversionnumber
ApplypatchestoloadandverifyanNSApolicy
YoumighthavenoticedsomedisturbingerrormessagesdmesginChapter4,Installation
ontheUDOO.Torefreshyourmemory,herearesomeofthem:
#dmesg|grep–iselinux
<6>SELinux:Initializing.
<7>SELinux:Startinginpermissivemode
<7>SELinux:Registeringnetfilterhooks
<3>SELinux:policydbversion26doesnotmatchmyversionrange15-23
...
ItwouldappearthateventhoughSELinuxisenabled,wedon’tquitehaveanerror-free
system.Atthispoint,weneedtounderstandwhatcausesthiserror,andwhatwecandoto
rectifyit.Attheendofthischapter,weshouldbeabletoidentifythebootprocessofan
SEforAndroiddevicewithrespecttopolicyloading,andhowthatpolicyisloadedinto
thekernel.Wewillthenaddressthepolicyversionerror.
www.it-ebooks.info
Policyload
AnAndroiddevicefollowsabootsequencesimilartothatofthe*NIXbootingsequence.
Thebootloaderbootsthekernel,andthekernelfinallyexecutestheinitprocess.Theinit
processisresponsibleformanagingthebootprocessofthedevicethroughinitscriptsand
somehardcodedlogicinthedaemon.Likeallprocesses,inithasanentrypointatthe
mainfunction.Thisiswherethefirstuserspaceprocessbegins.Thecodecanbefoundby
navigatingtosystem/core/init/init.c.
Whentheinitprocessentersmain(refertothefollowingcodeexcerpt),itprocesses
cmdline,mountssometmpfsfilesystemssuchas/dev,andsomepseudo-filesystems
suchasprocfs.ForSEforAndroiddevices,initwasmodifiedtoloadthepolicyintothe
kernelasearlyinthebootprocessaspossible.ThepolicyinanSELinuxsystemisnot
builtintothekernel;itresidesinaseparatefile.InAndroid,theonlyfilesystemmounted
inearlybootistherootfilesystem,aramdiskbuiltintoboot.img.Thepolicycanbefound
inthisrootfilesystemat/sepolicyontheUDOOortargetdevice.Atthispoint,theinit
processcallsafunctiontoloadthepolicyfromthediskandsendsittothekernel,as
follows:
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:Disableddue
tofailedpolicyload,andwonderwhywedidn’tseethiswhenwerandmesgbefore.
Thiscodeexecutesbeforesetlevelininit.rcisexecuted.
ThedefaultinitloglevelissetbythedefinitionofKLOG_DEFAULT_LEVELin
system/core/include/cutils/klog.h.Ifwereallywantedto,wecouldchangethat,
rebuild,andactuallyseethatmessage.
Nowthatwehaveidentifiedtheinitialpathofthepolicyload,let’sfollowitonitscourse
www.it-ebooks.info
throughthesystem.Theselinux_android_load_policy()functioncanbefoundinthe
Androidforkoflibselinux,whichisintheUDOOAndroidsourcetree.Thelibrarycan
befoundatexternal/libselinux,andalloftheAndroidmodificationscanbefoundin
src/android.c.
Thefunctionstartsbymountingapseudo-filesystemcalledSELinuxFS.Ifyourecall,this
wasoneofthenewfilesystemsmentionedin/proc/filesystemsthatwesawinChapter
4,InstallationontheUDOO.Insystemsthatdonothavesysfsmounted,themountpoint
is/selinux;onsystemsthathavesysfsmounted,themountpointis/sys/fs/selinux.
Youcancheckmountpointsonarunningsystemusingthefollowingcommand:
#mount|grepselinuxfs
selinuxfs/sys/fs/selinuxselinuxfsrw,relatime00
SELinuxFSisanimportantfilesystemasitprovidestheinterfacebetweenthekerneland
userspaceforcontrollingandmanipulatingSELinux.Assuch,ithastobemountedforthe
policyloadtowork.Thepolicyloadusesthefilesystemtosendthepolicyfilebytestothe
kernel.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)functionchangesaglobalvariableinlibselinuxsothat
otherroutinescanfindthelocationofthisvitalinterface.Fromthereitcallsanotherhelper
www.it-ebooks.info
function,selinux_android_reload_policy(),whichislocatedinthesamelibselinux
android.cfile.Itloopsthroughanarrayofpossiblepolicylocationsinpriorityorder.
Thisarrayisdefinedasfollows:
Staticconstchar*constsepolicy_file[]={
"/data/security/current/sepolicy",
"/sepolicy",
0};
Sinceonlytherootfilesystemismounted,itchooses/sepolicyatthistime.Theother
pathisfordynamicruntimereloadsofpolicy.Afteracquiringavalidfiledescriptortothe
policyfile,thesystemismemorymappedintoitsaddressspace,andcalls
security_load_policy(map,size)toloadittothekernel.Thisfunctionisdefinedin
load_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,thepolicyiswrittentothekernelviathispseudo
file:
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
www.it-ebooks.info
Fixingthepolicyversion
Atthispoint,wehaveaclearideaofhowthepolicyisloadedintothekernel.Thisisvery
important.SELinuxintegrationwithAndroidbeganinAndroid4.0,sowhenportingto
variousforksandfragments,thisbreaks,andcodeisoftenmissing.Understandingall
partsofthesystem,howevercursory,willhelpustocorrectissuesastheyappearinthe
wildanddevelop.Thisinformationisalsousefultounderstandthesystemasawhole,so
whenmodificationsneedtobemade,you’llknowwheretolookandhowthingswork.At
thispoint,we’rereadytocorrectthepolicyversions.
Thelogsandkernelconfigareclear;onlypolicyversionsupto23aresupported,and
we’retryingtoloadpolicyversion26.Thiswillprobablybeacommonproblemwith
Androidconsideringkernelsareoftenoutofdate.
Thereisalsoanissuewiththe4.3sepolicyshippedbyGoogle.SomechangesbyGoogle
madeitabitmoredifficulttoconfiguredevicesastheytailoredthepolicytomeettheir
releasegoals.Essentially,thepolicyallowsnearlyeverythingandthereforegeneratesvery
fewdeniallogs.Somedomainsinthepolicyarecompletelypermissiveviaaper-domain
permissivestatement,andthosedomainsalsohaverulestoalloweverythingsodeniallogs
donotgetgenerated.Tocorrectthis,wecanuseamorecompletepolicyfromtheNSA.
Replaceexternal/sepolicywiththedownloadfrom
https://bitbucket.org/seandroid/external-sepolicy/get/seandroid-4.3.tar.bz2.
AfterweextracttheNSA’spolicy,weneedtocorrectthepolicyversion.Thepolicyis
locatedinexternal/sepolicyandiscompiledwithatoolcalledcheck_policy.The
Android.mkfileforsepolicywillhavetopassthisversionnumbertothecompiler,sowe
canadjustthishere.Onthetopofthefile,wefindtheculprit:
...
#Mustbe<=/selinux/policyversreportedbytheAndroidkernel.
#Mustbewithinthecompatibilityrangereportedbycheckpolicy-V.
POLICYVERS?=26
...
Sincethevariableisoverridablebythe?=assignment.Wecanoverridethisin
BoardConfig.mk.Editdevice/fsl/imx6/BoardConfigCommon.mk,addingthefollowing
POLICYVERSlinetothebottomofthefile:
...
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.
Tip
Thefirstoftheprecedingcommandsshouldproducethefollowinglogoutput:
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.Thegetenforcecommandgetsthe
SELinuxenforcingstatus.Itcanbeinoneofthreestates:
Disabled:Nopolicyisloadedorthereisnokernelsupport
Permissive:Policyisloadedandthedevicelogsdenials(butisnotinenforcing
mode)
Enforcing:Thisstateissimilartothepermissivestateexceptthatpolicyviolations
resultinEACCESSbeingreturnedtouserspace
OneofthegoalswhilebootinganSELinuxsystemistogettotheenforcingstate.
Permissiveisusedfordebugging,asfollows:
#getenforce
Permissive
www.it-ebooks.info
www.it-ebooks.info
Summary
Inthischapter,wecoveredtheimportantpolicyloadflowthroughtheinitprocess.We
alsochangedthepolicyversiontosuitourdevelopmenteffortsandkernelversion.From
there,wewereabletoloadtheNSApolicyandverifythatthesystemloadedit.This
chapteradditionallyshowcasedsomeoftheSELinuxAPIsandtheirinteractionswith
SELinuxFS.Inthenextchapter,wewillexaminethefilesystemandthenmoveforwardin
ourquesttogetthesystemintoenforcingmode.
www.it-ebooks.info
www.it-ebooks.info
Chapter6.ExploringSELinuxFS
Inthelastfewchapters,wesawSELinuxFSsurfaceonnumerousoccasions.Fromits
entryin/proc/filesystemstothepolicyloadintheinitdaemon,itseesfrequentusein
anSELinux-enabledsystem.SELinuxFSisthekernel-to-userspaceinterfaceandthe
foundationonwhichhigheruserspaceidiomsandlibselinuxarebuilt.Inthischapter,we
willexplorethecapabilitiesofthisfilesystemforadeeperunderstandingofhowthe
systemworks.Specifically,wewill:
DeterminehowtofindthemountpointoftheSELinuxfilesystem
ExtractstatusinformationaboutourcurrentSELinuxsystem
ModifyourSELinuxsystemstatusontheflyfromtheshellandthroughcode
InvestigateProcFSinterfaces
www.it-ebooks.info
Locatingthefilesystem
Thefirstthingweneedtodoislocatethemountpointforthefilesystem.libselinux
mountsthefilesystemineitheroftwoplaces:/selinux(bydefault)or/sys/fs/selinux.
However,thisisnotastrictrequirementandcanbealteredwithacalltovoid
set_selinuxmnt(char*mnt),whichsetstheSELinuxmountpointlocation.However,
thisshouldhappenandshouldnotneedanyadjustmentinmostcircumstances.
Thebestwaytofindthemountpointinthesystemisbyrunningthemountcommandand
findingthelocationofthefilesystem.Fromtheserialconsole,issuethefollowing
commands:
root@udoo:/#mount|grepselinux
selinuxfs/sys/fs/selinuxselinuxfsrw,relatime00
Asyoucansee,themountpointis/sys/fs/selinux.Let’sgotothatdirectorybyissuing
thefollowingcommandattheserialterminalprompt:
root@udoo:/#cd/sys/fs/selinux
root@udoo:/sys/fs/selinux#
YouarenowintherootoftheSELinuxfilesystem.
www.it-ebooks.info
www.it-ebooks.info
Interrogatingthefilesystem
YoucaninterrogateSELinuxFStofindoutwhatthekernel’shighestsupportedpolicy
versionis.Thisisusefulwhenyoubegintoworkwithsystemsyoudidnotbuildfrom
source.ItisalsousefulwhenyoudonothavedirectaccesstotheKConfigfile.Itis
importanttonotethatbothDACandMACpermissionsapplytothisfilesystem.With
respecttoMACandSELinux,theaccessvectorsforthisareenumeratedinclasssecurity
inthepolicyfilelocatedatexternal/sepolicy/access_vectors:
root@udoo:/sys/fs/selinux#echo'catpolicyvers'
23
Tip
Inthepreviouscommand,andinseveralcommandstofollow,wedonotjustprintthe
fileswiththecatcommand.Thisisbecausethesefilesdonothaveatrailingnewlineat
theendofthefile.Withoutthenewline,thecommandpromptfollowingthecommand’s
executionwouldbeattheendofthelastlineoftheoutput.Wrappingthecatcommand
withechoguaranteesanewline.Analternatewaytogetthesameeffectisbyusingcat
policyvers;echo.
Asweexpected,thesupportedversionis23.Asyourecall,wesetthisvalueinChapter4,
InstallationontheUDOOwhileconfiguringthekerneltoenableSELinuxusingmake
menuconfigfromthekernel_imxdirectory.Thisisalsoaccessiblebythelibselinux
API:
intsecurity_policyvers(void);
Itshouldnotrequireanyelevatedpermissionsandisreadablebyanyoneonthesystem.
www.it-ebooks.info
Theenforcenode
Inpreviouschapters,wediscussedthatSELinuxoperatesintwomodes,enforcingand
permissive.Bothmodeslogpolicyviolations,however,enforcingmodecausesthekernel
todenyaccesstotheresourceandreturnanerrortothecallinguserspaceprocess(for
example,EACCESS).SELinuxFShasaninterfacetoquerythisstatus—thefilenode
enforce.Readingfromthisfilereturnsthestatus0or1dependingonwhetherweare
runninginpermissiveorenforcingmode,respectively:
root@udoo:/sys/fs/selinux#echo'catenforce'
0
Asyoucansee,oursystemisinpermissivemode.Androidhasatoolboxcommandfor
printingthisaswell.ThiscommandreturnsthestatusPermissiveorEnforcing
dependingonwhetherwearerunninginapermissiveorenforcingmode,respectively:
root@udoo:/sys/fs/selinux#getenforce
Permissive
Youcanalsowritetotheenforcefile.TheDACpermissionsforthisfilesystemare:
Owner:rootread,write
Group:rootread
Others:read
Anyonecangettheenforcingstatus,buttosetit,youmustbetherootuser.TheMAC
permissionrequiredforthisis:
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.Thefunctionin
libselinuxtodothisisintsecurity_setenforce(intvalue).Anotherinteresting
artifactoftheprecedingcommandiswecanseeprocfswasaccessed.SELinuxhassome
additionalentriesinprocfsaswell.Thosewillbecoveredfurtherinthischapter.
www.it-ebooks.info
Thedisablefileinterface
SELinuxcanalsobedisabledatruntimeusingthedisablefileinterface.However,the
kernelmustbebuiltwithCONFIG_SECURITY_SELINUX_DISABLE=y.Ourkernelwasnotbuilt
withthisoption.ThisfileiswriteonlybyownerandhasnospecificMACpermission
associatedwithit.Werecommendkeepingthisoptiondisabled.Additionally,SELinux
canbedisabledbeforeapolicyisloaded.Evenwhentheoptionisenabled,onceapolicy
isloaded,itisdisabled.
www.it-ebooks.info
Thepolicyfile
ThepolicyfileletsyoureadthecurrentSELinuxpolicyfilethatwasloadedintothe
kernel.Thiscanbereadandsavedtodisk:
root@udoo:/sys/fs/selinux#catpolicy>/sdcard/policy
Byenablingtheadbinterface,youcannowextractitfromthedeviceandanalyzeitonthe
hostwiththestandardSELinuxtools.TheDACpermissionsonthisfileareowner:root,
read.ThereisnoSELinuxpermissionspecifictothisfile.
Theinversetothepolicyfileistheloadfile.Wehaveseenthisfileappearwhenthe
policyfileisloadedbyinitusingthelibselinuxAPI:
intsecurity_load_policy(void*data,size_tlen);
www.it-ebooks.info
Thenullfile
ThenullfileisusedbySELinuxtoredirectunauthorizedfileaccesseswhendomain
transitionsoccur.Rememberthatadomaintransitioniswhenyoutransitionfromone
contexttoanother.Inmostcases,thisoccurswhenaprogramperformsaforkandexec
function,butthiscouldhappenprogrammatically.Ineithercase,theprocesshasfile
referencesitcannolongeraccess,andtohelpkeepprocessesfromcrashing,theyjust
write/readfromtheSELinuxnulldevice.
www.it-ebooks.info
Themlsfile
Oneofthecapabilitiesoursystemhasisthatourcurrentpolicyisusingmultilevel
security(MLS)support.Thisiseither0or1,basedonwhethertheloadedpolicyfileis
usingit.Sincewehaveitenabled,wewouldexpecttosee1fromthisfile:
root@udoo:/sys/fs/selinux#echo'catmls'
1
ThemlsfileisreadablebyallandhasacorrespondingSELinuxAPI:
intis_selinux_mls_enabled(void)
www.it-ebooks.info
Thestatusfile
Theversionfileallowsamechanismbywhichyoucanbeinformedofupdatesthatoccur
withinSELinux.Onesuchexamplewouldbewhenapolicyreloadoccurs.Auserspace
objectmanagercouldcachedecisionresultsandusethereloadeventasatriggertoflush
theircache.ThestatusfileisreadonlybyeveryoneandhasnospecificMAC
permissions.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;ourintentherewasonlytocoverseveral
filesbecauseoftheirimportanceorpertinencetowhatwe’vedoneandwherewe’regoing.
Wedidnotcover:
access
checkreqprot
commit_pending_bools
context
create
deny_unknown
member
reject_unknown
relabel
Theuseofthesefilesisnotsimpleandistypicallydonebyuserspaceobjectmanagersthat
areusingthelibselinuxAPItoabstractthecomplexities.
www.it-ebooks.info
AccessVectorCache
SELinuxFSalsohassomedirectoriesyoucanexplore.Thefirstisavc.Thisstandsfor
“AccessVectorCache”andcanbeusedtogetstatisticsaboutthesecurityserverinthe
kernel:
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_stats
liststhecurrentproperties.Aswecanseeintheoutputoftheprecedingcommand,we
have512slotsinthetable,with284oftheminuse.Forcollisions,wehavethelongest
chainat7entries.ThisfileisworldreadableandrequiresnospecialMACpermissions.
Youcanmodifythenumberofentriesinthistablethroughthecache_thresholdfile.
Thecache_thresholdfileisusedtotunethenumberofentriesintheavchashtable.Itis
worldreadableandownerwriteable.ItrequirestheSELinuxpermissionsetsecparam,and
canbewrittentoandreadfromwiththefollowingsimplecommands,respectively:
root@udoo:/sys/fs/selinux/avc#echo"1024">cache_threshold
root@udoo:/sys/fs/selinux/avc#echo'catcache_threshold'
1024
Youcandisablethecachebywriting0.However,outsidethebenchmarkingtests,thisis
notencouraged.
www.it-ebooks.info
Thebooleansdirectory
Theseconddirectorytolookintoisbooleans.AnSELinuxbooleanallowspolicy
statementstochangedynamicallyviabooleanconditions.Bychangingthebooleanstate,
youcanaffectthebehavioroftheloadedpolicy.Thecurrentpolicydoesnotdefineany
booleans;sothisdirectoryisempty.Inpoliciesthatdefinebooleans,thedirectorywould
bepopulatedwithfilesnamedaftereachboolean.Youcanthenreadandwritetothese
filestochangethebooleanstate.TheAndroidtoolboxhasbeenmodifiedtoincludethe
getseboolandsetseboolcommands.ThelibselinuxAPIalsoexposesthese
capabilities:
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.Whenyouuse
security_set_boolean*,youmustcallsecurity_commit_booleans()tomakeittake
effect.UnlikeLinuxdesktopsystems,permanentbooleansarenotsupported.Changing
theruntimevaluedoesnotpersistacrossreboots.Also,onAndroid,ifyouareattempting
AndroidCompatibilityTestSuite(CTS)compliance,booleanswillcausetheteststofail.
BooleanscanhavevaryingDACpermissionsbasedonthetarget,buttheyalwaysrequire
theSELinuxpermission,setbool.
Tip
YoumustpasstheAndroidCompatabilityTestSuiteforAndroidbranding.MoreonCTS
canbefoundathttps://source.android.com/compatibility/cts-intro.html.
www.it-ebooks.info
Theclassdirectory
Thenextdirectorytolookatisclass.Theclassdirectorycontainsalltheclassesdefined
intheaccess_vectorsSELinuxpolicyfileorviatheclasskeywordintheSELinux
policylanguage.Foreachclassdefinedinthepolicy,adirectoryexistswiththesame
name.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’s
examinetheproperty_servicedirectory.Thisdirectorywaschosenbecauseitisonly
onedefinedonAndroid.However,thefilespresentineachdirectoryarethesameand
includeindexandperms:
root@udoo:/sys/fs/selinux/class/property_service#ls
index
perms
ThemappingbetweenstringandsomearbitraryintegerthatisdefinedintheSELinux
kernelmoduleisindex.Adirectorythatcontainsallthepermissionspossibleforthatclass
isperms:
root@udoo:/sys/fs/selinux/class/property_service#cdperms/
root@udoo:/sys/fs/selinux/class/property_service/perms#ls
set
Asyoucansee,thesetaccessvectorisavailablefortheproperty_serviceclass.The
classdirectorycanbeverybeneficialtoobserveapolicyfilealreadyloadedinasystem.
www.it-ebooks.info
Theinitial_contextsdirectory
Thenextdirectoryentrytopeerintoisinitial_contexts.Thisisthestaticmappingof
theinitialsecuritycontexts,betterknownassecurityidentifier(sid).Thismaptellsthe
SELinuxsystemwhichcontextshouldbeusedtostarteachkernelobject:
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_capabilitiesdirectory
Thelastdirectorytolookintoispolicy_capabilities.Thisdirectorydefinesany
additionalcapabilitiesthepolicymighthave.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
ProcFS
Wealludedtosomeoftheprocfsinterfacesthatarebeingexported.Muchofwhatis
discussedisthesecuritycontexts,sothatmeanstheshellshouldhavesomesecurity
contextassociatedwithit…buthowdoweachievethis?Sincethisisageneral
mechanismthatallLSMsuse,thesecuritycontextsarebothreadandwrittenthrough
procfs:
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,butthosefiles
aretypicallyveryrestrictedbyMACpermissions.Typically,onlytheprocessthatowns
theprocfsentrycanreadthefiles,andyoumusthavebothstandardwritepermissionsand
acombinationofsetcurrent.Notethatthe“from”and“to”domainsmustbeallowed
usingadyntransition.Toread,youmusthavegetattr.Allofthesepermissionsare
attainedfromthesecurityclass,process.ThelibselinuxAPIfunctionsgetconand
setconallowyoutomanipulatecurrent.
Theprevfilecanbeusedtofindthepreviouscontextyouswitchedfrom.Thisfileisnot
writeable:
root@udoo:/proc/self/attr#echo'catprev'
u:r:init:s0
Ourserialterminal’sformerdomainorsecuritycontextwasu:r:init:s0.
Theexecfileisusedtosetthelabelforchildrenprocesses.Thisissetbeforerunningan
exec.AllthepermissionsonthesefilesarethesamewithrespecttotheMACpermissions
usedtoactuallysetthem.Thecallerattemptingtosetthismustalsoholdsetexecfrom
theprocessclass.ThelibselinuxAPIintsetexeccon(security_context_tcontext)
andintgetexeccon(security_context_t*context)canbeusedforsettingand
retrievingthelabel.
Thefscreate,keycreate,andsockcreatefilesdosimilarthings.Whenaprocesscreates
anyoneofthecorrespondingobjects,fsobjects(files,namedpipes,orotherobjects),
keys,orsockets,thevaluessethereareused.Thecallermustalsoholdsetfscreate,
setsockcreate,andsetkeycreatefromtheprocessclass.ThefollowingSELinuxAPI
isusedtoalterthese:
intset*createcon(security_context_tcontext);
intget*createcon(security_context_t*con);
www.it-ebooks.info
Where*canbefs,key,orsocket.
It’simportanttonotethatthesespecialprocessclasspermissionsgiveyoutheabilityto
changetheproc/attrfile.YoustillneedtogetthroughtheDACpermissionsandany
SELinuxpermissionssetonthefileobjectsthemselves.Thenandonlythendoyouneed
theadditionalpermission,suchassetfscreate.
www.it-ebooks.info
www.it-ebooks.info
JavaSELinuxAPI
SimilarAPIstotheCAPIsdiscussedpreviouslyexistforJavaaswell.Inthiscase,itis
assumedyouwillbuildthecodewiththeplatform,asthesearenotpublicAPIsshipped
withtheAndroidSDK.TheAPIislocatedat
frameworks/base/core/java/android/os/SELinux.java.However,thisisaverylimited
subsetoftheAPI.
www.it-ebooks.info
www.it-ebooks.info
Summary
Inthischapter,weexploredtheinterfacebetweenthekernelanduserspacewithrespectto
SELinux,andreinforcedtheconceptsofaccessvectorclassandsecuritycontext.Inthe
nextchapter,wewillperformsomeupgradestooursystemandlookattheauditlogs
gettingonestepclosertoourultimategoal—anoperabledeviceinSELinuxenforcing
mode.Wesayoperablebecausewecanputitinenforcingmodenow.However,ifyoudo
itnowviasetenforce1onaUDOO,yourdevicewillbecomeunstable.Onoursystem,
forexample,thebrowserfailstolaunchifwedothis.
www.it-ebooks.info
www.it-ebooks.info
Chapter7.UtilizingAuditLogs
Sofarwe’veseenAVCrecordsortheSELinuxdenialmessagesshowupindmesg,but
dmesgisacircularmemorybuffer,subjecttofrequentrolloverdependentonhowverbose
yourkernelis.Byusingtheauditkernelsubsystem,wecanroutethesemessagesintouser
spaceandlogthemtodisk.Onthedesktop,thedaemonthatdoesthisiscalledauditd.A
minimalportofauditdismaintainedintheNSAbrancheshowever,ithasnotofficially
beenmergedintoAOSP.WearegoingtousetheauditdversionfromtheNSAbranches
sinceweareworkingonAndroid4.3.TheofficiallymergedversionasofApril7,2014
canbefoundathttps://android-review.googlesource.com/#/c/89645/.It’simplemented
withinlogd,andmergedathttps://android-review.googlesource.com/#/c/83526/.
Inthischapter,wewill:
Updateoursystemwiththefast-pacedSEforAndroidOpenSourceCommunity
(AOSP)
Investigatehowtheauditsubsystemworks
LearntoreadSELinuxauditlogsandstartwritingpolicy
Lookatcontextsrelativetothelogs
AllLSMsshouldlogtheirmessagesintotheauditsubsystem.Theauditsubsystemcan
thenroutethemessagestothekernelcircularbufferusingprintk,ortotheauditing
daemoninuserspace,ifoneispresent.Thekernelanduserspaceloggingdaemon
communicateusingtheAUDIT_NETLINKsocket.Wewilldissectthisinterfacefurtherinthe
chapter.
Lastly,theauditsubsystemhasthecapabilitytoprintcomprehensiverecordswhenpolicy
violationsoccur.Althoughyoudon’tneedthisfeaturetoenableandworkwithSELinux,it
canmakeyourlifeeasier.Toenablethissystem,youmustuseauditd,becauselogd
currentlydoesn’thavethissupport.You’llneedtobuildyourkernelwith
CONFIG_AUDITSYSCALL=yandplaceanaudit.rulesfilein/data/misc/audit/.Afteryou
patchyourtreewiththefollowinginstructions,readsystem/core/auditd/README.
Unfortunately,theUDOOkernelversion3.0.35doesnotsupportCONFIG_AUDITSYSCALL.
Thepatchlocatedathttps://git.kernel.org/cgit/linux/kernel/git/stable/linuxstable.git/commit/?id=29ef73b7a823b77a7cd0bdd7d7cded3fb6c2587bshouldenablethe
support.However,ontheUDOO,itcausesadeadlockwecouldnottracedown.
www.it-ebooks.info
Upgrades–patchesgalore
AlthoughAndroid4.3,releasedfromGoogle,hadSEforAndroidsupport,itisstill
limited,especiallyintheareasofauditing.Oneofthesimplestwaystobringthistoa
moreuseablestateistogetthepatchesforsomeoftheprojectsfromtheNSA’sSEfor
Android4.3branch.Here,thecommunityhasstagedanddeployedmanyofthemore
advancedfeatureswhichwerenotmergedinthe4.3timeframe.
TheNSAmaintainsrepositoriesathttps://bitbucket.org/seandroid/.Therearemany
projectssofiguringoutwhichtouseandwhatbranchcanbedaunting.Awaytofindthem
istogothrougheachprojectandfindtheprojectswithaSEAndroid-4.3branch.You
don’tneedtodescendintothedevicetreessincewe’renotbuildingAOSPdevices.The
listofsuchprojectis:
https://bitbucket.org/seandroid/system-core
https://bitbucket.org/seandroid/frameworks-base
https://bitbucket.org/seandroid/external-libselinux
https://bitbucket.org/seandroid/build
https://bitbucket.org/seandroid/frameworks-native
Wecanalsosafelyskipsepolicysincewe’vealreadyupdatedittothebleedingedge,but
thekernelsareabittrickier.Weneedthechangesfromkernel-common
(https://bitbucket.org/seandroid/kernel-common)andthebinderpatch(https://androidreview.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
Wecanstartbyfiguringouttheexactversionweneedtopatchtobylookingatthe
build/core/build_id.mkfile,andbyusingthewebpage
https://source.android.com/source/build-numbers.htmltodoalookup.
ThefileshowsBUILD_IDisJSS15J,andthelookupshowsthatweareworkingwiththe
android-4.3_r2.1releasefortheUDOO.
Foreachdownloadedprojectsofar,generatethepatchesbyrunningthecommandgit
checkoutorigin/seandroid-4.3_r2.Finally,executegitformat-patchorigin/jbmr2.0-release.Sincethereisno4.3._r2.1branch,we’reusingr2.
Foreachofthesepatches,you’llneedtoapplytheminthetreefromtheircorresponding
udoo/<project>folder.Itisimportanttoapplythepatchesforeachprojectinnumeric
orderstartingwiththe0001*patch,movingonto0002*,andsoon.Asanexampleofhow
toapplyaspecificpatchforaproject,let’slookatthefirstpatchneededforsystem-core.
NotethattheseGitrepositoriesusehyphensinplaceoftheslashesinthesourcetree;so
frameworks-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-forradio.patch
patchingfilerootdir/init.rc
Reversed(orpreviouslyapplied)patchdetected!Assume-R?[n]
Note
NotethatforUDOO,itisimportantnottoapplyapatchnumberhigherthan0005in
frameworks/base.Forotherprojects,youshouldapplyallthepatches.
Notetheerror.JusthitCtrl+Ctoquitthepatchingprocesswheneveryouseethis.The
Gittreesarenotquiteperfect,andbecauseofthis,someofthepatchesarealreadyinthe
UDOOsource.Thepatchcommandwillletusknow,andwecanskipthesebycanceling
them,whenwarned,withCtrl+C.Keepgoingthroughthepatches,cancelingtheones
alreadyapplied,andfixingupanyfailures.Afterpatchinguserspace,it’shighly
recommendedthatyoubuildtoensurenothingisbroken.
Onceuserspaceiscompletelypatched,weneedtopatchthekernel.Startbycloningthe
kernel-commonprojectfromBitbucketwiththegitclone
https://bitbucket.org/seandroid/kernel-common.gitcommand.Wewillpatchthe
kernelwiththesamemethodastherestoftheprojectswiththeexceptionofthebinder
patch.Byviewingthelinkforthebinderpatchmentioned,https://androidreview.googlesource.com/#/c/45984/,wefoundthattheGitSHAhashis
a3c9991b560cf0a8dec1622fcc0edca5d0ced936,asgiveninthePatchset4reference
fieldinthefollowingscreenshot:
WecanthengeneratethepatchforthisSHAhash:
$gitformat-patch-1a3c9991b560cf0a8dec1622fcc0edca5d0ced936
www.it-ebooks.info
0001-Add-security-hooks-to-binder-and-implement-the-hooks.patch
Then,applythatpatchwiththepatchcommandaswedidbefore.Thepatchhasafailed
hunkforaheaderfileinclusion;justfixitupliketheothersbyusingtherejectfile.When
youbuild,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.0
kernels:
structselinux_audit_datasad={0,};
ad.selinux_audit_data=&sad;
Note
Wefiguredthisoutbylookingthroughtheoriginal3.0patches,whichcanbefoundat
followinglink:
https://bitbucket.org/seandroid/kernelomap/commits/59bc19226c746f479edc2acca9a41f60669cbe82?at=seandroid-omap-tuna3.0
Asyourecall,theUDOOusesacustominit.rc.Weneedtoaddanychangestoinit.rc
totheoneUDOOactuallyuses.Allthepatchesthatcanmodifyinit.rcwillbeinthe
system-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.rcinthesepatchesandapplythemto
device/fsl/imx6/etc/init.rcusingthesamepatchtechnique.
www.it-ebooks.info
www.it-ebooks.info
Theauditsystem
Intheprevioussection,wedidalotofpatching;thepointofwhichwastoenabletheaudit
integrationworkdoneonAndroidanditsdependencies.Thesepatchesalsofixsomebugs
inthecodeand,veryimportantly,enabletheSELinux/LSMbinderhooksandpolicy
controls.
TheauditsysteminLinuxisusedbyLSMstoprintthedenialrecordsaswellastogather
verythoroughandcompleterecordsofevents.Nomatterwhat,whenanLSMprintsa
message,itgetspropagatedtotheauditsubsystemandprinted.However,iftheaudit
subsystemhasbeenenabled,thenyougetmorecontextassociatedwiththedenial.The
auditsubsystemevensupportsloadingrulesforwatchingthis.Forinstance,youcould
watchallwritesto/systemthatwerenotdonebythesystemUID.
www.it-ebooks.info
Theauditddaemon
Theauditddaemon,orservice,runsinuserspaceandlistensoveraNETLINKsocketto
theauditsubsystem.Thedaemonregistersitselftoreceivethekernelmessages,andcan
alsoloadtheauditrulesoverthissocket.Onceregistered,theauditddaemonreceivesall
theauditevents.Theauditddaemonwasminimallyported,andtherewasanattemptto
mainlineitintoAndroidthatwaslaterrejected.However,auditdhasbeenusedby
variousOEMs(suchasSamsung)andbytheNSA’s4.3branch.Analternativeapproach
thatputrecordsinlogcatwaslatermergedintoAndroid(formoreinformation,referto
https://android-review.googlesource.com/89645).
Earlier,wesawtheAVCdenialmessagesfromSELinuxindmesg.Theproblemwiththis
isthatthecircularmemorylogispronetorolloverwhenyouhavemanydenialsora
chattykernel.Withauditd,allthemessagescometothedaemonandarewrittentothe
/data/misc/audit/audit.logfile.Thislogfile,hereinreferredtoasaudit.log,may
existondevicebootandisrotatedintothe/data/misc/audit/audit.oldfile,knownas
audit.old.Thedaemonresumesloggingtoanewaudit.logfile.Thisrotateevent
occurswhenthesizethresholdAUDITD_MAX_LOG_FILE_SIZEKB(setduringcompiletimein
thesystem/core/auditd/Android.mkfile)isexceeded.Thisthresholdistypically1000
KBbutcanbechangedinthedevice’smakefile.Also,sendingSIGHUPwithkillwill
causearotateasinthefollowingexample.
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
Auditdinternals
SincetheauditdandlibauditcodefromtheLinuxdesktophaveaGPLlicense,a
rewritewasdoneforAndroid,releasedundertheApachelicense.Therewriteisminimal,
thusyouwillonlyfindthefunctionsimplementedthatwererequiredtosupportthe
daemon.Thefunctionalandheaderinterfacesshouldremainidenticalthough.
Theauditddaemonstartslifeatmain()insystem/core/auditd.c.Itquicklychangesits
permissionsfromUIDroottoaspecialauditdUID.Whenitdoesthis,itretains
CAPSYS_AUDIT,whichisarequiredDACcapabilitychecktousetheAUDITNETLINK
socket.Itdoesthisviaacalltodrop_privileges_or_die().Fromthere,itdoessome
optionparsingwithgetopt(),andwefinallygettotheaudit-specificcalls,thefirstof
whichopenstheNETLINKsocketusingaudit_open().Thisfunctionsimplycalls
socket(PF_NETLINK,SOCK_RAW,NETLINK_AUDIT),whichopensafiledescriptortothe
NETLINKsocket.Afteropeningthesocket,thedaemonopensahandletoaudit.log
withacalltoaudit_log_open(constchar*logfile,constchar*rotatefile,
size_tthreshold).Thisfunctioncheckswhethertheaudit.logfileexistsand,ifit
does,renamesittoaudit.old.Itthencreatesanewemptylogfileinwhichthedatais
recorded.
Thenextstepistoregisterthedaemonwiththeauditsubsystemsothatitknowstowhom
tosendmessages.BysettingthePIDofthedaemon,youensurethatonlythisdaemonwill
getthemessages.SinceNETLINKcansupportmanyreaders,youdon’twanta“rogue
auditd”toreadthemessages.Withthatstated,thedaemoncalls
audit_set_pid(audit_fd,getpid(),WAIT_YES),whereaudit_fdistheNETLINK
socketfromaudit_open(),getpid()returnsthedaemon’sPID,andWAIT_YEScausesthe
daemontoblockuntiltheoperationiscomplete.Next,thedaemonenablestheaudit
subsystem’sadvancedfeatureswithacalltoaudit_set_enabled(audit_fd,1)andadds
rulestotheauditsubsystemviaaudit_rules_read_and_add(audit_fd,
AUDITD_RULES_FILE).Thisfunctionreadstherulesfromthatfile,formatssomestructures,
andsendsthosestructurestothekernel.
Theaudit_set_enabled()andaudit_rules_read_and_add()onlyhaveaneffectifthe
kernelisbuiltwithCONFIG_AUDITSYSCALL.Afterthis,thedaemoncheckswhetherthe-k
optionwasspecified.The-koptiontellsauditdtolookindmesgforanymissedaudit
records.Itdoesthisbecausethereisaracebetweencapturingauditrecordsbeforethe
circularbufferoverflowsanduserspacestartingmanyservices,generatingauditevents
andpolicyviolations.Essentially,thishelpscoalescetheauditeventsfromearlybootinto
thesamelogfiles.
Afterthis,thedaemonentersalooptoreadfromtheNETLINKsocket,formattingthe
messages,andwritingthemtothelogfile.ItstartsthisloopbywaitingforIOonthe
NETLINKsocketusingpoll().Ifpoll()exitswithanerror,theloopcontinuestocheck
thequitvariable.IfEINTRisraised,theloopguard,quit,issettotrueinthesignal
handler,andthedaemonexits.Ifpoll()isdataontheNETLINK,thedaemoncalls
audit_get_reply(audit_fd,&rep,GET_REPLY_BLOCKING,0),gettinganaudit_reply
www.it-ebooks.info
structurebackwiththerepparameter.Itthenwritestheaudit_replystructure(with
formatting)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()(whichis
reallyjustthesyscall,close(audit_fd)),andclosestheaudit.logwith
audit_log_close().Theaudit_log_*familyoffunctionsisnotpartoftheGPLed
interfacetoauditandisacustomwrite.
WhenGoogleportedauditdtothelogdinfrastructureinAndroid,itusedthesame
functionsandlibrarycodeusedbythedaemon’smain()andwrappeditintologd.
However,Googledidnottaketheaudit_set_enabled()and
audit_rules_read_and_add()functions.
www.it-ebooks.info
www.it-ebooks.info
InterpretingSELinuxdeniallogs
TheSELinuxdenialsgetroutedtothekernelauditsubsystem,toauditd,andfinally,to
audit.logandaudit.old.Withthelogsresidentinaudit.log,let’spullthisfileover
adbandhaveacloserlookatit.
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.Thetypefieldindicates
whattypeofmessageitis.Messageswithtype1400areAVCmessages,whichare
SELinuxdenialmessages(thereareothertypes,aswell).Themsg(shortformessage)
portionoftheprecedingpolicycontainsthepartforustoanalyze.
Thelastcommandweexecutedwasadbpull/data/misc/audit/aduit.logand,asyou
cansee,wehaveafewadbpolicyviolationsatthetailoftheaudit.logfile.Let’sstartby
lookingatthisevent:
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’snotwisetotrustthisvaluesinceit
canbecontrolledfromuserspaceusingtheprctl()interface.Itcanonlybeviewedasa
hint.ThebestwaytoverifythisistocheckthePIDusingps-Z:
#ps-Z|grepadbd
u:r:adbd:s0root30831/sbin/adbd
Withthedaemonverified,wecannowcheckthemessageinmoredetail.Themessage
consistsofthefollowingfields(optionalfieldsareidentifiedby*):
avc:denied:Thispartwillalwayshappenanddenotesitisadenialrecord.
{permission}:Thisisthepermissionthatwasdenied,inthiscase,getattr.
for:Thiswillalwaysbeprintedandmakestheoutputreadable.
Path*:Thisistheoptionalfieldthatcontainsthepathoftheobjectinquestion.It
onlymakessenseforfilesystemaccessdenials.
dev*:Thisistheoptionalfieldthatidentifiestheblockdeviceforthemounted
www.it-ebooks.info
filesystem.Itonlymakessenseforfilesystemaccessdenials.
ino*:Thisistheoptionalinodeofthefile.OnlytheanonymousfilesinLinuxprint
inode.Itonlymakessenseforfilesystemaccessdenials.
tclass:Thisisthetargetclassoftheobject,whichinourcasewasfile.
Atthispoint,weneedtounderstandwhatthemsgportionofthedenialrecordistellingus
ataverydistilledlevel.ItissayingthattheAndroiddebugbridgedaemonwantstobe
abletocallgetattronourpolicyfile.Afeweventsdown,wewillseeitalsowantsread
andopen.Thisisthesideeffectofrunningadbpull.Agetattrpermissiondenialoccurs
fromastat()syscall,andtheread/openarefromread()andopen()syscalls.Ifyou
wanttoallowthisinyourpolicy,whichwouldbeasecuritydecisionbasedonyourthreat
model,youshouldadd:
allowadbdaudit_log:file{getattrreadopen};
Alternatively,usethemacrosetsdefinedinglobal_macros:
allowadbdaudit_log:filer_file_perms;
Mostofthetime,youshouldusethemacrosdefinedinglobal_macrosforfilepermission
accesses.Typically,addingthemonebyoneisverytimeconsumingandtedious.The
macrosgroupthepermissionsinacontextanalogoustoread,write,andexecuteDAC
permissions.Forinstance,ifyougiveitopenandread,there’sagoodchanceatsome
pointthatthesourcedomainwillneedtostatthefile.So,ther_file_permsmacrohas
thosepermissionsinitalready.
Youshouldaddthisruletoexternal/sepolicy/adbd.te.The.tefiles(alsocalledtype
enforcementfiles)areorganizedbysourcecontext,somakesureyouaddittothecorrect
file.Wedonotrecommendaddingthisallowrule—there’snolegitimatereasonthatadbd
needsaccesstotheauditlogs—wecansafelyignorethesewithadontauditrule:
dontauditadbdaudit_log:filer_file_perms;
Thedontauditruleisapolicystatementthatsaysdon’taudit(print)denialsthatmatch
thisrule.
Ifyou’renotsurewhattodo,thebestadviceistoleveragethemailinglistsforSEfor
Android,SELinux,andaudit.Justkeepthemessagesappropriatetothespecificmailing
liststopic.
Atoolexistscalledaudit2allow,whichcanhelpyouwritepolicyallowrules.However,
it’sonlyatoolandcanbemisused.Ittranslatesthepolicyfiletotheallowrulesforthe
policy:
$cataudit.log|audit2allow
#=============adbd==============
allowadbdaudit_log:file{readgetattropen};
Theaudit2allowtoolisnotmacroawareorawareifyoureallywanttoaddthisallow
ruletothepolicyfile.Onlythepolicyauthorcanmakethisdecision.
Thereisalsoatooltoenablether_file_*macromappingcalledfixup.py.Youcanget
www.it-ebooks.info
thetoolathttps://bitbucket.org/billcroberts/fixup/overview.Afterdownloading,makeit
executable,andplaceitsomewhereinyourexecutablepath:
$chmoda+xfixup.py
$cataudit.log|audit2allow|fixup.py
#=============adbd==============
allowadbdaudit_log:filer_file_perms;
www.it-ebooks.info
www.it-ebooks.info
Contexts
Inthesimplestsense,writingpoliciesisjusttheactivityofidentifyingpolicyviolations
andaddingtheappropriateallowrulestothepolicyfile.However,inorderforSELinuxto
beeffective,thesourceandtargetcontextsmustbecorrect.Iftheyarenot,theallowrules
aremeaningless.
Thefirstthingsyoumightencounteraredenialswherethetargettypeisunlabeled.Inthis
case,thepropertargetlabelneedstobeset(refertoChapter11,LabelingProperties).
Also,processlabelscanbewrong.Multipleprocessescanbelongtoadomain,andunless
explicitlydoneviapolicy,thechildprocessofaparentinheritstheparent’sdomain.
However,inAndroid,domainsthathavemultipleprocessesarequitelimited.Youwill
neverseemultipleprocessesininit,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_shell
domains.Thefollowingtableprovidesacompletemappingofdomainstotheexpected
executablesandcardinality:
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)testshavebeenwrittenaroundthisand
submittedtoAOSPathttps://android-review.googlesource.com/#/c/82861/.
Basedonthesegenericassertionsofwhatagoodpolicyshouldlooklike,let’sevaluate
ours.
First,wewillcheckforunlabeledobjects.Fromthehost,withtheaudit.logfileyou
obtainedwithadbpull:
$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;wewill
addresstheseintheChapter11,LabelingProperties.Now,let’scheckfordomainsthat
havemultipleprocesseswhentheyshouldnot,andfindimproperbinariesinthose
domains(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_shell
domain,andwatchdogdisintheinitdomain.Thesemustbecorrected.
www.it-ebooks.info
www.it-ebooks.info
Summary
Writingsepolicyisrelativelyeasy,writinggoodpolicyisanart.Itrequiresthepolicy
authortounderstandthesystemandtheimplicationsoftheallowrule.Policyitselfisa
meta-programminglanguagewherethelanguagecontrolshowuserspaceandthekernel
getalong,andmuchlikeanyprogram,thepolicycanbearchitectedforaspecificuse.
Policiescanbetooporous(essentiallyuseless)orverytightanddifficulttochange
withoutbreakingtheportionsthatalreadywork.
Agoodpolicyneedstopreservetheintendedproperfunctionofthesystem,sothorough
testingofallthesystemswithinAndroidisessential.CTSisagreathelpinexercising
Android,butitoftendoesnotcoverallthecases;usertestingisrecommended.Inthenext
chapter,wewillcoverhowfilesystemsandfilesystemobjectsgettheirsecuritylabelsand
howwecanchangethem.Later,wewillgooverhowtouseCTSasatooltotestthe
systemandgeneratepolicyviolationsforintendedbehaviors.
www.it-ebooks.info
www.it-ebooks.info
Chapter8.ApplyingContextstoFiles
Inthelastchapter,weupgradedoursystem,collectedtheauditlogs,andstartedtoanalyze
theauditrecords.Wediscoveredthatsomeobjectsonthefilesystemwereunlabeled.In
thischapter,wewill:
Learnhowfilesystemsandfilesystemobjectsgettheirlabels
Demonstratetechniquestochangelabels
Introduceextendedattributesforlabeling
Investigatefilecontextsanddynamictypetransitions
www.it-ebooks.info
Labelingfilesystems
FilesystemsonLinuxoriginatefrommount,withtheexceptionoframdiskrootfson
Android.FilesystemsonLinuxvarydrastically.Ingeneral,inordertosupportallthe
featuresofSELinux,youneedafilesystemwiththesupportforxattrandthesecurity
namespace.Wesawthisrequirementwhenweweresettingupthekernelconfiguration.
Filesystemobjects,astheyarecreated,allstartwithaninitialcontext,justlikeallother
kernelobjects.Contextsonfilessimplyinheritfromtheirparent,soiftheparentis
unlabeled,thenthechildisunlabeled,withtheexceptionofatypetransitionrule.
Typically,ifthecontextisunlabeled,itinfersthatthedatawascreatedonafilesystem
priortoenablingSELinuxsupport,orthetypelabelinthexattrdoesnotexistinthe
currentlyloadedpolicy.
Theinitiallabelorinitialsecurityid(sid),isinthesepolicyfileinitial_sid_contexts.
Eachobjectclasshasitsassociatedinitialsidpresent.Forexample,let’stakealookatthe
followingcodesnippet:
...
sidfsu:object_r:labeledfs:s0
sidfileu:object_r:unlabeled:s0…
www.it-ebooks.info
fs_use
Filesystemscanbelabeledinavarietyofways.Thebestcasescenarioiswhenthe
filesystemsupportsxattrs.Inthatcase,anfs_use_xattrstatementshouldappearinthe
policy.Thesestatementsappearinthefs_usefileinthesepolicydirectory.Thesyntax
forfs_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;lookintheextended
attributesforthelabelorfilecontext.
www.it-ebooks.info
fs_task_use
Theotherwayafilesystemcanbelabeledisbyusingtheprocess’contextwhilecreating
objects.Thismakessenseforpseudofilesystemswheretheobjectsarereallyprocess
contexts,suchaspipefsandsockfs.Thesepseudofilesystemsmanagethepipeand
socketsyscallsandarenotreallymountedtouserspace.Theyexistinternallytothekernel,
forthekernelsuse.However,theydohaveobjects,andlikeanyotherobject,theyneedto
belabeled.Thisisthecontextinwhichthefs_task_usepolicystatementmakessense.
Theseinternalfilesystemscanonlybeaccessedbyprocessesdirectly,andprovideservices
tothoseprocesses.Hence,labelingthemwiththecreatormakessense.Thesyntaxisas
follows:
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_trans
Thenextwayyoumightwishtosetlabelsonpseudofilesystemsthatareactually
mounted,isbyusingfs_use_trans.Thissetsafilesystemwidelabelonthepseudo
filesystem.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
genfscon
Ifnoneofthefs_use_*statementsmeetyourusecases,whichwouldbethecaseforvfat
filesystemsandprocfs,thenyouwouldusethegenfsconstatement.Thelabelspecified
forgenfsconappliestoallinstancesofthatfilesystemmount.Forinstance,youmight
wishtousegenfsconwiththevfatfilesystems.Ifyouhavetwovfatmounts,theywill
usethesamegenfsconstatementforeachmount.However,genfsconbehavesdifferently
withprocfs,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’tsupportanyfine
granularitytoitslabeling;so/istheonlythingyoucanuse.However,youcangetwild
withprocfsandsettoanygranularityyoudesire.
www.it-ebooks.info
Mountoptions
Anotheroption,ifnoneofthosefityourneeds,istopassthecontextoptionviathemount
commandline.Thissetsafilesystemwidemountcontext,suchasgenfscon,butisuseful
inthecaseofmultiplefilesystemsthatneedtohaveseparatelabels.Forinstance,ifyou
havetwovfatfilesystemsmounted,youmightwishtoseparateaccessestothem.With
genfsconstatements,bothfilesystemswouldusethesamelabelprovidedbygenfscon.
Byspecifyingthelabelatmounttime,youcanhavetwovfatfilesystemsmountedwith
differentlabels.
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.These
optionsaremutuallyexclusivefromcontext.Thefscontextoptionsetsthemeta
filesystemtypethatisusedforcertainoperations,suchasmount,butdoesnotchangethe
perfilelabels.Thedefcontextsetsthedefaultcontextforunlabeledfilesoverridingthe
initial_sidstatements.Lastly,anotheroption,rootcontextallowsyoutosettheroot
inodecontextinthefilesystem,butonlyforthatobject.Accordingtothemanpagemount
(man8mount),itwasfoundusefulinstatelessLinux.
www.it-ebooks.info
Labelingwithextendedattributes
Lastly,andprobablythemostfrequentlyusedwayoflabeling,isbyusingtheextended
attributessupportalsoknownasxattrorEAsupport.Evenwithxattrsupport,new
objectsinheritthecontextoftheirparentdirectory;however,theselabelshavethe
granularityofbeingperfilesystemobject-basedorinode-based.Ifyouremember,wehad
toturnonorverifythatXATTR(CONFIG_EXT4_FS_XATTR)supportwasenabledforour
filesystemsonAndroidaswellasconfiguringSELinuxtouseitviatheconfigoption
CONFIG_EXT4_FS_SECURITY.
Extendedattributesareakey-valuemetadatastoresforfiles.SELinuxsecuritycontexts
usethesecurity.selinuxkey,andthevalueisastringthatisthesecuritycontextor
label.
www.it-ebooks.info
Thefile_contextsfile
Withinthesepolicydirectory,youwillfindthefile_contextsfile.Thisfileisconsulted
tosettheattributesonfilesystemsthatsupportperfilesecuritylabels.Notethatacouple
ofpseudofilesystemssupportthisaswell,suchastmpfs,sysfs,andrecentlyrootfs.The
file_contextfilehasaregularexpression-basedsyntaxasfollows,whereregexpisthe
regularexpressionforthepath:
regexp<type>(<filelabel>|<<none>>)
Ifmultipleregularexpressionsaredefinedforafile,thelastmatchisused,soorderis
important.
Thefollowinglistshowseachtypefieldvalueforthetypeoffilesystemobject,their
meanings,andsyscallinterface:
--:Thisdenotesaregularfile.
-d:Thisdenotesadirectory.
-b:Thisdenotesablockfile.
-s:Thisdenotesasocketfile.
-c:Thisdenotesacharacterfile.
-l:Thisdenotesalinkfile.
-p:Thisdenotesanamedpipefile.
Asyoucansee,thetypeisessentiallythemodeasoutputbyls-lacommand.Ifit’snot
specified,itmatcheseverything.
Thenextfieldisthefilelabelorthespecialidentifier<<none>>.Eitheronewouldsupplya
contextortheidentifier<<none>>.Ifyouspecifythecontext,theSELinuxtoolsthat
consultfile_contextsusethelastmatchtothespecifiedcontext.Ifthecontextspecified
is<<none>>,itmeansthatnocontextisassigned.So,leavetheonethatwehavefound.
Thekeyword<<none>>isnotusedintheAOSPreference,sepolicy.
It’simportanttonotethattheprecedingparagraphexplicitlystatesthatSELinuxtoolsuse
thefile_contextspolicy.Thekernelisnotawarethatthisfileexists.SELinuxlabelsall
itsobjectsbyexplicitlysettingthemfromuserspacewithtoolsthatlookupthecontextin
file_contextorviathefs_use_*andgenfspolicystatements.Inotherwords,
file_contextsisnotbuiltinthecorepolicyfile,anditisnotloadedoruseddirectlyby
thekernel.Atbuildtime,thefile_contextsfileisbuiltintheramdiskrootfsandcanbe
foundat/file_contexts.Also,duringbuildtime,thesystemimageislabeled,freeing
thedeviceitselffromthisburden.
InAndroid,init,ueventd,andinstalldhaveallbeenmodifiedtolookupthecontexts
ofobjectstheyarecreating;sothattheycanlabelthemproperly.Thus,alltheinitbuiltins
thatcreatefilesystemobjects,suchasmkdir,havebeenmodifiedtomakeuseofthe
file_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.Notehowtheentriesareinorder
frommostgenerictomorespecificdevfiles.Thus,anyfilesnotcoveredbythemore
specificentrieswillendupwiththecontextu:object_r:device:s0,andthefilesthat
matchfurtherdown,endupwithamorespecificlabel.Forinstance,theaccelerometerat
/dev/accelerometerwillgetthecontextu:object_r:sensors_device:s0.Notethatthe
typefieldwasomitted,whichmeansthatitmatchesonallfilesystemobjects,suchas
directories(type-d).
Youmightbewonderinghow/dev,thedirectoryitself,getsafilecontext.Lookingat
someofthesnippets,wesaythe/orroot,gotlabeledviathestatementgenfsconrootfs
/u:object_r:rootfs:s0inthegenfs_contextfile.Thischapterstatedearlierthat,“new
objectsinheritthecontextoftheirparentdirectory.”Hence,wecanreasonthat/devisof
contextu:object_r:rootfs:s0sincethatisthelabel/has.Wecantestthisbypassing
the-Zflagtolstoshowusthelabelof/dev.OntheUDOOserialconnection,executethe
followingcommand:
130|root@udoo:/#ls-laZ/
...
drwxr-xr-xrootrootu:object_r:device:s0dev
...
Itseemsthatthehypothesisisincorrect,butnotethatitistruethateverythinghasalabel,
andifit’snotspecified,thenitinheritsfromtheparent.Lookingbackatsepolicy,wecan
seethatthedevfilesystemwasinitiallysetwithafs_use_transdevtmpfs
u:object_r:device:s0;policystatement.Sowhenthefilesystemismounted,itisset
filesystemwide.Later,whenentriesareaddedbyinitorueventd,theyuse
file_contextsentriestosetthecontextofthenewlycreatedfilesystemobjecttowhatis
specifiedinthefile_contextsfile.Thefilesystemat/dev,whichisadevtmpspseudo
filesystem,isanexampleofafilesystemthathasbothafilesystem-widelabelviathe
fs_use_transstatement,butcanalsosupportfinegrainedlabelingviafile_contexts;.
FilesystemsarenotveryconsistentincapabilitiesonLinux.
www.it-ebooks.info
Dynamictypetransitions
DynamictypetransitionsindicatedbytheSELinuxpolicystatementtype_transitionare
awaytoallowfilestodynamicallydeterminetheirtypes.Becausethesearecompiledinto
thepolicy,thesedonothaveanyrelationtothefile_contextsfile.Thesepolicy
statementsallowthepolicyauthortodynamicallydictatethecontextofafilebasedonthe
contextinwhichthefileiscreated.Theseareusefulinsituationswhereyoudon’tcontrol
sourcecode,ordonotwishtocoupleSELinuxinanyway.Forinstance,thewpa
supplicant,whichisaservicethatrunsforWi-Fisupportandcreatesasocketfileinits
datadirectory.Itsdatadirectoryislabeledwiththetypewifi_data_fileandasexpected,
thesocketendsupwiththatlabel.However,thissocketissharedbythesystemserver.
Now,wecanallowjustthesystemservertoaccessthetypeandobjectclass,however,
hostapdandotherthingsarecreatingsocketsandotherobjectsinthatdirectoryandthus
theobjectsalsohavethistype.Wereallywanttoensurethatthetwosocketsinquestion,
theoneusedbyhostapdandtheotherbysystemserver,arekeptexclusivefromeach
other.Todothis,weneedtobeabletolabeloneofthesocketsatafinergranularity,and
todoso,wecaneithermodifythecodeoruseadynamictypetransition.Ratherthan
muckingwiththecode,let’suseatypetransition,asfollows:
type_transitionwpawifi_data_file:sock_filewpa_socket;
Thisisanactualstatementfromthesepolicyfile,wpa_supplicant.te.Itsaysthat,when
aprocessofthetypewpacreatesafileofthetypewifi_data_fileandtheobjectclassis
sock_filetolabelitaswpa_socketoncreation.Thestatementsyntaxisasfollows:
type_transition<creatingtype><createdtype>:<class><newtype>;
AsofSELinuxpolicyversion25,thetype_transitionstatementcansupportnamedtype
transitionswhereafourthargumentexistsandisthenameofthefile:
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.Regexisnot
supported.It’salsointerestingtonotethatthedynamictransitionsarenotlimitedtofile
objects,butanyobjectclasseventprocesses.Wewillseehowdynamicprocesstransitions
areusedinChapter9,AddingServicestoDomains.
www.it-ebooks.info
www.it-ebooks.info
Examplesandtools
Withthetheorybehindus,let’slookatthetoolsandtechniquestolabelfilesinthe
system.Let’sstartbymountingaramfsfilesystem.Wewillstartbyremounting/sinceit
isreadonlyandcreateamountpointforthefilesystem.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,and
setanewgenfsconstatementtouseit.Wewilldeclarethenewtypeinthesepolicyfile
file.te:
typeramdisk,file_type,fs_type;
Thetypepolicystatementsyntaxisasfollows:
type<newtype>,<attribute0,attribute1…attributeN>;
AttributesinSELinuxarestatementsthatletyoudefinecommongroups.Theyaredefined
viatheattributestatement.InAndroidSELinuxpolicy,wehavefile_typeand
fs_typedefinedforusalready.Wewillusethemherebecausethisnewtype,whichwe’re
creating,hastheattributesfile_typeandfs_type.Thefile_typeattributeisassociated
withatypeforafile,andthefs_typeattributemeansthatthistypeisalsoassociatedwith
filesystems.Attributes,rightnow,arenotofgreatimportance;sodon’tgetcaughtupin
thedetail.
Thenextthingtomodifyisthesepolicyfile,genfs_contextbyaddingthefollowing:
genfsconramfs/u:object_r:ramdisk:s0
Now,wewillcompilethebootimageandflashittothedevice,orbetteryet,let’susethe
dynamicpolicyreloadsupportlikethefollowing.
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,and
nowtoshowinheritance,let’sgoaheadandcreateafileonthefilesystemwithtouch:
root@udoo:/#cd/ramdisk
root@udoo:/ramdisk#touchhello
root@udoo:/ramdisk#ls-Z
-rw-------rootrootu:object_r:ramdisk:s0hello
Asweexpected,thenewfileislabeledwiththetyperamdisk.Now,supposewhenwedo
touchfromtheshell,wewantthefiletobeofadifferenttype,suchasramdisk_newfile;
howcanwedothis?Wecandothisbymodifyingtouchitselftoconsultfile_contexts,
orwecandefineadynamictypetransition;letustrythedynamictypetransition
approach.Thefirstargumenttothetype_transitionstatementisthecreatingtype;so
whattypeisourshellin?Youcangetthisbyperforming:
root@udoo:/ramdisk#echo`cat/proc/self/attr/current`
u:r:init_shell:s0
Asimplerwayistoruntheid-Zcommand,whichusestheaforementionedprocfile.For
aserialconsole,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,thepolicyweauthornow
willaddressbothcases.
Startbyopeningthesepolicyfile,init_shell.teandappendthefollowingtotheendof
thefile:
www.it-ebooks.info
type_transitioninit_shellramdisk:fileramdisk_newfile;
Dothisforthesepolicyfile,shell.te:
type_transitionshellramdisk:fileramdisk_newfile;
Now,weneedtodeclarethenewtype;soopenupthesepolicyfile,file.teandappend
thefollowing:
typeramdisk_newfile,file_type;
Notethatwehaveonlyusedthefile_typeattribute.Thisisbecauseafilesystemshould
neverhavethetyperamdisk_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’sinvestigatethereasonbytryingonanexampleofanext4
filesystem.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’tapplytoourtype
transitionrule;tofixthis,wecanusethechconcommandtoexplicitlychangethefiles
context:
root@udoo:/data#chconu:object_r:ramdisk:s0ramdisk
root@udoo:/data#ls-laZ|grepramdisk
drwx------rootrootu:object_r:ramdisk:s0ramdisk
Nowwiththecontextchangedtomatchwhatweweretryingearlierwiththeramdisk,let’s
trytocreateafilewithinthisdirectory:
root@udoo:/data/ramdisk#touchnewfile
root@udoo:/data/ramdisk#ls-laZ
-rw-------rootrootu:object_r:ramdisk_newfile:s0newfile
Asyoucansee,thetypetransitionhasoccurred.Thiswasmeanttoillustratetheissues
youmayfindwhileworkingwithSELinuxandAndroid.Nowthatwehaveshownthat
ourtype_transitionstatementisvalid,thereareonlytwopossibilitieswhythisis
failing:thefilesystemdoesn’tsupportitorwe’remissingsomethingsomewhereto“turnit
on”.Itturnsoutthatthelatteristhecase;weweremissingourfs_use_transstatements.
Sogoaheadandopenupthesepolicyfile,fs_useandaddthefollowingline:
fs_use_transramfsu:object_r:ramdisk:s0;
www.it-ebooks.info
ThisstatementenablesSELinuxdynamictransitionsonthisfilesystem.Now,rebuildthe
sepolicyproject,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’t
supportxattrs.
Now,supposewewanttomountanotherramdisk,whatwouldhappen?Wellsinceitwas
labeledwiththegenfsconstatement,allfilesystemsmountedwiththattypeshouldgetthe
context,u:object_r:ramdisk:s0.Wewillmountthisfilesystemat/ramdisk2,andverify
thisbehavior:
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,wewillneedto
havetheirtargetfilesinseparatetypes.Todothis,wecanmountthenewramdiskwiththe
contextoption.Butfirst,weneedtocreatethenewtype;letsgotothesepolicyfile,
file.teandaddanewtypecalledramdisk2:
typeramdisk2,file_type,fs_type;
Now,buildthesepolicywiththecommandmmm,followedbeusingthecommandabd
pushtopushthepolicy,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.Whenwemountedramfswithout
thecontextoption,wegot:
<7>SELinux:initialized(devramfs,typeramfs),usesgenfs_contexts
Whenwemounteditwiththecontext=<context>option,wegot:
<7>SELinux:initialized(devramfs,typeramfs),usesmountpointlabeling
WecanseethatSELinuxgivesussomehelpfulmessageswhiletryingtofigureoutfrom
whereitsourcesitslabels.
Now,let’sgoontolabelingfilesystemswiththexattrsupport,suchasext4.Wewillstart
withthetoolboxcommand,chcon.Thechconcommandallowsyoutosetthecontextofa
filesystemobjectexplicitly,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,whichisthedefaultlabelfor
thatfilesystem;let’schangetheamtypetoam_exec.Again,weneedtocreateanewtype
byaddingthefollowingtosepolicyfile,file.te:
typeam_exec,file_type;
Now,rebuildthepolicyfile,pushittotheUDOO,andtriggerareload.Afterthat,let’s
startremountingthesystem,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,andrestorethatfileto
whatissetinthefile_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_contextsandrestorethespecified
contextonthatobject.
TheAndroidsystem’sfilesystemgetsconstructedduringthebuildtime,andconsequently,
allitsfileobjectsarelabeledduringthatprocess.Wecanalsochangethisatbuildtimeby
changingfile_contexts.Withthischanged,thesystempartitionrebuilt,andafter
reflashingthesystem,weshouldseetheamfilewiththeam_exectype.Wecantestthisby
amendingthesepolicyfile,file_contextsbyaddingthislineattheendofthe
system/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,and
howwecancontroltheselabels.
www.it-ebooks.info
Fixingup/data
Additionallyintheauditlogs,wehaveseenabunchofunlabeledfiles,forinstance,the
followingdenial:
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,whichmountcommandsandwilltelluswhat
filesystemthisismountedto,initsoutput:
root@udoo:/#mount|grepmmcblk0p4
/dev/block/mmcblk0p4/dataext4
rw,seclabel,nosuid,nodev,noatime,nodiratime,errors=panic,user_x0
Sowhydoesthe/datafilesystemhavesomanyunlabeledfiles?Thereasonisthat
SELinuxismeanttobeturnedonfromanemptydevice,thatis,fromfirstboot.Android
buildsthedatadirectorystructuresondemand.Thus,allthelabelsforthe/dataare
handledbythefile_contextsfilesinceitisext4.Also,itishandledbythesystemsthat
createthe/datafilesanddirectories.Thesesystemshavebeenmodifiedtolabelthedata
partitionbasedonthefile_contextsspecifications.Sothispresentstwooptions:wipe
/dataandreboot,orrestorecon-R/data.
Optiononeisabitharsh,butifyouejecttheSDcardandremoveallthefilesonthedata
partition,partition4,Androidwillrebuildandyouwon’tseeanymoreunlabeled
issues.However,thisisnotrecommendedfordeployeddeviceswhenyouupgrade;you
willdestroyalloftheusers’data.
Optiontwoismorepalatableindeployedscenarios,buthasitslimitations.Notably,
executingrestorecon-R/datawilltakealongtimeandmustbedoneearlyinboot,
rightafterthemount.However,thisisreallytheonlyoptionatthispoint.Google,
however,hasdonealotofworkinthisarea,andcreatedasystemthatintelligently
relabels/dataonpolicyupdates.Forouruse,wewillchooseavariantofoptiontwo,
especiallyafterconsideringhowsparselypopulatedthe/datafilesystemis;wereally
haven’tinstalledorgeneratedalotofuserdatayet.Withthatstated,execute:
root@udoo:/#restorecon-R/data
root@udoo:/#reboot
Wedon’thavetoexecuterestoreconearlyinbootsinceoursystemisinpermissive
mode,andwe’renotinadeployedscenario.Now,let’spulltheaudit.logfileand
compareittothealreadypulledaudit.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
0
Great,wefixedupallofourunlabeledissueson/data!
www.it-ebooks.info
www.it-ebooks.info
Asidenoteonsecurity
Notethateventhoughwearerunningallthesecommandsandchangingallthesethings,
thisisnotasecurityvulnerabilitywithinSELinux.Beingabletochangetypelabels,
mountingfilesystems,andassociatingfilesystemswithatype,allrequireallowrules.If
youlookthroughtheauditlogs,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’thavebeenabletoperformanyofthe
experimentsshownhere.
www.it-ebooks.info
www.it-ebooks.info
Summary
Inthischapter,wesawhowtogetfilesintocontextsbyrelabelingthem.Weusedavariety
oftechniquestoaccomplishthistask,fromtoolboxcommandssuchaschconand
restorecon,tomountoptionsanddynamictransitions.Withthesetools,wecanensure
thatallfilesystemobjectsarelabeledcorrectly.Thisway,weendupwiththerighttarget
contextssothatthepoliciesweauthorareeffective.Inthenextchapter,wewillfocuson
theprocesses,makingsurethattheyareintherightdomainorcontext.
www.it-ebooks.info
www.it-ebooks.info
Chapter9.AddingServicestoDomains
Inthepreviouschapter,wecoveredtheprocessofgettingfileobjectsintheproper
domain.Inmostcases,thefileobjectisthetarget.However,inthischapter,wewill:
Emphasizelabelingprocesses—notablyAndroidservicesrunandmanagedbyinit
Managetheancillaryassociatedobjectscreatedbyinit
www.it-ebooks.info
Init–thekingofdaemons
TheinitprocessisvitalinaLinuxsystem,andAndroidisnotspecialinthiscase.
However,Androidhasitsownimplementationofinit.Initisthefirstprocessonthe
system,andthushasaProcessID(PID)of1.Allotherprocessesaretheresultofadirect
fork()frominit,thusallprocesseseventuallyareparentedunderinit,eitherdirectlyor
indirectly.Initisresponsibleforcleaningupandmaintainingtheseprocesses.For
instance,anychildprocesswhoseparentdiesisreparentedunderinitbythekernel.Inthis
way,initcancallwait()(man2waitformoredetails)tocleanupaftertheprocesswhen
itexits.
Note
Aprocesswhichhasterminatedbuthasnothadwait()calledisazombieprocess.The
kernelmustkeeptheprocessdatastructuresarounduntilthiscall.Failingtodosowill
consumememoryindefinitely.
Sinceinitistherootofallprocesses,italsoprovidesamechanismtodeclareandexecute
commandsthroughitsownscriptinglanguage.Filesusingthislanguagetocontrolinitare
referredtoasinitscripts,andwehavealreadymodifiedsomeofthem.Inthesourcetree,
weusedtheinit.rcfile,whichyoucanreachbynavigatingto
device/fsl/imx6/etc/init.rc,butonthedevice,itispackagedwiththeramdiskat
/init.rc,andismadeavailabletoinit,whichisalsopackagedintheramdiskat/init.
Toaddaservicetotheinitscript,youcanmodiheinit.reandaddadeclaration,as
follows:
service<name><path>[<argument>...]
Here,nameistheservicename,pathisthepathtotheexecutable,andargumentarespace
delimitedargumentstringstobedeliveredtotheexecutableinitsargvarray.
Forexample,hereistheservicedeclarationforrild,theRadioInterfaceLayerDaemon
(RILD):
Serviceril-daemon/system/bin/rild
Itisoftenthecasethatadditionalserviceoptionscanandneedtobeadded.Theinitscript
servicestatementsupportsarichassortmentofoptions.Forthecompletelist,refertothe
informationalfilelocatedatsystem/core/init/readme.txt.Additionally,wecovered
theSEforAndroid-specificchangesinChapter3,AndroidIsWeird.
Continuingtodissectrild,weseethattherestofthedeclarationintheUDOOinit.rcis
asfollows:
Serviceril-daemon/system/bin/rild
classmain
socketrildstream660rootradio
socketrild-debugstream660radiosystem
socketrild-pppstream660radiosystem
userroot
www.it-ebooks.info
groupradiocacheinetmiscaudiosdcard_rwlog
Theinterestingthingtonotehereisthatitcreatesquiteafewsockets.Thesocket
keywordininit.rcisdescribedbythereadme.txtfile:
Note
Fromthesourcetreefilesystem/core/init/readme.txt:
socket<name><type><perm>[<user>[<group>[<context>]]]
CreateaUnixdomainsocketnamed/dev/socket/<name>andpassitsfdtothelaunched
process.Thetypemustbedgram,stream,orseqpacket.TheuserandgroupIDsdefault
to0.TheSELinuxsecuritycontextforthesocketiscontext.Itdefaultstotheservice
securitycontext,asspecifiedbyseclabel,oriscomputedbasedontheserviceexecutable
file’ssecuritycontext.
Let’stakealookatthisdirectoryandseewhatwe’vefound.
root@udoo:/dev/socket#ls-laZ|grepadb
srw-rw----systemsystemu:object_r:adbd_socket:s0adbd
Thisraisesthequestion,“Howdiditgetintothatdomain?”Usingourknowledgefromthe
previouschapter,weknowthat/devisatmpfs,soweknowthatitdidnotenterthis
domainthroughxattrs.Itmustbeeitheracodemodificationoratypetransition.Let’s
checkwhetherit’satypetransition.Ifitis,wewouldexpecttoseeastatementinthe
expandedpolicy.conf.SELinuxpolicyisbasedonthem4macrolanguage.During
builds,itisexpandedintopolicy.conf,andthencompiled.Chapter12,Masteringthe
ToolChain,hasmoredetailsonthis.
Wecandiscoverthisbyusingsesearchtofindtypetransitionsforadbd_socket:
$sesearch-T-tadbd_socket$OUT/sepolicy
Asyoucanseefromtheemptyoutput,therearezerosuchlines,soit’snotthepolicy
whichisdoingthisbutacodechange.
InLinux,processesarecreatedwithfork()followedbyexec().Becauseofthis,weare
abletoaffordgreatkeywordstosearchtheinitdaemon.Wesuspectthatthecodetosetup
thesocketisjustafteracalltofork()inthechildprocessesandbeforeacalltoexec():
$grep-nforksystem/core/init/init.c
235:pid=fork();
So,theforkwearesearchingforisonline235ofinit.c;let’sopeninit.cinatext
editorandtakealook.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.Thechild
processexecuteswithinthisifstatementandtheparentskipsit.Thefunctioncreate_
socket()alsoseemsinteresting.Itappearstotakethenameoftheservice,thetypeof
socket,permissionsflags,uid,gid,andsocketcon.Whatissocketcon?Let’scheck
whetherwecantracebacktowhereitisset.
Ifwelookbeforefork(),wecanseethattheparentprocessgetsitssconbasedontwo
factors:
...
if(svc->seclabel){
scon=strdup(svc->seclabel);
if(!scon){
ERROR("Outofmemorywhilestarting'%s'\n",svc->name);
return;
}
}else{
...
Thefirstpaththroughtheifstatementoccurswhensvc->seclabelisnotnull.Thissvc
structureispopulatedwiththeoptionsthatcanbeassociatedwithaservice.Asarefresher
fromChapter3,AndroidIsWeird,seclabelletsyouexplicitlysetthecontextona
service,hardcodedtothevalueininit.rc.Theelseclauseisabitmoreinvolvedand
interesting.
Intheelseclause,wegetthecontextofthecurrentprocessbycallinggetcon().This
function,sincewe’rerunningininit,shouldreturnu:r:init:s0andstoreitinmycon.The
nextfunction,getfilecon()ispassedthepathoftheexecutable,andchecksthecontext
ofthefileitself.Thethirdfunctionistheworkhorsehere:security_compute_create().
www.it-ebooks.info
Thistakesthemycon,fcon,andtargetclassandcomputesthesecuritycontext,scon.
Giventheseinputs,ittriestodetermine,basedonpolicytypetransitions,whatthe
resultingdomainforthechildshouldbe.Ifnotransitionsaredefined,sconwillbethe
sameasmycon.
Aconditionalexpressionwithinthecreate_socket()functionadditionallydetermines
thesocketcontextpassed.Thevariablesiisastructurethatcontainsalltheoptionstothe
socketstatementintheinitservicesection.Asspecifiedbythereadme.txtfile,si>socketconisthesocketcontextargument.Inotherwords,thesocketcontextcancome
fromoneofthreeplaces(indescendingpriority):
Thesocketconoptiononthesocketoptionintheservicedeclaration
Theseclabeloptionontheservicekeyword
Dynamicallycomputedfromsourceandtargetcontexts
Thesocketcontextispassedtocreate_socket().Now,let’slookatcreate_socket().
Thisfunctionisdefinedatsystem/core/init/util.c:87.Thesnippetsofcodearound
socket()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.Thismeans
thatthesocketcreatedbythesocket()callwillhavethecontextsetvia
setsockcreatecon().Afterit’screated,theprocessresetsittotheoriginalbyusing
setsockcreatecon(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.Thefunctionsareanalogousto
setsock_creation(),butworkforfilesystemobjects.However,theselabel_lookup()
functionlooksinfile_contextsforthecontextofthefile.Thepartyoumightbemissing
isthatthecalltobind(),forpath-basedsockets,createsafileatthepathspecifiedin
sockaddr_unstruct.So,thesocketobjectandthefilesystemnodeentryaredistinctly
separatethingsandcanhavedifferentcontexts.Typically,thesocketbelongstothe
process’context,andthefilesystemnodeisgivensomeothercontext.
www.it-ebooks.info
www.it-ebooks.info
Dynamicdomaintransitions
Wesawinitcomputingofthecontextsfortheinitsockets,butweneverencounteredit
whilesettingthedomainsforchildprocesses.Inthissection,wewilldiveintothetwo
techniquestodoso:explicitsettingwithaninitscriptandsepolicydynamicdomain
transitions.
Thefirstwaytothedomainsforchildprocessesiswiththeseclabelstatementintheinit
scriptservicedeclaration.Withinthechildprocessesexecutionafterfork(),wefindthis
statement:
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,weseethatthe
exec()functioncallsaremade.Theexec()syscallneverreturnsonsuccess;itonly
returnsonfailure.
Theotherwaytosetthedomainsforchildprocesses,whichisthepreferredway,isby
usingsepolicy.It’spreferredbecausethepolicyhasnodependenciesonanythingelse.By
hardcodingacontextintoinit,you’recouplingadependencybetweentheinitscriptand
thesepolicy.Forinstance,ifthesepolicyremovesatypethatwashardcodedintheinit
script,theinitsetconwillfail,butbothsystemswillcompilecorrectly.Ifyouremovea
typeforatypetransitionandleavethetransitionstatement,youcancatchtheerrorat
compiletime.Sincewelookedattherildservicestatement,let’slookattherild.te
policyfilelocatedinsepolicy.Weshouldsearchforthetype_transitionkeywordin
thisfileusinggrep:
$grep-ctype_transitionrild.te
0
Noinstancesoftype_transitionarefound,butthiskeywordmustexist,similartofiles.
However,itcanbehiddeninanunexpandedmacro.TheSELinuxpolicyfilesareinthe
m4macrolanguage,andtheygetexpandedpriortobeingcompiled.Let’slookthrough
rild.teandcheckwhetherwecanfindsomemacros.Theyaredistinguishedandlook
likefunctionswithparameters.Thefirstmacrowecomeacrossisthe
init_daemon_domain(rild)macro.Now,weneedtofindthismacro’sdefinitionin
sepolicy.Them4languageusesthedefinekeywordtodeclaremacros,sowecansearch
forthat:
$grep-ninit_daemon_domain*|grepdefine
te_macros:99:define(`init_daemon_domain',`
Ourmacroisdeclaredinte_macros,whichcoincidentallyholdsallthemacrosrelatedto
www.it-ebooks.info
typeenforcement(TE).Let’stakealookatwhatthismacrodoesinmoredetail.First,its
definitionis:
...
#####################################
#init_daemon_domain(domain)
#Setupatransitionfrominittothedaemondomain
#uponexecutingitsbinary.
define(`init_daemon_domain',`
domain_auto_trans(init,$1_exec,$1)
tmpfs_domain($1)
')
...
Thecommentedlinesintheprecedingcode(linesstartingwith#inm4),statethatitsets
upatransitionfrominittothedaemondomain.Thissoundslikesomethingwewant.
However,boththeencompassingstatementsaremacros,andweneedtorecursively
expandthem.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,weneed
tokeepexpandingmacrosinoursearch.Accordingtothecomment,thedomain_trans()
macroallowsjustthetransitiontooccur.RememberthatalmosteverythinginSELinux
needsexplicitpermissionfromthepolicyinordertohappen,includingtypetransitions.
Thelaststatementinthemacroistheoneweweresearchingfor:
type_transition$1$2:process$3;
Ifyouexpandthisstatementout,you’llget:
type_transitioninitrild_exec:processrild;
Whatthisstatementconveysisthatifyoumakeanexec()syscallonafilewiththetype
rild_exec,andtheexecutingdomainisinit,thenmakethechildprocess’domainrild.
www.it-ebooks.info
www.it-ebooks.info
Explicitcontextsviaseclabel
Theotheroptionforsettingcontextsisverystraightforward.It’shardcodingthemwiththe
initscriptintheservicedeclaration.Intheservicedeclaration,aswesawinChapter3,
AndroidIsWeird,thereweremodificationstotheinitlanguage.Oneoftheadditionsis
seclabel.Thisoptionjustletsinitexplicitlychangethecontextoftheservicetothe
argumentgiventoseclabel.Hereisanexampleofadbd:
Serviceadbd/sbin/adbd
classcore
socketadbdstream660systemsystem
disabled
seclabelu:r:adbd:s0
Sowhyusedynamictransitionsonsomeandseclabelonothers?Theansweris
dependentonwhereyou’reexecutingfrom.Thingssuchasadbdexecuteearlyonfromthe
ramdisk,andsincetheramdiskreallydoesn’tuseperfilelabels,youcan’tsetup
transitionsproperly—thetargethasthesamecontext.
www.it-ebooks.info
www.it-ebooks.info
Relabelingprocesses
Nowthatwearearmedwithdynamicprocesstransitions,andtheabilitytosetsocket
contextsfrominitscriptsisneeded.Let’sattempttorelabeltheservicesthatarein
impropercontexts.Wecantellifthey’reimproperbycheckingthemagainstthefollowing
rules:
Nootherprocessbutinitshouldbeintheinitcontext
Nolongrunningprocessshouldbeintheinit_shelldomain
Nothingbutzygoteshouldbeinthezygotedomain
Note
AmorecomprehensivetestsuiteispartofCTSonAOSP.RefertotheAndroidCTS
projectformoredetails:(gitclone)https://android.googlesource.com/platform/cts.Take
noteofthe
./hostsidetests/security/src/android/cts/security/SELinuxHostTest.javaand
./tests/tests/security/src/android/security/cts/SELinux.*.javatests.
Let’srunsomebasiccommandsandevaluatethestatusofourUDOOovertheadb
connection:
$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,andthesecondis
ashprocess.Weneedtofindtheseandcorrectthem.
Wewillstartwiththemysteryshprogram.Asyoucanrecallfromthepreviouschapter,
ourUDOOserialconsoleprocesshadthecontextofinit_shell,sothisisagoodsuspect.
Let’scheckPIDsandfindout.FromaUDOOserialconsoleexecute:
root@udoo:/#echo$$
2278
WecancomparethisPIDtothePIDfieldintheadbshellpsoutputhere(PIDfieldis
thethirdfield,index2),andasyoucansee,wehaveamatch.
Fromthere,weneedtofindtheservicedeclarationforthis.Weknowthatitisininit.rc
sinceit’srunningininit_shell,atypethatcanonlybetransitionedtobyinitdirectlyas
pertheSELinuxpolicy.Also,initonlystartsprocessingthingsbyservicedeclarations,so
inordertobeininit_shell,youmuststartbyinitviaaservicedeclaration.
Note
Usesesearchtofindoutsuchthingsonthecompiledsepolicybinary:
$sesearch-T-sinit-tshell_exec-cprocess$OUT/root/sepolicy
www.it-ebooks.info
Ifwesearchinit.rcfortheUDOO,whichisinudoo/device/fsl/imx6/etc,wecan
grepitscontentsfor/system/bin/sh,thecommandinquestion.Ifwedothat,wewill
find:
$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,andverifythatourserial
connectionnolongerworks:
$adbshellsetpropctl.stopconsole
Myliveserialconnectiondiedat:
root@udoo:/#avc:denied{set}forproperty=ctl.console
scontext=u:r:shell:s0tcontext=u:e
Nowthatwehaveverifiedwhatitis,wecanstartitbackup:
$adbshellsetpropctl.startconsole
Withthesystembackinaworkingstate,wenowneedtoaddressthebestwaytocorrect
thelabelonthisservice.Wehavetwooptions:
Usinganexplicitseclabelentryininit.rc
Usingatypetransition
Theoptionwewillusehereisthefirst.Thereasonisbecauseinitexecutesshellfromtime
totime,andwedon’twantalloftheseintheconsoleprocessesdomain.Wewantleast
privilegetosegregatetherunningprocesses.Byusingtheexplicitseclabel,wewon’t
changeanyoftheothershellsthatareexecutedalongtheway.
Todothis,weneedtomodifytheinit.rcentryforconsole;add:
serviceconsole/system/bin/sh
classcore
console
userroot
grouproot
seclabelu:r:shell:s0
Theproperdomainforthisexecutableisshell,sinceitshouldhavethesamepermission
setasadbshell.Afteryoumakethischange,recompilethebootimage,flash,andthen
reboot.Wecanseethatitisnowinashelldomain.Toverify,executethefollowingfroma
UDOOserialconnection:
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.Thewatchdogdprocessalreadyhasa
domainandallowsrulesinwatchdog.te;sowejustneedtoaddaseclabelstatementand
getitintothisproperdomain.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.Agoodteaching
examplewouldhavesubshellsfromashellintheirowndomain.Let’sstartbydefininga
newdomainandsettingupthetransition.
Wewillcreateanew.tefileinsepolicycalledsubshell.te,andedititsothatits
contentscontainthefollowing:
typesubshell,domain,shelldomain,mlstrustedsubject;
#domain_auto_trans(olddomain,type,newdomain)
#Automaticallytransitionfromolddomaintonewdomain
#uponexecutingafilelabeledwithtype.
#
domain_auto_trans(shell,shell_exec,subshell)
Now,themmmtrickusedearlierinthebookcanbeusedtocompilejustthepolicyAlso,use
adbpushcommandtopushthenewpolicyto/data/security/current/sepolicyand
executesetproptoreloadthepolicy,justaswedidinChapter8,ApplyingContextsto
Files.
Totestthis,weshouldbeabletotypesh,andverifythedomaintransition.Wewillstart
bygettingourcurrentcontext:
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.Ifyou
couplethiswithlabelingfiles,aspresentedinChapter8,ApplyingContextstoFiles,you
www.it-ebooks.info
haveapowerfultooltocontrolprocesspermissions.
www.it-ebooks.info
www.it-ebooks.info
Limitationsonapplabeling
Afundamentallimitationofthesedynamicprocesstransitionsisthattheyrequirean
exec()systemcalltobemade.OnlythencanSELinuxcomputethenewdomain,and
triggerthecontextswitch.Theonlyotherwaytodothisisbymodifyingthecode,which
essentiallyiswhatinitisdoingwhenyouspecifyseclabel().Theinitcodesetstheexec
contextforitsprocess,causingthenextexectoendupinthespecifieddomain.Infact,we
canseethisintheinit.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()beforethe
exec()systemcallhandsovercontroltoanewbinaryimage.InAndroid,applicationsare
notspawnedthisway,andnoexec()syscallexistsintheprocesscreationpath;soanew
mechanismwillbeneeded.
www.it-ebooks.info
www.it-ebooks.info
Summary
Inthischapter,welearnedhowtolabelprocessesviatypetransitionsaswellasviathe
seclabelstatements.Wealsoinvestigatedhowinitmanagesservicesockets,andhowto
properlylabelthem.Wethencorrectedtheprocesscontextsfortheserialconsoleaswell
asthewatchdogdaemon.
ApplicationsinAndroidneverhaveanexplicitcalltoexec()tostarttheirprogram
execution.Sincethereisnoexec(),wehavetolabelapplicationswithacodechange.In
thenextchapter,wewilladdresshowthishappens,andhowapplicationsgetlabeled.
www.it-ebooks.info
www.it-ebooks.info
Chapter10.PlacingApplicationsin
Domains
InChapter3,AndroidIsWeird,weintroducedthezygoteandthatallapplications,APKs
inAndroidspeak,emanatefromthezygotejustlikeservicesemanatefromtheinit
process.Assuch,theyneedtobelabeled,aswedidinthepreviouschapter.Recallthat
labelingisthesameasplacingaprocessinadomainofthatlabel.Applicationsneedtobe
labeledaswell.
Note
APKisthefileextensionandformatforinstallableapplicationpackagesonAndroid.It’s
analogoustothedesktoppackageformatslikeRPM(Redhatbased)orDEB(Debian
based).
Inthischapter,wewilllearnto:
Properlylabelapplicationprivatedatadirectoriesandtheirruntimecontexts
Furtherexaminezygoteandmethodstosecureit
Discoverhowafinishedmac_permssions.xmlfileassignsseinfovalue
Createanewcustomdomain
www.it-ebooks.info
Thecasetosecurethezygote
Androidapplicationswithelevatedpermissionsandcapabilitiesarespawnedfromthe
zygote.Anexampleofthisisthesystemserver,alargeprocesscomprisedofnativeand
non-nativecodehostingavarietyofservices.Thesystemserverhousestheactivity
manager,packagemanager,GPSfeedsandsoon.Thesystemserveralsorunswitha
highlysensitiveUIDofsystem(1000).Also,manyOEMspackagewhatareknownas
systemapps,whicharestandaloneapplicationsrunningwiththesystemUID.
Thezygotealsospawnsapplicationsthatdonotneedelevatedpermissions.Allthird-party
applicationsrepresentthis.ThirdpartyapplicationsrunastheirownUID,separatefrom
sensitiveUIDs,suchassystem.Additionally,applicationsgetspawnedintovariousUIDs
suchasmedia,nfc,andsoon.OEMstendtodefineadditionalUIDs.
It’simportanttonotethattogetintoaspecialUID,likesystem,youmustbesignedwith
theproperkey.Androidhasfourmajorkeysusedtosignapplications:media,platform,
shared,andtestkey.Theyarelocatedinbuild/target/product/security,alongwitha
README.
AccordingtotheREADME,thekeyusageisasfollows:
testkey:Agenerickeyforpackagesthatdonototherwisespecifyakey.
platform:Atestkeyforpackagesthatarepartofthecoreplatform.
shared:Atestkeyforthingsthataresharedinthehome/contactsprocess.
media:Atestkeyforpackagesthatarepartofthemedia/downloadsystem.
InordertorequestsystemUIDforyourapplication,youmustbesignedwiththe
platformkey.Possessionoftheprivatekeyisrequiredtoexecuteinthesemoreprivileged
environments.
Asyoucansee,wehaveapplicationsexecutingatavarietyofpermissionlevels,andtrust
levels.Wecannottrustthirdpartyapplicationssincetheyarecreatedbyunknownentities,
andwecantrustthingssignedwithourprivatekeys.However,beforeSELinux,
applicationpermissionswerestillboundbythesameDACpermissionlimitationsasthose
identifiedinChapter1,LinuxAccessControls.Becauseoftheseproperties,itmakesthe
zygoteaprimetargetforattack,aswellasfortificationwithSELinux.
www.it-ebooks.info
www.it-ebooks.info
Fortifyingthezygote
Nowthatwehaveidentifiedaproblemwithzygote,thenextstepisunderstandinghowto
getapplicationsintoappropriatedomains.WeneedeitherSELinuxpolicyorcodechanges
toplacenewprocessesintoadomain.InChapter9,AddingServicestoDomains,we
covereddynamicdomaintransitionswithinit-basedservicesandtheendofthechapter
mentionstheimportanceoftheexec()syscallinthe“LimitationsonAppLabeling”
section.Thisisthetriggeronwhichdynamicdomaintransitionsoccur.Ifthereisnoexec
inthepath,wewouldhavetorelyoncodechanges.However,onealsohastoconsiderthe
signingkeyinthissecuritymodel,andthereisnowayinpureSELinuxpolicylanguageto
expressthekeytheprocesswassignedwith.
Ratherthanexploringthewholezygote,wecandissectthefollowingpatchesthat
introduceapplicationlabelingintoAndroid.Additionally,wecandiscoverhowthe
introduceddesignmeetstherequirementsofrespectingthesigningkey,workingwithin
thedesignofSELinuxandthezygote.
www.it-ebooks.info
Plumbingthezygotesocket
InChapter3,AndroidIsWeird,welearnedthatthezygotelistensforrequeststospawna
newapplicationfromasocket.Thefirstpatchtoexamineishttps://androidreview.googlesource.com/#/c/31066/.Thispatchmodifiesthreefilesinthebase
frameworksofAndroid.ThefirstfileisProcess.javainthemethodstartViaZygote().
Thismethodisthemainentrypointforothermethodswithrespecttobuildingstring
argumentsandpassingthemtothezygotewithzygoteSendArgsAndGetResult().The
patchintroducesanewargumentcalledseinfo.Lateron,wewillseehowthisgetsused.
Itappearsthatthispatchisplumbingthisnewseinfoargumentoverthesocket.Notethat
thiscodeiscalledexternaltothezygoteprocess.
ThenextfiletolookatinthispatchisZygoteConnection.java.Thiscodeexecutesfrom
withinthecontext.Thepatchstartsoffbydeclaringastringmembervariable
peerContextintheZygoteConnectionclass.Intheconstructor,thispeerContext
memberissettothevalueobtainedfromacallto
SELinux.getPeerContext(mSocket.getFileDescriptor()).
SincetheLocalSocketmSocketisaUnixdomainsocketunderthehood,youcanobtain
theconnectedclient’scredentials.Inthiscase,thecalltogetPeerContext()getsthe
client’ssecuritycontext,orinmoreformalterms,theprocesslabel.Aftertheinitialization,
furtherdowninmethodrunOnce(),weseeitbeingusedincallsto
applyUidSecurityPolicyandotherapply*SecurityPolicyroutines.Theprotected
methodrunOnce()iscalledtoreadonestartcommandfromthesocketandarguments.
Eventually,aftertheapply*SecurityPolicychecks,itcallsforkandSpecialize().Each
securitypolicycheckhasbeenmodifiedtouseSELinuxontopoftheexistingDAC
securitycontrols.IfwereviewapplyUidSecurityPolicy,weseetheymakethecall:
booleanallowed=SELinux.checkSELinuxAccess(peerSecurityContext,
peerSecurityContext,"zygote","specifyids");
Thisisanexampleofauserspaceleveragingmandatoryaccesscontrolsinwhatisknown
asanobjectmanager.Additionally,asecuritycheckhasbeenaddedforthemysterious
seinfostringintheapplyseInfoSecurityPolicy()method.Allthesecuritycheckshere
forSELinuxspecifythetargetclasszygote.Soifwelookintosepolicy
access_vectors,weseetheaddedclasszygote.ThisisacustomclassforAndroidand
definesallthevectorscheckedinthesecuritychecks.
Thelastfilewe’llconsiderfromthispatchisActivityManagerService.java.The
ActivityManagerisresponsibleforstartingapplicationsandmanagingtheirlifecycles.
It’saconsumeroftheProcess.startAPIandneedstospecifyseinfo.Thispatchis
simple,andfornow,justsendsnull.Later,wewillseethepatchenablingitsuse.
Thenextpatch,https://android-review.googlesource.com/#/c/31063/,executeswithinthe
contextoftheAndroidDalvikVMandiscodedintheVMzygoteprocessspace.The
forkAndSpecialize()wesawinZygoteConnectionendsupinthisnativeroutine.It
entersusingstaticpid_tforkAndSpecializeCommon(constu4*args,bool
isSystemServer).Thisroutineisresponsibleforcreatingthenewprocessthatbecomes
www.it-ebooks.info
theapplication.
ItbeginswithhousekeepingcodemovingfromJavatoCandsetsuptheniceNameand
seinfovaluesasC-stylestrings.Eventually,thecodecallsfork()andthechildprocess
startsdoingthings,likeexecutingsetgidandsetuid.Theuidandgidvaluesare
specifiedtothezygoteconnectionwiththeProcess.startmethod.Wealsoseeanew
calltosetSELinuxContext().Asanaside,theorderoftheseeventsisimportanthere.If
yousettheSELinuxcontextofthenewprocesstooearly,theprocesswouldneed
additionalcapabilitiesinthenewcontexttodothingslikesetuidandsetgid.However,
thosepermissionsarebestlefttothezygotedomain,sotheapplicationdomainweentered
canbeasminimalaspossible.
Continuing,setSELinuxContexteventuallycallsselinux_android_setcontext().Note
thattheHAVE_SELINUXconditionalcompilationmacroswereremovedafterthiscommit,
butpriortothe4.3release.Alsonotethatselinux_android_setcontext()isdefinedin
libselinux,soourjourneywilltakeusthere.Hereweseethemysteriousseinfoisstill
beingpassedalong.
Thenextpatchtoevaluateishttps://android-review.googlesource.com/#/c/39601/.This
patchactuallypassesamoremeaningfulseinfovaluefromtheJavalayer.Ratherthan
beingsettonull,thispatchintroducessomeparsinglogicfromanXMLfile,andpasses
thisalongtotheProcess.startmethod.
Thispatchmodifiestwomajorcomponents:PackageManagerandinstalld.
PackageManagerrunsinsidethesystem_server,andperformsapplicationinstallation.It
maintainsthestateofallinstalledpackagesinthesystem.Thesecondcomponent,a
serviceknownasinstalld,isaveryprivilegedrootservicethatcreatesallthe
applications’privatedirectoriesondisk.Ratherthangivingsystemserver,andtherefore
PackageManager,thecapabilitytocreatethesedirectories,onlyinstalldhasthese
permissions.Usingthisapproach,eventhesystemservercannotreaddatainyourprivate
datadirectoriesunlessyoumakeitworldreadable.
Thispatchislargerthantheothers,soweareonlygoingtoinspectthepartsdirectly
relevanttoourdiscussion.We’llstartbylookingatPackageManagerService.java.This
classisthepackagemanager,properforAndroid.Intheconstructorfor
PackageManagerService(),weseetheadditionofmFoundPolicyFile=
SELinuxMMAC.readInstallPolicy();.
Basedonthenaming,wecanconjecturethatthismethodislookingforsometypeof
policyconfigurationfile,andiffound,returnstrue,settingthemFoundPolicyFilemember
variable.WealsoseesomecallstocreateDataDirsandmInstaller.*calls.Thesewe
canignore,sincethosecallsareheadedtoinstalld.
Thenextmajorportionaddsthefollowing:
if(mFoundPolicyFile){
SELinuxMMAC.assignSeinfoValue(pkg);
}
It’simportanttonotethatthiscodewasaddedintothescanPackageLI()method.This
www.it-ebooks.info
methodiscalledeverytimeapackageneedstobescannedforinstallation.Soatahigh
level,ifsomepolicyfileisfoundduringservicestartup,thenaseinfovalueisassignedto
thepackage.
ThenextfiletolookatisApplicationInfo.java,acontainerclassformaintainingmeta
informationaboutapackage.Aswecansee,theseinfovalueisspecifiedhereforstorage
purposes.Additionally,thereissomecodeforserializinganddeserializingtheclassvia
theAndroidspecificParcelimplementation.
Atthispoint,weshouldhaveacloserlookattheSELinuxMMAC.javacodetoconfirmour
understandingofwhat’sgoingon.Theclassstartsbydeclaringtwolocationsforpolicy
files.
//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,weseethecallfrom
PackageManagerServiceinitializationtothemethoddefinedintheclass
readInstallPolicy(),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,thiscodeusesthearraytofindafileat
thespecifiedlocations.Itisprioritybased,withthe/datalocationtakingprecedenceover
/system.Therestofthecodeinthismethodlookslikeparsinglogicandfillsuptwohash
tablesthatweredefinedintheclassdeclaration:
//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.xmlfileand
createinternalmappingsfromsigningkeytoseinfoandpackagenametoseinfo.
TheothercallfromPackageManagerServiceintothisclasscamefromvoid
assignSeinfoValue(PackageParser.Packagepkg).
Let’sinvestigatewhatthismethodcando.Itstartsbycheckingiftheapplicationissystem
UIDorasysteminstalledapp.Inotherwords,itcheckswhethertheapplicationisathirdpartyapplication:
if(((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM)!=0)||
((pkg.applicationInfo.flags&ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)!=
0)){
ThiscodehassubsequentlybeendroppedbyGoogle,andwasinitiallyarequirementfor
merge.Wecan,however,continueourevaluation.Thecodeloopsoverallthesignatures
inthepackage,andchecksagainstthehashtable.Ifitissignedwithsomethinginthat
map,itusestheassociatedseinfovalue.Theothercaseisthatitmatchesbypackage
name.Ineithercase,thepackage’sApplictionInfoclassseinfovalueisupdatedto
reflectthisandbeusedelsewherebyinstalldandzygoteapplicationspawn:
//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,whatismergedintomainlineAOSPandwhatismaintainedintheNSA
Bitbucketrepositoriesisabitdifferent.TheNSAhasadditionalcontrolsinthesepolicy
filesthatcancauseanapplicationinstallationtoabort.GoogleandtheNSAare“forked”
overthisissue,sotospeak.IntheNSAversionsofSELinuxMMAC.java,youcanspecify
thatapplicationsmatchingaspecificsignatureorpackagenameareallowedtohave
www.it-ebooks.info
certainsetsofAndroid-levelpermissions.Forinstance,youcanblockallapplications
frombeinginstalledthatrequestCAMERApermissionsorblockapplicationssignedwith
certainkeys.Thisalsohighlightshowimportantitcanbetofindpatcheswithinlargecode
basesandquicklycomeuptospeedonhowprojectsevolve,whichcanoftenseem
daunting.
ThelastfileinthispatchforustoconsiderisActivityManagerService.java.Thispatch
replacesthenullwithapp.info.seinfo.Afterallthatworkandallthatplumbing,we
finallyhavethemysticalseinfovaluefullyparsed,associatedperapplicationpackage,
andsentalongtothezygoteforuseinselinux_android_setcontext().
Nowitwouldbenefitustositbackandthinkaboutsomeofthepropertieswewantedto
achieveinlabelingapplications.Oneofthemistosomehowcoupleasecuritycontext
withtheapplicationsigningkey,andthisispreciselythemainbenefitofseinfo.Thisisa
highlysensitiveandtrustedstringassociatedvalueofasigningkey.Theactualcontentsof
thestringarearbitraryanddictatedinmac_permissions.xml,whichisthenextstopon
ouradventure.
www.it-ebooks.info
Themac_permissions.xmlfile
Themac_permissions.xmlfilehasaveryconfusingname.Expanded,thenameisMAC
permissions.However,itsmajormainlinefunctionalityistomapasigningkeytoa
seinfostring.Secondarily,itcanalsobeusedtoconfigureanon-mainstreaminstall-time
permission-checkingfeature,knownasinstalltimeMMAC.MMACcontrolsarepartof
theNSA’sworktoimplementmandatoryaccesscontrolsinthemiddlewarelayer.MMAC
standsfor“MiddlewareMandatoryAccessControls”.Googlehasnotmergedanyofthe
MMACfeatures.However,sinceweusedtheNSABitbucketrepositories,ourcodebase
containsthesefeatures.
Themac_permissions.xmlisanXMLfile,andshouldadheretothefollowingrules,
whereitalicizedportionsareonlysupportedonNSAbranches:
AsignatureisahexencodedX.509certificateandisrequiredforeachsignertag.
A<signersignature="">elementmayhavemultiplechildelements:
allow-permission:Itproducesasetofmaximalallowedpermissions
(whitelist)
deny-permission:Itproducesablacklistofpermissionstodeny
allow-all:Itisawildcardtagthatwillalloweverypermissionrequested
package:Itisacomplextagwhichdefinesallow,deny,andwildcardsub-
elementsforaspecificpackagenameprotectedbythesignature
Zeroormoreglobal<packagename="">tagsareallowed.Thesetagsallowapolicy
tobesetoutsideanysignatureforspecificpackagenames.
A<default>tagisallowedthatcancontaininstallpolicyforallappsnotsignedwith
apreviouslylistedcertandnothavingaperpackageglobalpolicy.
Unknowntagsatanylevelareskipped.
Zeroormoresignertagsareallowed.
Zeroormorepackagetagsareallowedpersignertag.
A<packagename="">tagmaynotcontainanother<packagename="">tag.If
found,it’sskipped.
Whenmultiplesub-elementsappearforatag,thefollowinglogicisusedto
ultimatelydeterminethetypeofenforcement:
Ablacklistisusedifatleastonedeny-permissiontagisfound.
Awhitelistisused,ifnotablacklist,andatleastoneallow-permissiontagis
found.
Awildcard(acceptallpermissions)policyisusedifnotablacklistandnota
whitelist,andatleastoneallow-alltagispresent.
Ifa<packagename="">sub-elementisfound,thenthatsub-element’spolicyis
usedaccordingtotheearlierlogicandoverridesanysignatureglobalpolicy
type.
Inorderforapolicystanzatobeenforced,atleastoneofthepreceding
situationsmustapply.Meaning,emptysigner,defaultorpackagetagswillnot
beaccepted.
www.it-ebooks.info
Eachsigner/default/package(globalorattachedtoasigner)tagisallowedto
containone<seinfovalue=""/>tag.Thistagrepresentsadditionalinfothateach
appcanuseinsettinganSELinuxsecuritycontextontheeventualprocess.
StrictenforcingofanyXMLstanzaisnotenforcedinmostcases.Thismainly
appliestoduplicatetags,whichareallowed.Intheeventthatatagalreadyexists,the
originaltagisreplaced.
Therearealsonochecksonthevalidityofpermissionnames.Althoughvalid
Androidpermissionsareexpected,nothingpreventsunknowns.
Followingaretheenforcementdecisions:
Allsignaturesusedtosignanapparecheckedforpolicyaccordingtosigner
tags.However,onlyoneofthesignaturepolicieshastopass.
Intheeventthatnoneofthesignaturepoliciespass,ornoneevenmatch,thena
globalpackagepolicyissought.Iffound,thispolicymediatestheinstall.
Thedefaulttagisconsultedlast,ifneeded.
Alocalpackagepolicyalwaysoverridesanyparentpolicy.
Ifnoneofthecasesapply,thentheappisdenied.
ThefollowingexamplesignoretheInstallMMACsupportandfocusonthemainline
usageofseinfomapping.Thefollowingisanexampleofstanzamappingallthings
signedwiththeplatformkeytoseinfovalueplatform:
<!--PlatformdevkeyinAOSP-->
<signersignature="@PLATFORM">
<seinfovalue="platform"/>
</signer>
Hereisanexamplemappingallthingssignedwiththereleasekeytothereleasedomain
withtheexceptionofthebrowser.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@RELEASEarespecialprocessing
stringsusedduringbuild.Anothermappingfilemapsthesetoactualkeyvalues.Thefile
thatisprocessedandplacedontothedevicehasallkeyreferencesreplacedwithhex
encodedpublickeysratherthantheseplaceholders.Italsohasallwhitespaceand
www.it-ebooks.info
commentsstrippedtoreducesize.Let’stakealookbypullingthebuiltfilefromthe
deviceandformattingit.
$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.ThishexstringisavalidX509
certificate.
www.it-ebooks.info
keys.conf
Theactualmagicdoingthemappingfromsignature=@PLATFORMin
mac_permissions.xmliskeys.conf.Thisconfigurationfileallowsyoutomapapem
encodedx509toanarbitrarystring.Theconventionistostartthemwith@,butthisisnot
enforced.TheformatofthefileisbasedonthePythonconfigparserandcontainssections.
Thesectionnamesarethetagsinthemac_permissions.xmlfileyouwishtoreplacewith
keyvalues.Theplatformexampleis:
[@PLATFORM]
ALL:$DEFAULT_SYSTEM_DEV_CERTIFICATE/platform.x509.pem
InAndroid,whenyoubuild,youcanhavethreelevelsofbuilds:engineering,
userdebug,oruser.Inthekeys.conffile,youcanassociateakeytobeusedforalllevels
withthesectionattributeALL,oryoucanassigndifferentkeysperlevel.Thisishelpful
whenbuildingreleaseoruserbuildswithveryspecialreleasekeys.Weseeanexampleof
thisinthe@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$special
character.Thedefaultlocationforthepemfilesisbuild/target/product/security.
However,youshouldneverusethesekeysforauserreleasebuild.Thesekeysarethe
AOSPtestkeysandarepublic!Bydoingso,anyonecanusethesystemkeytosigntheir
appandgainsystemprivilege.Thekeys.conffileisonlyusedduringthebuildandisnot
locatedonthesystem.
www.it-ebooks.info
seapp_contexts
Sofar,wehavelookedathowafinishedmac_permssions.xmlfileassignstheseinfo
value.Nowweshouldaddresshowthelabelingisactuallyconfiguredandutilizesthis
value.Thelabelingofapplicationsismanagedinanotherconfigurationfile,
seapp_contexts.Likemac_permissions.xml,itisloadedtothedevice.However,the
defaultlocationis/seapp_contexts.Theformatofseapp_contextsisthekey=value
pairmappingsperline,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=false
Specifieduser=stringbeforeunspecifieduser=string
Fixedtheuser=stringbeforetheuser=prefix(endingin*)
Longeruser=prefixbeforeshorteruser=prefix
Specifiedseinfo=stringbeforeunspecifiedseinfo=string.
Specifiedname=stringbeforeunspecifiedname=string.
Specifiedsebool=stringbeforeunspecifiedsebool=string.
Outputs:
domain(string):Itspecifiestheprocessdomainfortheapplication.
type(string):Itspecifiesthedisklabelfortheapplications’privatedata
directory.
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()and
selinux_android_setfilecon2()functionstolookuptheproperapplicationdomainor
filesystemcontext,respectively.Thesourceforthesecanbefoundin
external/libselinux/src/android.candarerecommendedreads.Forexample,this
entryplacesallapplicationswithUIDbluetoothinthebluetoothdomainwithadata
directorylabelofbluetooth_data_file:
user=bluetoothdomain=bluetoothtype=bluetooth_data_file
Thisexampleplacesallthirdpartyor“default”applicationsintoaprocessdomainof
untrusted_appandadatadirectoryofapp_data_file.ItadditionallyusesMLS
categoriesoflevelFrom=apptohelpprovideadditionalMLS-basedseparations.
user=_appdomain=untrusted_apptype=app_data_filelevelFrom=app
Currently,thisfeatureisexperimentalasthisbreakssomeknownapplication
compatibilityissues.Atthetimeofthiswriting,thiswasahotitemoffocusforboth
GoogleandNSAengineers.Sinceitisexperimental,let’svalidateitsfunctionalityand
thendisableit.
Wehavenotinstalledanythirdpartyapplicationsyet,sowe’llneedtodosoinorderto
experiment.FDroidisausefulplacetofindthirdpartyapplications,solet’sdownload
somethingfromthereandinstallit.Wecanusethe0xbenchmarkapplicationlocatedat
https://f-droid.org/repository/browse/?fdid=org.zeroxlab.zeroxbenchmarkwithanAPKat
https://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
Tip
Checklogcatfortheinstalltimeseinfovalue:
$adblogcat|grepSELinux
I/SELinuxMMAC(2557):package(org.zeroxlab.zeroxbenchmark)installedwith
seinfo=default
FromyourUDOO,launchthe0xbenchmarkAPK.Weshouldseeitrunningwithitslabel
inps:
$adbshellps-Z|grepuntrusted
u:r:untrusted_app:s0:c40,c256u0_a40178902285org.zeroxlab.zeroxbenchmark
Noticethelevelportionofthecontextstrings0:c40,c256.Thesecategorieswerecreated
withthelevel=appsettingfromseapp_contexts.
www.it-ebooks.info
Todisableit,wecouldsimplyremovethekey-valuepairforlevelfromtheentryin
seapp_contexts,orwecouldleveragetheseboolconditionalassignment.Let’susethe
Booleanapproach.Modifythesepolicyseapp_contextsfilesotheexisting
untrusted_appentryismodified,andanewoneisadded.Changeuser=_app
domain=untrusted_apptype=app_data_filetouser=_appsebool=app_level
domain=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,therewasabuilderrorcomplainingaboutnotfindingtheselinuxBooleanonline
42ofseapp_contexts.Let’sattempttocorrecttheissuebydeclaringtheBoolean.In
app.te,add:boolapp_levelfalse;.Nowpushthenewlybuiltseapp_contextsand
sepolicyfiletothedeviceandtriggeradynamicreload:
$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,wediscoveredthesourceoftheissueisthatthe
path/data/securityisnotworldsearchable,causingaDACpermissionsfailure.
Note
Wefoundthisbyprintingofftheresultanderrorcodesinandroid.cwherewesawthe
fopenonseapp_contexts_file[]array(filesinpriorityorder)whilecheckingtheresult
offp=fopen(seapp_contexts_file[i++],"r")in
selinux_android_seapp_context_reload()andusingselinux_log()todumpthedata
tologcat.
$adbshellls-la/data|grepsecurity
drwx------systemsystem1970-01-0400:22security
www.it-ebooks.info
RememberthesetselinuxcontextoccursaftertheUIDswitch,soweneedtomakeit
searchableforothers.WecanfixthepermissionsontheUDOOinit.rcscriptby
changingdevice/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_contextstodisable
theMLScategories.It’simportanttonotethatwhenchangingcategoriesortypeson
APKs,itisrequiredtoremoveandinstalltheAPK,oryouwillorphantheprocessfromits
datadirectorybecauseitwon’thaveaccesspermissionsundermostcircumstances.
Next,let’stakethisAPK,uninstallit,andassignitauniquedomainbychangingits
seinfostring.Typically,youusethisfeaturetotakeasetofapplicationssignedwitha
commonkeyandgetthemintoacustomdomaintodocustomthings.Forexample,if
you’reanOEM,youmayneedtoallowcustompermissionstothirdpartyapplicationsthat
arenotsignedwithanOEMcontrolledkey.StartbyuninstallingtheAPK:
$adbuninstallorg.zeroxlab.zeroxbenchmark
Createanewentryinmac_permissions.xmlbyadding:
<signersignature="@BENCHMARK">
<allow-all/>
<seinfovalue="benchmark"/>
</signer>
Nowweneedtogetapemfileforkeys.conf.SounpackagetheAPKandextractthe
publiccertificate:
$mkdirtmp
$cdtmp
$unzip~/org.zeroxlab.zeroxbenchmark_9.apk
$cdMETA-INF/
$$opensslpkcs7-informDER-in*.RSA-outCERT.pem-outformPEMprint_certs
We’llhavetostripanycruftfromthegeneratedCERT.pemfile.Ifyouopenitup,you
shouldseetheselinesatthetop:
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.Thefileshouldstart
withBEGINCERTIFICATEandendwithENDCERTIFICATEscissorlines.
www.it-ebooks.info
Let’smovethistoanewfolderinourworkspacecalledcertsandmovethecertificate
intothisfolderwithabettername:
$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.Thedomaintypeshouldbedeclaredinafilecalled
benchmark_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;
Tip
Youmaynotalwayswantalloftheseattributes,especiallyifyou’redoingsomething
securitycritical.Makesureyoulookateachattributeandmacroandseeitsusage.You
don’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?
Theproblemisin
frameworks/base/services/java/com/android/server/pm/SELinuxMMAC.java.Itlooks
in/data/security/mac_permissions.xml;sowecanjustpushmac_permissions.xml.
Thisisanotherbuginthedynamicpolicyreloadandhastodowithhistoricalchangesin
thisloadingprocedure.Theculpritiswithinthe
frameworks/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.Uninstallandreinstallthe
benchmarkAPK,andcheckthelogs:
I/SELinuxMMAC(2564):package(org.zeroxlab.zeroxbenchmark)installedwith
seinfo=default
OK.Itstilldidn’twork.Whenweexaminedthecode,themac_permissions.xmlfilewas
loadedduringpackagemanagerservicestart.Thisfilewon’tgetreloadedwithouta
reboot,solet’suninstallthebenchmarkAPK,andreboottheUDOO.Afterit’sbeen
bootedandadbisenabled,triggeradynamicreload,installtheAPK,andchecklogcat.It
shouldhave:
I/SELinuxMMAC(2559):package(org.zeroxlab.zeroxbenchmark)installedwith
seinfo=benchmark
Nowlet’sverifytheprocessdomainbylaunchingtheAPK,checkingps,andverifyingits
applicationprivatedirectory:
<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
www.it-ebooks.info
Summary
Inthischapter,weinvestigatedhowtoproperlylabelapplicationprivatedatadirectories
aswellastheirruntimecontextsviatheconfigurationfilesandSELinuxpolicy.Wealso
lookedintothesubsystemsandcodetomakeallofthisworkaswellassomebasicthings
thatmaygowrongalongtheway.Inthenextchapter,wewillexpandonhowthepolicy
andconfigurationfilesgetbuiltbypeeringintotheSEforAndroidbuildsystem.
www.it-ebooks.info
www.it-ebooks.info
Chapter11.LabelingProperties
Inthischapter,wewillcoverhowtolabelpropertiesviatheproperty_contextsfile.
PropertiesareauniqueAndroidfeaturewelearnedaboutinChapter3,AndroidIsWeird.
Wewanttolabelthesetorestrictsettingofourpropertiestoonlythedomainsthatshould
setthem,preventingaclassicDACrootattackfrominadvertentlychangingthevalue.In
thischapter,wewilllearnto:
Createnewproperties
Labelnewandexistingproperties
Interpretanddealwithpropertydenials
EnumeratespecialAndroidpropertiesandtheirbehaviors
www.it-ebooks.info
Labelingviaproperty_contexts
Allpropertiesarelabeledusingtheproperty_contextsfile,anditssyntaxissimilarto
file_contexts.However,insteadofworkingonfilepaths,itworksonpropertynamesor
propertykeys(propertiesinAndroidareakey-valuestore).Thepropertykeysthemselves
aretypicallydelimitedwithperiods(.).Thisisanalogoustofile_contexts,exceptthe
slash(/)becomesaperiod.Somesamplepropertiesandtheirentriesin
property_contextswouldlooklikethefollowing:
ctl.ril-daemonu:object_r:ctl_rildaemon_prop:s0
ctl.u:object_r:ctl_default_prop:s0
Noticehowallctl.propertiesarelabeledwiththectl_default_proptype,butctl.rildaemonhasadifferenttypelabelofctl_rildaemon_prop.Thesearerepresentativeofhow
youcanstartgenericallyandmovetomorespecificvalues/typesasnecessary.
Additionally,anythingnotexplicitlylabeleddefaultstodefault_propthrougha“match
all”expressioninproperty_contexts:
#defaultpropertycontext
*u:object_r:default_prop:s0
www.it-ebooks.info
www.it-ebooks.info
Permissionsonproperties
Onecanviewthecurrentpropertiesonthesystem,andcreatenewoneswiththecommand
lineutilitiesgetpropandsetprop,asshowninthefollowingcodesnippet:
root@udoo:/#getprop
...
[sys.usb.state]:[mtp,adb]
[wifi.interface]:[wlan0]
[wlan.driver.status]:[unloaded]
RecallfromChapter3,AndroidIsWeird,thatpropertiesaremappedintoeveryone’s
addressspace,thusanyonecanreadthem.However,noteveryonecanset(write)them.
TheDACpermissionmodelforpropertiesishardcodedinto
system/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_permsarraytosetanypropertythatthe
prefixmatcheswith.Forinstance,inordertosettheselinux.properties,youmustbe
UIDAID_SYSTEM(uid1000)orroot.Yes,rootcanalwayssetaproperty,andthisisakey
benefittoapplyingSELinuxtoAndroidproperties.Unfortunately,thereisnowayto
getprop-Ztolistthepropertiesandtheirlabels,likewithls-Zandfiles.
www.it-ebooks.info
www.it-ebooks.info
Relabelingexistingproperties
Inordertobecomemorecomfortablewithlabelingproperties,let’srelabelthe
wifi.interfaceproperty.First,let’sverifyitscontextbycausingadenialandviewing
thedeniallog,asshowninthefollowingcode:
root@udoo:/#setpropwifi.interfacewlan0
avc:denied{set}forproperty=wifi.interfacescontext=u:r:shell:s0
tcontext=u:object_r:default_prop:s0tclass=property_service
AninterestingactionoccurredwhenweexecutedthesetpropcommandovertheUDOO
serialconsole.TheAVCdenialrecordwasprintedout.Thisisbecausetheserialconsole
includesanythingprintedfromthekernelusingprintk().Whathappenshereistheinit
process,whichcontrolssetpropsasdetailedinChapter3,AndroidIsWeird,writesa
messagetothekernellog.Thislogmessageshowsupwhenweexecuteoursetprop
command.Ifyourunthisthroughadbshell,you’llseethemessageontheserialconsole,
butnotintheadbconsole.Todothis,however,youmustrebootyoursystembecause
SELinuxonlyprintsdenialrecordsoncewhileinpermissivemode.
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’s
changethistowifi_prop.
Westartbyeditingproperty.teinthesepolicydirectorytodeclarethenewtypeto
labelthesepropertiesbyappendingthefollowingline:
typewifi_prop,property_type;
Withthetypedeclared,thenextstepistoapplythelabelbymodifying
property_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.Thereisnomentionof
property_contextsinthisfile;thus,itmustbementionedelsewhere.Thisleadsusto
searchsystem/core,whichcontainsthepropertyserviceforusesofthatfile.Thematches
areoncodeininit.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.Thisexercisewasmeanttopointouthowtrickythiscanbeif
youforgettodosomething.Noinformativedenialmessagesweredisplayed,onlyan
indicatorthatitwasdenied.Thisisbecausethesepolicyfilethatcontainsthetype
declarationforwifi_propwasneverpushed.Thiscausescheck_mac_perms()in
system/core/init/property_service.ctofailintheselinux_check_access()function
becauseitcannotfindthetypetocomputetheaccesscheckagainst,eventhoughthelook
upinproperty_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)is
u:object_r:wifi_prop:s0.
Nowwiththetargetpropertylabeled,youcanallowaccesstoit.Notethatthisisa
contrivedexample,andintherealworld,youprobablywouldnotwanttoallowaccess
fromshelltomostproperties.Thepolicyshouldalignwithyoursecuritygoalsandthe
propertyofleastprivilege.
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
www.it-ebooks.info
Creatingandlabelingnewproperties
Allpropertiesaredynamicallycreatedinthesystemusingsetpropcallsorfunctioncalls
thatdotheequivalentfromC(bionic/libc/include/sys/system_properties.h)and
Java(android.os.SystemProperties).NotethattheSystem.getProperty()and
System.setProperty()Javacallsworkonapplicationprivatepropertystoresandarenot
tiedintotheglobalone.
ForDACcontrols,youneedtomodifyproperty_perms[]asnotedearliertohave
permissionsfornon-rootuserstocreateorsettheproperty.Notethatrootcanalwaysset
andcreate,unlessconstrainedbySELinuxpolicy.
Supposewewanttocreatetheudoo.nameandudoo.ownerproperties;weonlywantthe
rootuserandshelldomaintoaccessthem.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,wewould
relabelthese,exactlyaswedidintheprecedingsection,Relabelingexistingproperties.
www.it-ebooks.info
www.it-ebooks.info
Specialproperties
InAndroid,therearesomespecialpropertiesthathavedifferentbehaviors.Weenumerate
thepropertynamesandmeaningsintheproceedingsections.
www.it-ebooks.info
Controlproperties
Propertiesthatstartwithctlarereservedascontrolpropertiesforcontrollingservices
throughinit:
start:Startsaservice(setpropctl.start<servicename>)
stop:Stopsaservice(setpropctl.stop<servicename>)
restart:Restartsaservice(setpropctl.restart<servicename>)
www.it-ebooks.info
Persistentproperties
Anypropertystartingwiththeprefixpersistpersistsacrossrebootsandisrestored.The
dataissavedto/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
SELinuxproperties
Theselinux.reload_policypropertyisspecial.Aswehaveseen,itsuseisfortriggering
adynamicreloadevent.
www.it-ebooks.info
www.it-ebooks.info
Summary
Inthischapter,wehaveexaminedhowtocreateandlabelnewandexistingpropertiesand
someoftheodditiesthatoccurwhendoingso.Wehavealsoexaminedthehardcoded
DACpermissiontableforpropertiesinproperty_service.c,aswellasthehardcoded
specialtypropertieslikethectl.family.Inthenextchapter,welookathowthetoolchain
buildsandcreatesallthepolicyfileswehavebeenusing.
www.it-ebooks.info
www.it-ebooks.info
Chapter12.MasteringtheToolChain
Sofar,wehavetakenadeepdiveintothecodeandpoliciesthatdriveSEforAndroid
technologies,butthebuildsystemandtoolsareoftenoverlooked.Masteringthetoolchain
willhelpyouimproveyourdevelopmentpractices.Inthischapter,wewilllookatallthe
componentsoftheSEforAndroidbuildandhowtheywork.Wewillcoverthefollowing
topics:
Buildingspecifictargets
ThesepolicyAndroid.mkfile
Custombuildpolicyconfiguration
Buildtools:
check_seapp
insertkeys.py
checkpolicy
checkfc
sepolicy-check
sepolicy-analyze
www.it-ebooks.info
Buildingsubcomponents–targetsand
projects
Sofar,wehaverunsomemagicalcommandssuchasmm,mmm,andmakebootimageto
actuallybuildvariousportionsoftheSEforAndroidcode.Googleofficiallydescribes
someofthesetoolsinthedocumentsathttps://source.android.com/source/buildingrunning.html,butmostcommandsarenotlisted.Nonetheless,
http://elinux.org/Android_Build_Systemhasawriteupthatismorecomprehensive.
InGoogle’s“buildingandrunning”documentation,theydescribethetargetasthedevice,
whichisultimatelywhatyoulunchfor.WhenbuildingAndroid,thelunchcommandsets
upenvironmentvariablesforthemakecommandyouexecutelater.Itsetsupthebuild
systemtooutputthecorrectconfigurationforthetargetdevice.Thisconceptofatargetis
notwhatwillbediscussedinthischapter.Instead,whentargetismentionedherein,it
meansaspecificmaketarget.However,intheeventofneedingtomentionthetarget
device,thecompletephrase“targetdevice”willbeused.Whilesomewhatconfusing,
thisterminologyisstandardandwillbeunderstoodbyengineersinthefield.
Wehaveissuedmakeafewtimes,optionallyprovidingatargetasanargumentandan
option,forexamplethe-j16option.Somethinglikemakeormake-j16essentiallybuilds
allofAndroid.Optionally,youcanspecifyatargetorlistoftargetsascommand
arguments.Anexampleofthisiswhenboot.imgwasbuilt.Theboot.imgfilecanbebuilt
andrebuiltbyspecifyingthebootimagetarget.Thecommandweuseforthispurposeis
makebootimage.Ithelpstoexpeditebuildsbyrebuildingonlytheportionsofthesystem
thatareneeded.Butwhatifyouonlyneedtorebuildaparticularfile?Perhaps,youonly
wanttorebuildsepolicy.Youcanspecifythatasthetargettobuild,asinmakesepolicy.
Thisleadstothequestion,“Whatabouttheotherfilessuchasmac_permissions.xml,
seapp_contexts,andsoon?”Theycanbebuiltinthesameway.Themoreintriguing
questionis,“Howdoesoneknowwhatthetargetnameis?Isitalwaysthefileoutput
name?”
Android’sbuildsystemisconstructedontopofGNUmake
(http://www.gnu.org/software/make/).ThecoreoftheAndroidbuildsystem’smakefiles
systemcanbefoundinbuild/core,andthedocumentationcanbefoundintheNDK
(https://developer.android.com/tools/sdk/ndk/index.html).Themajortakeawayfromthat
readingisthatatypicalAndroid.mkfiledefinessomethingcalledLOCAL_MODULE:=
mymodulename,andsomethingcalledmymodulenameisbuilt.Thetargetnamesaredefined
bytheseLOCAL_MODULEstatements.Let’slookattheAndroid.mkforexternalsepolicy,and
focusonthesepolicyportionofit,asthereareotherlocalmodulesortargetsdefinedin
thatMakefile.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.mkfilebyjustlookingforlinesthat
beginwithLOCAL_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,andthegrepmanpage
statesthat-wprovideswholewordsearch.
TheprecedinglistiscomprehensivefortheversionofAndroidweareusingonthe
UDOO.However,youshouldrunthecommandonyourexactversionoftheMakefileto
getanideaofwhatthingscanbebuilt.
Androidhassomeadditionaltoolsthatareseparatefrombuildingtargetsandgetaddedto
yourenvironmentwhenyouusesourcebuild/envsetup.sh.Thesearemmandmmm.They
bothperformthesametask,whichistobuildallthetargetsspecifiedinanAndroid.mk
file,however,differingthattheydonotbuildanyoftheirdependencies.Thetwo
commandsonlydifferinwheretheysourcethelocationoftheAndroid.mktoscourfor
buildtargets.Themmcommandusesthecurrentworkingdirectory,whereasmmmusesa
suppliedpath.Also,agreatoptionforeithercommandis-B,whichforcesarebuild.An
engineercansavealotoftimebyusingthemm(m)commandsovermake<target>.The
fullmakecommandwastesalotoftimefiguringoutthedependencytree,soexecutingmmm
path/to/projectonapreviouslybuiltsourcetree(ifyouknowthatallyourchangesare
withinaproject)cansaveafewminutes.However,sinceitdoesn’tbuildthe
dependencies,you’llneedtoensurethattheyarealreadybuiltandhavenodependent
changes.
www.it-ebooks.info
www.it-ebooks.info
Exploringsepolicy’sAndroid.mk
Theprojectlocatedatexternal/sepolicyusesanAndroid.mkfile,likeanyother
Androidproject,tobuildtheiroutputs.Let’sdissectthisfileandseewhatitdoes.
www.it-ebooks.info
Buildingsepolicy
We’llstartinthemiddlebylookingatthetargetforsepolicy.Itstartsoffwithfairly
boilerplateAndroid.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.Itstartsoffbydeclaringatargetfilethat
getsbuiltintotheintermediateslocation.Theintermediateslocationisdefinedbythe
Androidbuildsystem.ItthenassignsthevaluesofMLS_SENSandMLS_CATStosomelocal
variablesforlateruse.Thelastlineisthemostinteresting.Itusesamakefunction,called
build_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.The
interestingbitsoftherecipearethem4commandandthesedcommand.
Note
Formoreinformationonm4,seehttp://www.gnu.org/software/m4/manual/m4.html,and
formoreinformationonsed,refertohttps://www.gnu.org/software/sed/manual/sed.html.
SELinuxpolicyfilesgetprocessedusingm4.m4isamacroprocessorlanguagethatisoften
usedasafrontendtoacompiler.Them4commandtakessomeofthevaluessuchas
PRIVATE_MLS_SENSandPRIVATE_MLS_CATSandpassesthemthroughasmacrodefinitions.
Thisisanalogoustothegcc-Doption.Itthentakesthedependenciesforthetargetas
inputviathemakeexpansion,$^,andoutputsthemtothetargetnameusingthemake
expansionof$@.Italsotakesthatoutputandgeneratesa.dontauditversion.Thatversion
hasallofthedontauditlinesdeletedfromthepolicyfileusingsed.TheMLSvaluestell
SELinuxhowmanycategoriesandsensitivitiestogenerate.Thesemustbestatically
definedinthepolicyblobthatisloadedintothekernel,asfollows:
...
@mkdir-p$(dir$@)
$(hide)m4-Dmls_num_sens=$(PRIVATE_MLS_SENS)-D
mls_num_cats=$(PRIVATE_MLS_CATS)-s$^>$@
$(hide)sed'/dontaudit/d'$@>$@.dontaudit…
www.it-ebooks.info
Thenextportiondefinestherecipeforbuildingtheactualtarget,namedfrom
LOCAL_MODULE_POLICY,evenifthisisnotobvious.LOCAL_BUILT_MODULEexpandstothe
intermediatefiletobebuilt,sepolicyinthiscase.ItfinallygetscopiedbytheAndroid
buildsystemasLOCAL_INSTALLED_MODULEbehindthescenes.Thistargetdependsonthe
intermediatepolicy.conffileandoncheckpolicy.Itusescheckpolicytotransformthe
m4expandedpolicy.confandpolicy.conf.dontauditintotwosepolicyfiles,sepolicy
andsepolicy.dontaudit.TheactualtoolthatisusedtocompiletheSELinuxstatements
inbinaryformtoloadtothekernelischeckpolicy,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,foruseelsewherewithinthe
Android.mkfile,andclearspolicy.conftoavoidpollutingtheglobalnamespaceofmake,
asshown:
...
built_sepolicy:=$(LOCAL_BUILT_MODULE)
sepolicy_policy.conf:=
...
Additionally,buildingsepolicyalsodependsonthePOLICYVERSvariable,whichis
conditionallyassignedavalueof26ifnotset.Thisisthepolicyversionnumberusedby
checkpolicy,andaswesawearlierinthebook,wehadtooverridethisforourUDOO.
www.it-ebooks.info
Controllingthepolicybuild
Wesawthatthesepolicystatementcallsthebuild_policyfunction.Wealsoseeitsuse
inthatAndroid.mkfileforbuildingsepolicy,file_contexts,seapp_contexts,
property_contexts,andmac_permissions.xml,soitreasonsthatitisfairlyimportant.
Thisfunctionoutputsalistoffullyresolvedpathsusedforpolicyfiles.Thefunctiontakes
asinputsavariableargumentlistoffilenamesandincludesregularexpressionsupport
(note*.teinthebuild_policyfortargetsepolicy).Internally,thatfunctionusessome
magictoallowyoutooverrideorappendtothecurrentpolicybuildwithoutmodifyingthe
external/sepolicydirectorydirectly.ThisismeantforOEMsanddevicebuilderstobe
abletoaugmentpolicytocovertheirspecificdevices.
Whenbuildingapolicy,youcansetthefollowingmakevariables,typicallyinthedevice’s
Makefile,tocontroltheresultingbuild.Thevariablesareasfollows:
BOARD_SEPOLICY_DIRS:Thisisthesearchpathforpotentialpolicyfiles
BOARD_SEPOLICY_UNION:Thisisapolicyfileofnametoappendtoallfileswiththe
samename
BOARD_SEPOLICY_REPLACE:Thisisapolicyfileusedtooverridethebase
external/sepolicypolicyfile
BOARD_SEPOLICY_IGNORE:Thisisusedtoremoveaparticularpolicyfilefromthe
build,givenarepository’srelativepath
UsingtheUDOOasanexample,theproperwaytoauthorapolicywasnevertomodify
external/sepolicybuttocreateadirectoryindevice/fsl/udoo/sepolicy:
$mkdir<PATH>
ThenwemodifytheBoardConfig.mk:
$vimBoardConfig.mk
Next,weaddthefollowinglines:
BOARD_SEPOLICY_DIRS+=device/fsl/udoo/sepolicy
Tip
Beverycarefulwith+=asopposedto:=.Inlargeprojecttrees,someofthesevariables
maybesethigherinthebuildtreebycommonBoardConfigs,andyoucouldwipeout
theirsettings.Typically,thesafestbetis+=.Forfurtherdetails,seeVariableAssignmentin
theGNUmakemanual,athttp://www.gnu.org/software/make/manual/make.html.
Thiswilltellthebuild_policy()functioninAndroid.mktosearchnotonly
external/sepolicybutalsodevice/fsl/udoo/sepolicyforpolicyfiles.
Next,wecancreateafile_contextsfileinthisdirectory,andmoveourchangesfor
labelingtothisdirectorybycreatinganewfile_contextsfilein
device/fsl/udoo/sepolicy.
Afterthis,weneedtoinstructthebuildsystemtocombine,orunion,ourfile_contexts
www.it-ebooks.info
filewiththeoneinexternal/sepolicy.Weaccomplishthisbyaddingthefollowing
statementtotheBoardConfig.mkfile:
BOARD_SEPOLICY_UNION+=file_contexts
Youcandothisforanypolicyfile,evencustomfiles.Itdoesamatchonthefilenameby
basenameonly(nodirectories).Forinstance,ifyouhadawatchdog.terulesfileyou
wantedtoaddtothebasewatchdog.terulesfile,youcouldjustaddwatchdog.te,as
shown:
BOARD_SEPOLICY_UNION+=file_contextswatchdog.te
Thisproducesanewwatchdog.tefileduringthebuildthatunionsyournewruleswiththe
onesfoundinexternal/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’t
havethesamefileappearinUNIONandREPLACE,asit’sambiguous.Youcan’thavemore
thanonespecificationofBOARD_SEPOLICY_REPLACEonthesamepolicyfile.
Supposewehaveahierarchicalbuildoccurringfortwofictitiousdevices,deviceXand
deviceY.Thetwodevices,deviceXanddeviceY,bothinheritBoardConfigCommon.mk
fromdeviceA.DeviceAisnotarealdevice,butsinceXandYsharecommonalities,the
commonbitsarekeptindeviceA.
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,youmightnotwanttheresultingpolicysetfordeviceYtocontain
device/OEM/A/custom.te.ThisisausecaseforBOARD_SEPOLICY_IGNORE.Youcanuse
thistofilteroutspecificpolicyfiles.However,youhavetobespecificandusethe
repository’srelativepath.Forexample,indeviceY’sBoardConfig.mk:
BOARD_SEPOLICY_IGNORE+=device/OEM/A/custom.te
Now,whenyoubuildapolicyfordeviceY,thepolicysetwillnotincludethatfile.
BOARD_SEPOLICY_IGNOREcanalsobeusedwithBOARD_SEPOLICY_REPLACE,allowing
multipleusesinthedevicehierarchy,butonlyoneBOARD_SEPOLICY_REPLACEstatement
takeseffect.
www.it-ebooks.info
Diggingdeeperintobuild_policy
Nowthatwehaveseenhowtousesomenewmechanismstocontrolthepolicybuild,let’s
actuallydissectwhereinthebuildprocesshappens.Asstatedearlier,thepolicybuildis
controlledbytheAndroid.mkfile.Weencounteredcallstothebuild_policy()function
earlier,andthisispreciselywherethemagichappenswithrespecttoallofthe
BOARD_SEPOLICY_*variablesweset.Examiningthebuild_policyfunction,wesee
referencestothesepolicy_replace_pathsvariable,solet’sstartbylookingatthat
variable.
Thesepolicy_replace_pathsvariablebeginslifebygettingevaluatedwhenthe
Makefileisevaluated.Inotherwords,itisexecutedunconditionally.Thecodestartsoff
byloopingoveralltheBOARD_SEPOLICY_REPLACEfilesandcheckswhetheranyarein
BOARD_SEPOLICY_UNION.Ifoneisfound,anerrorisprintedandthebuildfails,showing
Ambiguousrequestforsepolicy$(pf).Appearsinboth
BOARD_SEPOLICY_REPLACEandBOARD_SEPOLICY_UNION,where$(pf)isexpandedtothe
offendingpolicyfile.Afterthat,itexpandstheBOARD_SEPOLICY_REPLACEentrieswith
thosefoundonthesearchpathssetbyBOARD_SEPOLICY_DIRS,thusresultinginfull
relativepathsfromtherootoftheAndroidtree.Thenitfilterstheseentriesagainst
BOARD_SEPOLICY_IGNORE,droppinganythingthatshouldbeignored.Itthenensuresthat
onlyonefilecandidateforreplacementisfound.Otherwise,itissuestheappropriateerror
message.Lastly,itensuresthatthefileexistsintheLOCAL_PATHorbasepolicy,andifnone
ofthetwoisfound,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_policyfunctionarethefilenamesyouwishtoexpandinto
theirAndroidroot-relativepathnames,usingthepowerprovidedbythe
BOARD_SEPOLICY_*familyofvariables.Forinstance,acallto$(build_policy,
file_contexts)inthecontextofourdevicesA,X,andYwouldresultinthis:
device/OEM/A/file_contexts
device/OEM/Y/file_contexts
Thebuild_policyfunctionisabittrickytoread.Manynestedfunctioncallsresultinthe
deepestindentsrunningfirst.However,likeallcode,wereaditfromtoptobottomand
lefttoright,sotheexplanationwillbeginthere.Thefunctionstartsbyloopingthroughall
thefilespassedasarguments.ItthenexpandsthemagainsttheBOARD_SEPOLICY_DIRS
onceforreplaceandonceforaunion.Thesepolicy_replace_pathsvariableiserror
checkedtoensureafiledoesnotappearinbothlocations,replaceandunion.Forthe
replacepathexpansion,itcheckswhethertheexpandedpathisin
sepolicy_replace_dirs,andifitis,replacesit.Fortheunionportion,itjustexpands
them.Theresultsoftheseexpansionsarethenfedthroughafilteron
BOARD_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.xml
Themac_permissions.xmlbuildisabittricky,aswesawinChapter10,Placing
ApplicationsinDomains.First,mac_permissions.xmlcanbeusedwithallthe
BOARD_SEPOLICY_*variablesintroducedthusfar.TheendresultisoneXMLfileadhering
totherulesofthosevariables.Additionally,therawXMLfilesareprocessedbyatool
calledinsertkeys.py,locatedinsepolicy/tools.Theinsertkeys.pytooluses
keys.conftomaptagsintheXMLfilesignaturestanzawith.pemfilescontainingthe
certificate.Thekeys.conffileisalsosubjecttouseinBOARD_SEPOLICY_*variables.The
buildrecipefirstcallsbuild_policyonkeys.confandusesm4toconcatenatetheresults.
Thus,m4declarationsinkeys.confwillberespected.However,thishasnotbeenused.
Theinitialintentionwastousethem4-ssynclinessothatyoucanfollowtheinclusion
chaininthekeys.conffilewhenconcatenatedbym4processing.Ontheotherhand,sync
linesareprovidedbym4whenconcatenatingmanyfiles,andtheyprovidecommented
linesadheringtothe#lineNUM"FILE"'lines.Theseareusefulbecausem4takesmultiple
inputfilesandcombinesthemintoasingle,expandedoutputfile.Therewillbesynclines
indicatingthebeginningofeachofthosefiles,andtheycanhelpyoutrackdownissues.
Continuingbacktothemac_permissions.xmlbuild,afterexpansionofkeys.confbym4,
thisfile,alongwithallthemac_permissions.xmlfilesfromacalltobuild_policy()are
finallyfedtoinsertkeys.py.Theinsertkeys.pytoolthenusesthekeys.conffileto
replaceallmatchingsignature=<TAG>lineswithanactualhex-encodedX509fromthe
PEMfile,thatis,signature=308E3600.Additionally,theinsertkeys.pytoolcombines
theXMLfilesintoonefile,andstripswhitespaceandcommentstoreduceitssizeondisk.
Thishasnobuilddependenciesontheothermajorfilessuchassepolicy,
seapp_contexts,property_contexts,andmac_permissions.xml.
www.it-ebooks.info
Buildingseapp_contexts
Theseapp_contextsfileisalsosubjecttoalltheBOARD_SEPOLICY_*variables.Allofthe
seapp_contextsfilesfromaresultantcalltobuild_policy()arealsofedthroughm4-s
togetasingleseapp_contextsfilethatcontainssynclines.Again,like
mac_permissions.xmlfile’sbuildofkeys.conf,m4hasn’tbeenusedotherthanforthe
synclines.Thisresulting,concatenatedseapp_contextsfileisthenfedintocheck_seapp.
ThistoolisauthoredintheCprogramminglanguageandbuiltintoanexecutableduring
thebuild.Thesourcecanbefoundintools/check_seapp.Thistoolreadsthe
seapp_contextsfileandchecksitssyntax.Itverifiesthattherearenoinvalidkeyvalue
pairs,thatlevelFromisavalididentifier,andthatthetypeanddomainfieldsarevalidfor
agivensepolicy.Thisbuildisdependentonsepolicyforthestricttypecheckingof
domainandtypefieldsagainstthepolicyfile.
www.it-ebooks.info
Buildingfile_contexts
Thefile_contextsfileisalsosubjecttoalloftheBOARD_SEPOLICY_*variables.The
resultingsetispassedthroughm4-s,andthesingleoutputisrunthroughthecheckfc
tool.Thecheckfctoolchecksthegrammarandsyntaxofthefileandalsoverifiesthatthe
typesexistinthebuiltsepolicy.Becauseofthis,itisdependentonthesepolicybuild.
www.it-ebooks.info
Buildingproperty_contexts
Theproperty_contextsbehavesexactlylikethefile_contextsbuild,exceptthatit
checksaproperty_contextsfile.Italsousescheckfc.
www.it-ebooks.info
CurrentNSAresearchfiles
Additionally,workonEnterpriseOperations(eops)isalreadyunderwayattheNSA.As
thisfeaturehasn’tbeenmergedintomainstreamAndroidandislikelytochangewildly,it
won’tbecoveredhere.However,thebestplaceforthebleedingedgeisalwaysthesource
andNSABitbucketrepositories.Theselinux-network.shalsofallsunderthiscategory;
ithasn’tseenmainstreamadoptionyet,andwilllikelybedroppedfromAOSP
(https://android-review.googlesource.com/#/c/114380/).
www.it-ebooks.info
www.it-ebooks.info
Standalonetools
TherearealsosomestandalonetoolsbuiltforAndroidpolicyevaluationthatyoumayfind
useful.Wewillexploresomeofthemandtheirusages.Mostofthestandarddesktoptools
you’llfindinotherreferencesstillworkonSEforAndroidSELinuxpolicy.Notethatif
yourunanyofthefollowingtoolsandgetasegmentationfault,youwilllikelyneedto
applythepatchfromthethreadathttp://marc.info/?l=seandroidlist&m=141684060409894&w=2.
www.it-ebooks.info
sepolicy-check
Thistoolallowsyoutoseewhetheragivenallowruleexistsinapolicyfile.Thebasic
syntaxofitscommandisasfollows:
sepolicy-check-s<domain>-t<type>-c<class>-p<permission>-P
<policy_file>
Forinstance,ifyouwanttoseewhethersystem_appcanwritetosystem_data_filefor
classfile,youcanexecute:
$sepolicy-check-ssystem_app-tsystem_data_file-cfile-pwrite-P
$OUT/root/sepolicy
www.it-ebooks.info
sepolicy-analyze
ThisisagoodtooltocheckforcommonissuesinSELinuxdevelopmentanditcatches
someofthecommonpitfallsofnewSELinuxpolicywriters.Itcancheckforequivalent
domains,duplicateallowrules.Itcanalsoperformpolicytypedifferencechecks.
Thedomainequivalencecheckfeatureisveryhelpful.Itshowsyoudomainsyoumay(in
theory)wanttobedifferent,eventhoughtheyconvergedintheimplementation.These
typeswouldbeidealcandidatestocoalesce.However,itmighthavealsoshownanissue
inthedesignofthepolicythatshouldbecorrected.Inotherwords,youdidn’texpectthese
domainstobeequivalent.Invokingthecommandisasfollows:
$sepolicy-analyze-e-P$OUT/root/sepolicy
Theduplicateallowrulecheckswhetherallowrulesexistontypesthatalsoexiston
attributesthatthetypeinheritsfrom.Theallowruleonthespecifictypeisacandidatefor
removal,sincethereisalreadyanallowontheattribute.Toexecutethischeck,runthe
followingcommand:
$sepolicy-analyze-D-P$OUT/root/sepolicy
Thedifferenceisalsohandyisalsohandytoviewtypedifferenceswithinafile.Ifyou
wanttoseewhatthedifferencebetweentwodomainsis,youcanusethisfeature.Thisis
usefulforidentifyingpossibledomainstocoalesce.Toperformthischeck,executethe
followingcommand:
$sepolicy-analyze-d-P$OUT/root/sepolicy
www.it-ebooks.info
www.it-ebooks.info
Summary
Inthischapter,wecoveredhowthevariouscomponentsthatcontrolthepolicyonthe
deviceareactuallybuiltandcreated,suchassepolicyandmac_permissions.xml.This
chapteralsopresentedtheBOARD_SEPOLICY_*variablesusedtomanageandbuildapolicy
acrossdevicesandconfigurations.ThenwereviewedtheAndroid.mkcomponents,
detailinghowtheheartofthebuildandconfigurationmanagementworks.
www.it-ebooks.info
www.it-ebooks.info
Chapter13.GettingtoEnforcingMode
Asanengineer,you’rehandedsomeAndroiddevice,andtherequirementistoapplySE
forAndroidcontrolstothedevicetoenhanceitssecurityposture.Sofar,wehaveseenall
thepiecesthatneedtobeconfiguredandhowtheyworktoenablesuchasystem.Inthis
chapter,we’lltakealltheskillscoveredtogetourUDOOinenforcingmode.Wewill:
Run,evaluate,andrespondtoauditlogsfromCTS
DevelopsecurepolicyfortheUDOO
Switchtoenforcingmode
www.it-ebooks.info
UpdatingtoSEPolicymaster
ManychangestothesepolicydirectoryhaveoccurredintheAOSPmasterbranchsince
the4.3release.Atthetimeofthiswriting,themasterbranchoftheexternal/sepolicy
projectwasonGitcommitSHAb5ffb.Theauthorsrecommendattemptingtousethe
mostrecentcommit.However,forillustrativepurposes,wewillshowyouhowto
optionallycheckoutcommitb5ffbsoyoucanaccuratelyfollowtheexamplesinthis
chapter.
First,you’llneedtoclonetheexternal/sepolicyproject.Intheseinstructions,we
assumeyourworkingdirectoryhastheUDOOsourcescontainedinthe./udoodirectory:
$gitclonehttps://android.googlesource.com/platform/external/sepolicy
$cdsepolicy
Ifyouwanttofollowtheexamplesinthischapterprecisely,you’llneedtocheckout
commitb5ffbwiththefollowingcommand.Ifyouskipit,youwillendupusingthelatest
commitinthemasterbranch:
$gitcheckoutb5ffb
Now,we’llreplacetheUDOO4.3sepolicywithwhatwejustacquiredfromGoogle:
$cd..
$rm-rfudoo/external/sepolicy
$cp-rsepolicyudoo/external/sepolicy
Optionally,youcanremovethe.gitfolderfromthenewlycopiedsepolicywiththe
followingcommand,butthisisnotnecessary:
$rm–rfudoo/external/sepolicy/.git
Also,copytheaudit.tefileandrestoreit.
Additionally,restoretheauditdcommitfromtheNSABitbucketseandroidrepository.
Foryourreference,it’scommitSHAd270aa3.
Afterthat,removeallreferencestosetoolfromudoo/build/core/Makefile.This
commandwillhelpyoulocatethem:
$grep-nwsetooludoo/build/core/Makefile
www.it-ebooks.info
www.it-ebooks.info
Purgingthedevice
Atthispoint,ourUDOOismessy,solet’sreflashit,includingthedatadirectory,andstart
afresh.Wewanttohaveonlythecodeandtheinitscriptchanges,withouttheadditional
sepolicy.Thenwecanauthorapolicyproperlyandapplyallthetechniquesandtools
we’veencountered.We’llstartbyresettingtoastateanalogoustothecompletionof
Chapter4,InstallationontheUDOO.However,themajordifferenceisweneedtobuilda
userdebugversionratherthananengineering(eng)versionforCTS.Theversionis
selectedinthesetupscript,whichultimatelycallslunch.Tobuildthisversion,executethe
followingcommandsfromtheUDOOworkspace:
$.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
www.it-ebooks.info
SettingupCTS
YoumustpassCTSifyourorganizationseeksAndroidbranding.However,evenifyou
don’t,it’sagoodideatoruntheseteststohelpensureadevicewillbecompliantwith
applications.Basedonyoursecuritygoalsanddesires,youmayfailportionsofCTSif
you’renotseekingAndroidbranding.Forourcase,we’relookingatCTSasawayto
exercisethesystemanduncoverpolicyissuesthatpreventtheproperfunctioningofthe
UDOO.Itssourceislocatedinthects/directory,butwerecommenddownloadingthe
binarydirectlyfromGoogle.YoucangetmoreinformationandtheCTSbinaryitselffrom
https://source.android.com/compatibility/cts-intro.htmland
https://source.android.com/compatibility/android-cts-manual.pdf.
DownloadtheCTS4.3binaryfromtheDownloadstab.ThenselecttheCTSbinary.The
CompatibilityDefinitionDocument(CDD)isalsoworthreading.ItcoversthehighleveldetailsofCTSandcompatibilityrequirements.
DownloadCTSfromhttps://source.android.com/compatibility/downloads.htmlandextract
it.SelecttheCTSversionthatmatchesyourAndroidversion.Ifyoudon’tknowwhich
versionyourdeviceisrunning,youcanalwayscheckthero.build.version.release
propertyfromtheUDOOwithgetpropro.build.version.release:
$mkdir~/udoo-cts
$cd~/udoo-cts
$wgethttps://dl.google.com/dl/android/cts/android-cts-4.3_r2-linux_x86arm.zip
$unzipandroid-cts-4.3_r2-linux_x86-arm.zip
www.it-ebooks.info
www.it-ebooks.info
RunningCTS
TheCTSexercisesmanycomponentsonthedeviceandhelpstestvariouspartsofthe
system.Agood,generalpolicyshouldallowproperfunctioningofAndroidandpassCTS.
FollowthedirectionsintheAndroidCTSusermanualtosetupyourdevice(seeSection
3.3,Settingupyourdevice).Typically,youwillseesomefailuresifyoudon’tfollowall
thestepsprecisely,asyoumaynothavetheaccessorthecapabilitiestoacquireallthe
resourcesneeded.However,CTSwillstillexercisesomecodepaths.Ataminimum,we
recommendgettingthemediafilescopiedandWi-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;butyoucancheckthestatusofthe
test:
cts-tf>li
CommandIdExecTimeDeviceState
18m:220123456789ABCDEFrunningctsonbuild4.3_r2
Pluginspeakerstoenjoythesoundsfromthemediatestsandringtones!Also,CTS
rebootsthedevice.IfyourADBsessionisnotrestoredafterrebooting,ADBmaynot
executeanytests.Usethe--disable-rebootoptionwhenrunningthects-tf>runcts
--planCTS--disable-rebootplan.
www.it-ebooks.info
www.it-ebooks.info
Gatheringtheresults
First,we’llconsidertheCTSresults.Althoughweexpectsomefailures,wealsoexpect
theproblemwillnotgetworsewhenwegotoenforcingmode.Second,we’lllookatthe
auditlogs.Let’spullbothofthesefilesfromthedevice.
www.it-ebooks.info
CTStestresults
CTScreatesatestresultsdirectoryeachtimeitisrun.CTSisindicatingthedirectory
namebutnotthelocation:
11-3010:30:28I/0123456789ABCDEF:Createdresultdir2014.11.30_10.30.28
ThelocationismentionedbytheCTSmanualandcanbefoundundertheextractedCTS
directoryinrepository/results,typicallyatandroid-cts/repository/results.The
testdirectoriescontainanXMLtestreport,testResult.xml.Thiscanbeopenedinmost
webbrowsers.Ithasaniceoverviewofthetestsanddetailsofallexecutedtests.The
pass:failratioisourbaseline.Theauthorshad18,736pass,andonly53fail,whichis
fairlygoodconsideringhalfofthosearefeatureissues,suchasnoBluetoothorreturning
trueforcamerasupport.
www.it-ebooks.info
Auditlogs
Wewillusetheauditlogstoaddressdeficienciesinourpolicy.Pulltheseoffthedevice
usingthestandardadbpullcommandswehaveusedthroughoutthebook.Sincethisisa
userdebugbuildanddefaultadbterminalsareshelluid(notroot),startadbasrootwith
adbroot.suisalsoavailableonuserdebugbuilds.
Tip
Youmaygetanerrorsaying/data/misc/audit/audit.logdoesnotexist.Thesolutionis
torunadbasrootviatheadbrootcommand.Also,whenrunningthiscommand,itmay
hang.Justgotosettings,disable,andthenenableUSBDebuggingunderDeveloper
Options.Thenkilltheadb-rootcommandandverifyyouhaverootbyrunningadb
shell.Nowyoushouldbearootuseragain.
www.it-ebooks.info
www.it-ebooks.info
Authoringdevicepolicy
Runbothaudit.logandaudit.oldthroughaudit2allowtoseewhat’sgoingon.The
outputofaudit2allowisgroupedbysourcedomain.Ratherthangoingthroughitall,we
willhighlighttheunusualcases,startingwiththeinterpretedresultsofaudit2allow.
Assumingyouareintheauditlogdirectory,performcataudit.*|audit2allow|
less.Anypolicyworkwillbedoneinthedevice-specificUDOOsepolicydirectory.
www.it-ebooks.info
adbd
Thefollowingareouradbddenialsasfilteredthroughaudit2allow:
#=============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.Thefirstthingthatcaughtoureyewas
theexecuteon/dev/ashmem,whichisacharacterdriver.Typically,thisisonlyneededfor
DalvikJIT.Lookingattherawaudits(cataudit.*|grepadbd|grepexecute),we
seethefollowing:
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.Ourguess
isithassomethingtodowithDalvik,butwhyisitintheadbddomain?Also,whyisadbd
writingtotheinputdevice?Allthisisstrangebehavior.Typically,whenyouseethings
likethis,it’sbecausethechildrendidn’tendupintheproperdomain.Runthiscommand
tocheckthedomainsandconfirmoursuspicions:
$adbshellps-Z|grepadbd
u:r:adbd:s0root200461/sbin/adbd
u:r:adbd:s0root2010120046ps
Wethenrunadbshellps-Z|grepadbdtoseewhichthingswererunningintheadb
domain,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
Thebasepolicydefinesadomaintransitionwhenadbdloadstheshellusingexectogoto
theshelldomain.Thisisdefinedintheadbd.teexternalsepolicyas
domain_auto_trans(adbd,shell_exec,shell).
Obviously,anincorrectlabelhasbeenappliedtoshell,solet’slookatfile_contextsin
theexternalsepolicytofindoutwhy.
$catfile_contexts|grepshell_exec
/system/bin/sh—u:object_r:shell_exec:s0
Thetwodashesmeanthatonlyregularfileswillbelabeledandsymboliclinkswillbe
skipped.Weprobablydon’twanttolabelthesymlink,butratherthemkshdestination.Do
thisbyaddingacustomfile_contextsentrytothedeviceUDOOsepolicyandadding
thefiletotheBOARD_SEPOLICY_UNIONconfig.Infile_contexts,add/system/bin/mksh—
u:object_r:shell_exec:s0,andinsepolicy.mk,addBOARD_SEPOLICY_UNION+=
file_contexts.
Tip
Throughouttheremainderofthechapter,wheneveryoucreateormodifypolicyfiles(for
example,contextfilesor*.tefiles),don’tforgettoaddthemtoBOARD_SEPOLICY_UNION
insepolicy.mk.
Sincethisisafairlyfatalissuewiththepolicyandadbd,wewon’tworryaboutthedenials
fornow,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/,weshouldlook
atthemounttable:
root@udoo:/#mount|grepdevice
/dev/block/mmcblk0p7/deviceext4
ro,seclabel,nosuid,nodev,relatime,user_xattr,barrier=1,data=ordered00
Typically,mountcommandsareintheinitscriptsfollowingamkdir,orinanfstabfile
withtheinitbuilt-in,mount_all.Aquicksearchfordeviceandmkdirininit.rcfinds
nothing,butwedofinditinfstab.freescale.Thedeviceisread-only,soweshouldbe
abletogiveitatype,labelitwithfilecontexts,andapplythegetattrdomaintoits
directoryclass.Sinceit’sread-onlyandempty,nobodyshouldneedmorepermissions.
Lookingatthemake_sd.shscript,wenoticethatpartition7oftheblockdeviceisthe
www.it-ebooks.info
venderdirectory.ThisisamisspellingofthecommonvendordirectorythatOEMsplace
proprietaryblobsin.Weplacefiletypesinfile.teandthedomainallowrulesin
domain.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-Ronittolabelexisting
files.
IfyoupulltheauditlogsmultipletimesfromtheUDOO,youmayalsoendupwith
denialsshowingthatyoudidso,asadbdwillnotbeabletoaccessthem.Youmayseethis:
#=============adbd==============
allowadbdaudit_log:file{readgetattropen};
Thisrulecomesfromtheendofthetestwhenyouadbpulledtheauditlogs.Wecan
safelydontauditthisandaddaneverallowtoensureitdoesn’taccidentallygetallowed.
Theauditlogscontaininformationamalwarewritercouldusetonavigatethroughthe
policy,andthisinformationshouldbeprotected.Inadevicesepolicyfolder,addan
adbd.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/sepolicyalong
withalldependenttypes.
Theneverallowentriesshowyouhowtousethecompliment,~,andsetdifference,-,
operatorsforstrongassertionsorbrevity.Thefirstneverallowstartswithdomain,andall
processtypes(domains)aremembersofthedomainattribute.Wepreventaccessthrough
setdifference,leavingthesetthatmustneverhaveaccess.Wethencomplimenttheaccess
vectorsettoallowonlygetattrorstatonthelogs.Thesecondneverallowuses
complimenttoensuresystem_serverislimitedtoreadoperations.
www.it-ebooks.info
bootanim
Thebootanimdomainisassignedtothebootanimationservicethatpresentssplash
screensonboot,typicallythecarrier’sbranding:
#=============bootanim==============
allowbootaniminit:unix_stream_socketconnectto;
allowbootanimlog_device:chr_file{writeopen};
allowbootanimproperty_socket:sock_filewrite;
Anythingtouchingtheinitdomainisaredflag.Here,bootanimconnectstoaninitUnix
domainsocket.Thisisapartofthepropertysystem,andwecanseethatafterconnecting,
itwritestothepropertysocket.ThesocketobjectanditsURIareseparate.Inthiscase,it’s
thefilesystem,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.The
patchthatremovedsupportisathttps://android-review.googlesource.com/#/c/108147/.
Ratherthanapplyareversepatchtotheexternalsepolicy,wecanjustaddtherulestoour
devicepolicyinadomain.tefile.Wecansafelyallowtheseusingthepropermacrosand
stylesinthedeviceUDOOsepolicyfolder.Inbootanim.te,add
unix_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;
Thelogdevicedenialwasaddressedunderbootanimbyaddingtheallowrulesforall
domainstouselog_device.Thesystem_data_file:sock_filewriteisstrange.Inmost
circumstances,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,which
policyversion23doesnotsupport:
system_server.te:297:type_transitionsystem_server
system_data_file:sock_filesystem_ndebug_socket"ndebugsocket";
Wehavetochangethecodetosetthepropercontextorjustallowit,whichwewill.We
won’tgrantadditionalpermissionsbecauseitneveraskedforopen,andwe’recrossing
domains.Preventingfileopensacrossdomainsisideal,astheonlywaytogetthisfile
descriptoristhroughanIPCcallintotheowningdomain.Indebuggerd.te,addallow
debuggerdsystem_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’tuse
binder.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.Thismustbea
labelingerrorontheapp_processfile,whichisthezygote.Thels-laZ
/system/bin/app_processcommandrevealsu:object_r:system_file:s0
app_process,soaddanentrytofile_contextstocorrectthis.Wecanfindthelabelto
useinzygote.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
installd
Theaddeddomain.teruleshandleinstalld.
www.it-ebooks.info
keystore
#=============keystore==============
allowkeystoreapp_data_file:filewrite;
allowkeystorelog_device:chr_file{writeopen};
Thelogdeviceistakencareofbythedomain.terules.Let’slookattheraw
app_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.ThismeansMLSsupportisactivatedforapp
domains.Intheseapp_contextsbasesepolicy,weseethis:
user=_appdomain=untrusted_apptype=app_data_filelevelFrom=user
user=_appseinfo=platformdomain=platform_apptype=app_data_file
levelFrom=user
MLSseparationofapplicationdataisstillunderdevelopmentanddidn’tworkon4.3,so
wecandisablethis.Wecanjustdeclaretheminadevice-specificseapp_contextsfile.In
seapp_contexts,adduser=_appdomain=untrusted_apptype=app_data_fileand
user=_appseinfo=platformdomain=platform_apptype=app_data_file.In4.3,any
changestocontextondatarequireafactoryreset.The4.4versionaddedsmartrelabel
capabilities.
www.it-ebooks.info
mediaserver
#=============mediaserver==============
allowmediaserveradbd:binder{transfercall};
allowmediaserverinit:binder{transfercall};
allowmediaserverlog_device:chr_file{writeopen};
Thelogdevicewasaddressedinthedomain.terules.We’llskipinitandadbdtoo,since
theirissuesweretriggeredbyimproperprocessdomains.It’simportantnottoaddallow
rulesblindly,asmostoftheworkforexistingdomainscanbehandledwithsmalllabel
changesorafewrules.
www.it-ebooks.info
netd
#=============netd==============
allownetdkernel:systemmodule_request;
allownetdlog_device:chr_file{writeopen};
Thelogdevicedenialofnetdwasaddressedbydomain.te.However,weshould
scrutinizeanythingrequestingacapability.Whengrantingcapabilities,thepolicyauthor
needstobeverycareful.Ifadomainisgrantedtheabilitytoloadasystemmoduleand
thatdomainormodulebinaryitselfiscompromised,itcouldleadtotheinjectionof
malwareintothekernelvialoadablemodules.However,netdneedsloadablekernel
modulesupporttosupportsomecards.Addtheallowruletoafilecallednetd.teinthe
deviceUDOOsepolicy.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,sinceitsissueswere
triggeredbyimproperprocessdomains.
www.it-ebooks.info
surfaceflinger
#=============surfaceflinger==============
allowsurfaceflingerinit:bindertransfer;
allowsurfaceflingerlog_device:chr_file{writeopen};
Again,thelogdevicewashandledindomain.te.We’llskipinittoo,sinceitsissueswere
triggeredbyimproperprocessdomains.
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,wewill
onlyaddresstheDalvikcachedenial:
type=1400msg=audit(1417405611.550:159):avc:denied{write}forpid=2571
comm="er.ServerThread"name="system@app@SettingsProvider.apk@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@app@SettingsProvider.apk@classes.dex"dev=mmcblk0p4ino=129458
scontext=u:r:system_server:s0tcontext=u:object_r:dalvikcache_data_file:s0
tclass=file
Theexternalsepolicyseandroid-4.3branchalloweddomain.te:allowdomain
dalvikcache_data_file:filer_file_perms;.Writeswereallowedbysystem_appwith
system_app.te:allowsystem_appdalvikcache_data_file:file{writesetattr
};.Weshouldbeabletograntthiswriteaccessbecausetheremaybeaneedtoupdateits
Dalvikcachefile.Indomain.te,addallowdomaindalvikcache_data_file:file
r_file_perms;,andinsystem_server.te,addallowsystem_server
dalvikcache_data_file:file{writesetattr};.
www.it-ebooks.info
toolbox
#=============toolbox==============
allowtoolboxsysfs:filewrite;
Typically,oneshouldnotwritetosysfs.Nowlookattherawdenialfortheoffending
sysfsfile:
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,andallow
toolboxaccesstoit.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,addallow
toolboxsysfs_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’t
addressmostofthesenow.However,youshouldlookoutformislabeledandunlabeled
targetfiles.Whilesearchingthedeniallogsasinterpretedbyaudit2allow,thefollowing
wasfound:
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.Werecommenda
thoroughreviewofthesourcecode,butfornow,wewilllabelitasgpu_device.
/dev/.coldboot_doneiscreatedbyueventdwhenthecoldbootprocesscompletes.If
ueventdisrestarted,itskipsthecoldboot.Wedon’tneedtolabelthis.Thisdenialis
causedbythesourcedomainMLSonatargetfilethatisnotasubsetofthecategoriesof
thesourceanddoesnothavethemlstrustedsubjectattribute;itshouldgoawaywhen
wedropMLSsupportfromapps.
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,butthefiledescriptorisvalidandonly
watchdogcanuseit.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-initueventd-recovery}device:chr_file{openreadwrite};.Forsuchasimple
change,we’lljustmodifythebasesepolicytoneverallow{domain-init-ueventdrecovery-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.Thesystemdataaccessesneedfurther
investigation,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.Relabelingitwithouttypetransitions
isimpossible,sowehavetoallowit.Inwpa.te,addallowwpasystem_data_file:dir
rw_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
www.it-ebooks.info
Secondpolicypass
Afterloadingthedraftedpolicy,thedevicestillhasdenialsonboot:
#=============init==============
allowinitrootfs:file{writecreate};
allowinitsystem_file:fileexecute_no_trans;
#=============shell==============
allowshelldevice:chr_file{readwritegetattr};
allowshellsystem_file:fileentrypoint;
Allofthesedenialsshouldbeinvestigatedbecausetheytargetsensitivetypes,tcontext
specifically.
www.it-ebooks.info
init
Therawdenialsforinitareasfollows:
<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,andsince
initisrunningunconfined,wecanjustaddittoinit.te.Wecouldaddtheallowruleto
theunconfinedset,butsincethatisgoingaway,let’sminimizethepermissiononlyto
init:
allowintrootfs:filecreate_file_perms;
Note
Unconfinedisnotcompletelyunconfined.RulesgetstrippedfromthisdomainasAOSP
movesclosertozerounconfineddomains.
Doingthis,however,causesanotherneverallowtofail.Wecanmodify
external/sepolicydomain.tetobypassthis.Changetheneverallowfromthis:
#Nothingshouldbewritingtofilesintherootfs.
neverallow{domain-recovery}rootfs:file{createwritesetattrrelabelto
appendunlinklinkrename};
Changeittothis:
#Nothingshouldbewritingtofilesintherootfs.
neverallow{domain-recovery-init}rootfs:file{createwritesetattr
relabeltoappendunlinklinkrename};
Note
Ifyouneedtomodifyneverallowentriestobuild,youwillfailCTS.Theproperapproach
istoremovethisbehaviorfrominit.
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,wecanrelabelmagdwithitsowntypeandplaceitinitsownunconfined
domain.Aneverallowinthebasepolicyforcesustomoveeachexecutableintoitsown
domain.
www.it-ebooks.info
Createafilecalledmagd.te,addittoBOARD_SEPOLICY_UNION,andaddthefollowing
contentstoit:
typemagd,domain;
typemagd_exec,exec_type,file_type;
permissive_or_unconfined(magd);
Alsoupdatefile_contextstocontainthis:
/system/bin/magdu:object_r:magd_exec:s0
Repeatthestepsthatweredoneformagdforrfkill.Justreplacemagdwithrfkillinthe
precedingexample.Latertestingrevealedanentry-pointdenialwherethesourcecontext
wasinit_shellandthetargetwasrfkill_exec.Afteraddingtheshellrules,itwas
discoveredthatrfkillisloadedusingexecfromtheinit_shelldomain,solet’salso
adddomain_auto_trans(init_shell,rfkill_exec,rfkill)totherfkill.tefile.
Additionallygroupedwiththisdiscoverywasrfkillattemptingtoopen,read,andwrite
/dev/rfkill.Sowemustlabel/dev/rfkillwithrfkill_device,allowrfkillaccess
toit,andappendallowrfkillrfkill_device:chr_filerw_file_perms;tothe
rfkill.tefile.Createanewfiletodeclarethisdevicetype,calleddevice.te,andadd
typerfkill_device,dev_type;.Afterthat,labelitwithfile_contextsbyadding
/dev/rfkillu:object_r:rfkill_device:s0.
www.it-ebooks.info
shell
Thefirstshelldenialwewillevaluateisthedenialonentrypoint:
<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.Wecancreateanunconfineddomain
forshellsspawnedbyinittoendupintheinit_shelldomain.Theconsolestillendsup
intheshelldomainviaanexplicitseclabel,andotherinvocationsendupas
init_shell.Createanewfile,init_shell.te,andaddittoBOARD_SEPOLICY_UNION.
www.it-ebooks.info
init_shell.te
typeinit_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.Addthefollowing
entrytothefilecontexts:
/dev/ttymxc[0-9]*u:object_r:tty_device:s0
www.it-ebooks.info
www.it-ebooks.info
Fieldtrials
Atthispoint,rebuildthesourcetree,wipethedatafilesystem,flash,andre-runCTS.
Repeatthisuntilalldenialsareaddressed.
Onceyou’redonewithCTSandinternalQAtrials,werecommendperformingafieldtrial
withthedeviceinpermissivemode.Duringthisperiod,youshouldbegatheringthelogs
andrefiningpolicy.Ifthedomainsarenotstable,youcandeclarethemaspermissivein
thepolicyfileandstillputthedeviceinenforcingmode;enforcingsomedomainsisbetter
thanenforcingnone.
www.it-ebooks.info
www.it-ebooks.info
Goingenforcing
Youcanpasstheenforcingmodeeitherusingbootloader(whichwillnotbecovered
here)orwiththeinit.rcscriptearlyinboottime.Youcandothisrightaftersetcon:
setconu:r:init:s0
setenforce1
Oncethisstatementiscompiledintotheinit.rcscript,itcanonlybeundonewitha
subsequentbuildandareflashofboot.img.Youcancheckthisbyrunningthe
getenforcecommand.Also,asaninterestingtest,youcantrytorunthereboot
commandfromtherootserialconsoleandwatchitfail:
root@udoo:/#getenforce
Enforcing
root@udoo:/#reboot
reboot:Operationnotpermitted
www.it-ebooks.info
www.it-ebooks.info
Summary
Inthischapter,allofyourpreviousunderstandingofthesystemwasusedtodevelopreal
SEforAndroidpolicyforabrandnewdevice.Youarenowempoweredwiththe
knowledgeofhowtowriteSELinuxpolicyforAndroid,whereandhowthecomponents
ofthesystemwork,andhowtoportandenablethesefeaturesonvariousAndroid
platforms.Sincethisisafairlynewfeaturethatinfluencesmanysysteminteractions,
issuesthatwillrequirecodechangesaswellaspolicychangeswillarise.Understanding
bothiscrucial.
Aspolicyauthorsandsecuritypersonnelingeneral,theresponsibilitytosecurethesystem
restsonourshoulders.Inmostorganizations,you’rerequiredtoworkinthedark.
However,ifyoucan,doasmuchworkandaskasmanyquestionsasyouwanttointhe
mailinglist,andneveracceptthestatusquo.TheSEforAndroidandAOSPprojects
welcomealltocontribute,andbycontributing,youwillhelpmaketheprojectbetterand
enhancethefeaturesetsforall.
www.it-ebooks.info
www.it-ebooks.info
AppendixA.TheDevelopment
Environment
InordertobuildtheAndroid4.3sourcesprovidedbyUDOO,youneedanUbuntuLinux
systemwithOracleJava6.Whileitmaybepossibletouseavariantofthissetup,
Google’sstandardtargetdevelopmentplatformforAndroid4.3isUbuntu12.04.
Therefore,wewillusethissetuptoensurethehighestprobabilityofsuccessinour
explorationofLinux,SELinux,Android,theUDOO,andSEforAndroid.
Inthisappendix,wewilldothefollowing:
DownloadandinstallUbuntu12.04usingavirtualmachine(VM)
EnhanceourVM’sperformancebyinstallingtheVirtualBoxExtensionPackand
VirtualBoxGuestAdditions
SetupadevelopmentenvironmentappropriateforbuildingtheLinuxkerneland
UDOOsources
InstallOracleJava6
Tip
IfyoualreadyuseUbuntuLinux12.04,youcanskiptotheTheBuildEnvironment
section.IfyouintendtoinstallUbuntunatively(notinaVM),youshouldskiptothe
UbuntuLinux12.04sectionandfollowthosedirections,ignoringtheVirtualBoxsteps.
www.it-ebooks.info
VirtualBox
Thereareanumberofvirtualizationproductsavailableforrunningguestoperating
systems,suchasUbuntuLinux,butforthissetupwewilluseVirtualBox.VirtualBoxisa
widelyusedopensourcevirtualizationsystemavailableforMac,Linux,Solaris,and
Windowshosts(amongothers).Itsupportsavarietyofguestoperatingsystems.
VirtualBoxalsoallowstheuseofhardwarevirtualizationofmanymodern/common
processorfamiliestoincreaseperformancebyprovidingeachvirtualmachineitsown
privateaddressspace.
TheVirtualBoxdocumentationhasexcellentinstallationinstructionsforvarious
platforms,andwerecommendreferringtotheseforyourhostplatform.Youcanfind
informationaboutinstallingandrunningVirtualBoxforyourhostoperatingsystemat
http://www.virtualbox.org/manual/ch02.html.
www.it-ebooks.info
www.it-ebooks.info
UbuntuLinux12.04(precisepangolin)
ToinstallUbuntuLinux12.04,youwillfirstneedtodownloadanappropriatedistribution
image.Thesecanbefoundathttp://releases.ubuntu.com/12.04/.Whilethereareanumber
ofacceptableimagesthere,wewillinstallthe64-bitdesktopversionofthedistribution
—http://releases.ubuntu.com/12.04/ubuntu-12.04.5-desktop-amd64.iso.Thehostmachine
we’reusinginthisexampleisa64-bitMacbookProrunningOSX10.9.2,sowe’re
targetinga64-bitguestaswell.Ifyouhavea32-bitmachine,thebasicmechanicsofwhat
wecoverwillbethesame;onlyafewdetailswillbedifferent,sowewillleavethosefor
youtodiscoverandresolve.
LaunchVirtualBoxonyourhost,waitfortheVMManagerwindowtoappear,and
performthefollowingsteps:
1. ClickonNew.
2. FortheNameandOperatingSystemsettings,makethefollowingselections:
Name:SEforAndroidBook
Type:Linux
Version:Ubuntu(64bit)
3. SetMemorySizetoavaluetoatleast16GB.Anythinglowerthanthiswillleadto
unsuccessfulbuilds.
4. Tosetuptheharddrive,selectCreateavirtualharddrivenow.Setthisvaluetoat
least80GB.
5. ChoosetheHardDriveFileType,VDI(VirtualBoxDiskImage).
6. Ensurestorageonthephysicalharddriveissettodynamicallyallocated.
7. Whenpromptedforfilelocationandsize,namethenewvirtualharddriveSEfor
AndroidBook,andsetitssizeto80GB.
EnsuretheSEforAndroidBookVMisselectedintheleftpane.ClickonthegreenStart
arrowtoperformaninitiallaunchoftheVM.Adialogwillappear,askingyoutoselecta
virtualopticaldiskfile.Clickonthesmallfoldericonandlocatetheubuntu-12.04.5desktop-amd64.isoCDimageyoudownloadedearlier.ThenclickonStart.
WhenthescreenturnsblackandshowsakeyboardimageatthebottomcenteroftheVM
window,pressanykeytobegintheUbuntuinstallation.Assoonasyoudothis,the
languageselectionscreenwillappear.Choosewhicheverlanguageismostappropriatefor
you,butforthisexample,we’llselectEnglish.ThenselectInstallUbuntu.
Sometimes,youmayseeanunusual-lookingerrorprintedacrossyourVMwindow—
somethinglikeSMBusbaseaddressuninitialized.Thismessageisshownbecause
VirtualBoxdoesn’tsupportaparticularkernelmodulethatisloadedbydefaultwith
Ubuntu12.04.However,thiswillnotcauseanydifficultyandisonlyacosmetic
annoyance.Afterafewmoments,aniceGUIinstallationscreenwillappear,waitingfor
youtochoosealanguageagain.We’llchooseEnglishagain.
OnthefollowingPreparingtoinstallUbuntuscreen,threechecklistitemsareshown.
www.it-ebooks.info
Youshouldhavealreadysatisfiedthefirstitem,sinceyourvirtualdriveismuchlarger
thantheminimumrequirementforUbuntu.Tosatisfytheothers,ensureyourhostsystem
ispluggedinwithapowersupplyandhasanestablishednetworkconnection.Although
thisisentirelyunnecessaryforourpurposeshere,wealmostalwaysmarktheDownload
updateswhileinstallingandInstallthisthird-partysoftwareboxesbeforecontinuing.
OntheInstallationtypescreen,we’lltaketheeasypathandselectErasediskandinstall
Ubuntu.KeepinmindthatthiswillonlyerasethediskofyourVM’svirtualharddrive
andleavesyourhostsystemintact.OntheErasediskandinstallUbuntuscreen,your
virtualharddriveshouldalreadybeselected,soyouonlyneedtoclickInstallNow.
FromthispointforwardintheUbuntuinstallation,twoseparatetaskswillhappen
simultaneously:inabackgroundthread,theinstallerwillpreparethevirtualdriveforthe
installationofthebasesystem;secondly,youwillconfiguresomebasicaspectsofyour
newsystem.Butfirst,youwillhavetoidentifyyourtimezonebyclickingonthe
appropriatepointontheworldmapbeforecontinuing.Thenidentifyyourkeyboardlayout
andcontinue.
Setupyourfirstuseraccount.Inthiscase,itwillbetheaccountweusedtodotheworkin
thisbook,sowewillenterthefollowinginformation:
YourName:BookUser
Yourcomputer’sname:SE-for-Android
Pickausername:bookuser
Passwordfields:(whateveryouprefer)
WewillalsoselectLoginautomatically.Whilewewouldnotnormallydothisfor
securityreasons,wewilldoitinourlocalVMforconvenience;butyoumayprotectthis
accountinwhicheverwayyouprefer.
OncetheUbuntuinstallationiscomplete,adialogaskingyoutorestartthecomputerwill
appear.ClicktheRestartnowbutton,andafterafewmoments,aterminalpromptwill
informyoutoremoveallinstallationmediaandpressEnter.Toremovethevirtual
installationCD,gotoDevices|CD/DVDDevices|Removediskfromvirtualdrive
usingtheVirtualBoxmenubar.ThenpressEntertorestarttheVM,butinterrupttheboot
processbyclosingtheVMwindow.Itwillaskyouifyouwanttopoweroffthemachine.
JustclickOK.
www.it-ebooks.info
www.it-ebooks.info
VirtualBoxextensionpackandguest
additions
TogetthebestperformancefromyourguestUbuntuVMandaccesstothevirtualUSB
devicesnecessaryforworkingwiththeUDOO,youwillneedtoinstalltheVirtualBox
extensionpackandguestadditions.
www.it-ebooks.info
VirtualBoxextensionpack
DownloadtheextensionpackfromtheVirtualBoxwebsite,at
http://www.virtualbox.org/wiki/Downloads.Therewillbeadownloadlinkthereintended
forAllsupportedplatforms.Oncethisfileisdownloaded,you’llneedtoinstallit.This
processisdifferentforeachtypeofhostsystem,butitisverystraightforward.ForLinux
andMacOSXhosts,simplydouble-clickingonthedownloadedextensionpackfilewill
dothetrick.ForWindowssystems,youwillneedtoruntheinstalleryou’vedownloaded.
www.it-ebooks.info
VirtualBoxguestadditions
Onceyou’vecompletedtheinstallationoftheextensionpack,bootyourUbuntuLinux
12.04VMfromVirtualBoxbyselectingtheVMfromtheleftpaneandclickingonStart
inthetoolbar.OnceyourUbuntudesktopisactive,you’llnoticeitdoesnotfitintoyour
VMwindow.ResizetheVMwindowtomakeitlarger,andtheVMscreenwillremainthe
samesize.This,amongotherperformanceissues,willberesolvedbyinstallingthe
VirtualBoxguestadditions.Youmayalsoseeawindowopenonyourvirtualdesktop
indicatinganewversionofUbuntuisavailable.Donotupgrade;justclosethatwindow.
UsingtheVirtualBoxmenubar,gotoDevices|InsertGuestAdditionsCDImage….
Shortlyafterward,adialogwillappear,askingwhetheryouwanttorunthesoftwareon
thenewmediayoujustinserted.ClicktheRunbutton.Youwillthenneedtoauthenticate
youruserbyenteringyouruser’spassword(whichyouenteredduringsetup).Oncethe
userisauthenticated,ascriptwillautomaticallybuildandupdateseveralkernelmodules.
Oncethescriptcompletes,reboottheVMbyclickingonthegearinthetop-rightcornerof
thescreen,selectingShutdown…,andclickingonRestartinthedialogthatfollows.
WhentheVMreboots,thefirstthingyoushouldnoticeisthattheVMscreennowfitsinto
theVMwindow.Moreover,ifyouresizetheVMwindow,theVMscreenresizeswithit.
Thisisthesimplestwaytodetermineyou’vesuccessfullyinstalledtheVirtualBoxguest
additions.
www.it-ebooks.info
www.it-ebooks.info
Savetimewithsharedfolders
Anotherthingyoucandotoboostyouraggregateperformancewhiledevelopingimages
fortheUDOOistosetupsharedfoldersbetweenyourhostsystemandyourUbuntu
Linuxguestsystem.Inthisway,onceyou’vebuiltanewSDcardimagefortheUDOO,
youcanmaketheimagedirectlyavailabletothehostthroughthesharedfolder.Thehost
canthenexecutethelong-runningcommandstoflashtheSDcardwithoutaddingtimeto
theprocessbyslowingdownaccesstoyourhost’scardreaderthroughthevirtualization
layer.Inthecaseofthesystemwe’reusingtowritethisbook,thereisasavingsofaround
10minutesperimageflashed.
Tosetupasharedfolder,youmustbeginwiththeVirtualBoxManageropenandyour
UbuntuVMpoweredoff.ClicktheSettingstoolbaricon.ThenselecttheSharedFolders
taboftheSettingsdialogthatopens.ClicktheAddSharedFoldericontotheright.Enter
FolderPathtoafolderonyourhostthatyouwanttoshare.Inourcase,wecreatedanew
foldercalledvbox_sharetosharewithourVMguest.VirtualBoxwillgenerateFolder
Name,butmakesureyouselectAuto-mountbeforeclickingOK.Whenyoubootyour
UbuntuVMfromnowon,thesharedfolderwillbeaccessibleinyourguestVMas
/media/sf_<folder_name>.However,ifyouattempttolistthefilesinthatdirectoryfrom
yourguest,youwilllikelybedenied.Togainfullaccesstothisfolder(asinread-andwriteaccess)forourbookuser,we’llneedtoaddthatUIDtothevboxsfgroup:
$sudousermod-a-Gvboxsfbookuser
LogoutandlogintoyourguestagainorrestarttheguestVMtocompletetheprocess.
www.it-ebooks.info
www.it-ebooks.info
Thebuildenvironment
ToprepareoursystemtobuildtheLinuxkernel,Android,andAndroidapplications,we
needtoinstallandsetupsomekeypiecesofsoftware.ClicktheUbuntudashboardiconat
thetopofthelaunchbarontheleftofyourscreen.Inthesearchbarthatappears,type
termandpressEnter.Aterminalwindowwillopen.Thenexecutethefollowing
commands:
$sudoapt-getupdate
$sudoapt-getinstallapt-filegit-coregnupgflexbisongperfbuildessentialzipcurlzlib1g-devlibc6-devlib32ncurses5-devia32-libs
x11proto-core-devlibx11-devia32-libsdialogliblzo2-devlibxml2-utils
minicom
TypeyandpressEnterwhenaskedwhetheryouwanttocontinue.
www.it-ebooks.info
www.it-ebooks.info
OracleJava6
DownloadthemostrecentJava6SEDevelopmentKit(version6u45)fromtheOracle
Javaarchivewebsite,athttp://www.oracle.com/technetwork/java/javase/archive139210.html.You’llneedthejdk-6u45-linux-x64.binversiontosatisfyGoogle’starget
developmentenvironment.Onceitisdownloaded,executethefollowingcommandsto
installtheJava6JDK:
$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
www.it-ebooks.info
Summary
Inthisappendix,wediscussedGoogle’stargetdevelopmentenvironmentforAndroidand
showedhowtocreateacompatibleenvironment,potentiallyinavirtualmachine.You
shouldfeelfreetomodifyotherelementsofyoursystem,buthavingtheelementsofthis
appendixinstalledwillprovideyouwiththeminimallyviableenvironmentnecessaryto
performallthestepsoutlinedinChapter4,InstallationontheUDOO,andbeyond.
www.it-ebooks.info
Index
A
absoluteauthority
about/Thecaseformore
AccessVectorCache/AccessVectorCache
accessvectors
about/Accessvectors
impersonate/Binderandsecurity
call/Binderandsecurity
set_context_mgr/Binderandsecurity
transfer/Binderandsecurity
ActivityManagerService(AMS)
about/Binderandsecurity
Android
DAC,usingfor/Android’suseofDAC
securitymodel/Android’ssecuritymodel
Android.mk,sepolicy
exploring/Exploringsepolicy’sAndroid.mk
sepolicy,building/Buildingsepolicy
policybuild,controlling/Controllingthepolicybuild
build_policy,defining/Diggingdeeperintobuild_policy
mac_permissions.xml,building/Buildingmac_permissions.xml
seapp_contexts,building/Buildingseapp_contexts
file_contexts,building/Buildingfile_contexts
property_contexts,building/Buildingproperty_contexts
NSAresearchfiles/CurrentNSAresearchfiles
AndroidDebugBridge(adb)
about/UDOOserialandAndroidDebugBridge
AndroidInterfaceDescriptionLanguage(AIDL)/Binder’sarchitecture
AndroidRunTime(ART)/Zygote–applicationspawn
Androidversions
URL/Thepropertyservice
Androidvulnerabilities
about/GlancingatAndroidvulnerabilities
Skypevulnerability/Skypevulnerability
GingerBreak/GingerBreak
CVE-2010-EASY/Rageagainstthecage
MotoChopper/MotoChopper
AOSPdevices
URL/Upgrades–patchesgalore
applabeling
limitations/Limitationsonapplabeling
www.it-ebooks.info
applications/Android’ssecuritymodel
auditddaemon/Theauditddaemon
auditdinternals/Auditdinternals
auditlogs/Auditlogs
auditsystem
about/Theauditsystem
auditddaemon/Theauditddaemon
auditdinternals/Auditdinternals
www.it-ebooks.info
B
Bell-LaPadula(BLP)model
about/Multilevelsecurity
Binder
about/Binder
architecture/Binder’sarchitecture
features/Binder’sarchitecture
andsecurity/Binderandsecurity
binderpatch
URL/Upgrades–patchesgalore
booleansdirectory/Thebooleansdirectory
buildenvironment
about/Thebuildenvironment
build_policy
defining/Diggingdeeperintobuild_policy
www.it-ebooks.info
C
cache_thresholdfile/AccessVectorCache
capabilitiesmodel
about/Capabilitiesmodel
chconcommand/Examplesandtools
classdirectory/Theclassdirectory
CompatibilityDefinitionDocument(CDD)/SettingupCTS
CompatibilityTestSuite(CTS)/Contexts
CompatibilityTestSuitecompliance(CTS)
about/Thebooleansdirectory
URL/Thebooleansdirectory
contexts
about/Contexts
domains,mapping/Contexts
controlproperties/Controlproperties
CTS
URL/Relabelingprocesses
settingup/SettingupCTS
running/RunningCTS
CTSbinary
URL/SettingupCTS
CTSresults
gathering/Gatheringtheresults
CTStestresults/CTStestresults
auditlogs/Auditlogs
CTStestresults/CTStestresults
CVE-2010-EASY/Rageagainstthecage
www.it-ebooks.info
D
/datafilesystem
fixingup/Fixingup/data
DAC
used,forAndroid/Android’suseofDAC
definekeyword/Dynamicdomaintransitions
device
purging/Purgingthedevice
devicepolicy
authoring/Authoringdevicepolicy
adbd/adbd
bootanim/bootanim
debuggerd/debuggerd
drmserver/drmserver
dumpstate/dumpstate
installd/installd
keystore/keystore
mediaserver/mediaserver
netd/netd
rild/rild
servicemanager/servicemanager
surfaceflinger/surfaceflinger
system_server/system_server
toolbox/toolbox
untrusted_app/untrusted_app
vold/vold
watchdogd/watchdogd
wpa/wpa
disablefileinterface/Thedisablefileinterface
dynamicdomaintransitions
about/Dynamicdomaintransitions
dynamictypetransitions/Dynamictypetransitions
dyntransition/ProcFS
www.it-ebooks.info
E
enforcefile/Theenforcenode
enforcing
about/Theenforcenode
enforcingmode
passing/Goingenforcing
existingproperties
relabeling/Relabelingexistingproperties
explicitcontexts
viaseclabel/Explicitcontextsviaseclabel
extendedattributes
labelingwith/Labelingwithextendedattributes
www.it-ebooks.info
F
fieldtrials
about/Fieldtrials
filesystem
locating/Locatingthefilesystem
interrogating/Interrogatingthefilesystem
enforcefile/Theenforcenode
disablefileinterface/Thedisablefileinterface
policyfile/Thepolicyfile
nullfile/Thenullfile
mlsfile/Themlsfile
statusfile/Thestatusfile
AccessVectorCache/AccessVectorCache
booleansdirectory/Thebooleansdirectory
classdirectory/Theclassdirectory
initial_contextsdirectory/Theinitial_contextsdirectory
policy_capabilitiesdirectory/Thepolicy_capabilitiesdirectory
procfs/ProcFS
filesystems
labeling/Labelingfilesystems
fs_use/fs_use
fs_task_use/fs_task_use
fs_use_trans/fs_use_trans
genfscon/genfscon
mountoptions/Mountoptions
extendedattributes/Labelingwithextendedattributes
file_contextsfile/Thefile_contextsfile
dynamictypetransitions/Dynamictypetransitions
file_contexts
building/Buildingfile_contexts
file_contextsfile/Thefile_contextsfile
fixup.py
URL/InterpretingSELinuxdeniallogs
flashing
about/FlashingimageonanSDcard
FLASK
about/Gettingbacktothebasics
fs_task_use/fs_task_use
fs_use/fs_use
fs_use_trans/fs_use_trans
www.it-ebooks.info
G
genfscon/genfscon
getenforcecommand,states
disabled/Fixingthepolicyversion
permissive/Fixingthepolicyversion
enforcing/Fixingthepolicyversion
GingerBreak/GingerBreak
graphicalmenu
settings/Retrievingthesource
groups
changing/Changingownersandgroups
www.it-ebooks.info
I
initial_contextsdirectory/Theinitial_contextsdirectory
initprocess
about/Init–thekingofdaemons
InterprocessCommunication(IPC)
about/Binder
www.it-ebooks.info
J
JavaSELinuxAPI
about/JavaSELinuxAPI
www.it-ebooks.info
K
kernel
SELinux,enablingin/It’salive
kernel-common
URL/Upgrades–patchesgalore
kernel-commonproject
URL/Upgrades–patchesgalore
keys.conf/keys.conf
www.it-ebooks.info
L
labeling
viaproperty_contexts/Labelingviaproperty_contexts
labels
about/Labels
users/Users
roles/Roles
types/Types
LinuxSecurityModule(LSM)
about/Binderandsecurity
www.it-ebooks.info
M
mac_permissions.xml
building/Buildingmac_permissions.xml
mac_permissions.xmlfile
about/Themac_permissions.xmlfile
mlsfile/Themlsfile
MotoChopper/MotoChopper
mountoptions/Mountoptions
multi-levelsecurity(MLS)/Themlsfile
multilevelsecurity(MLS)model
about/Multilevelsecurity
www.it-ebooks.info
N
NationalSecurityAgency(NSA)
about/Binderandsecurity
NSArepositories
URL/Upgrades–patchesgalore
NSAresearchfiles/CurrentNSAresearchfiles
nullfile/Thenullfile
www.it-ebooks.info
O
OracleJava6
about/OracleJava6
OracleJavaarchive
URL/OracleJava6
owners
changing/Changingownersandgroups
www.it-ebooks.info
P
patches
about/Upgrades–patchesgalore
permissionbits
changing/Changingpermissionbits
permissions,onproperties
about/Permissionsonproperties
permissive
about/Theenforcenode
persistentproperties/Persistentproperties
petanalogy
URL/Puttingittogether
about/Puttingittogether
policybuild
controlling/Controllingthepolicybuild
policyfile/Thepolicyfile
policyload
about/Policyload
policypass
about/Secondpolicypass
init/init
shell/shell
init_shell.te/init_shell.te
policyversion
fixing/Fixingthepolicyversion
policy_capabilitiesdirectory/Thepolicy_capabilitiesdirectory
processes
relabeling/Relabelingprocesses
ProcessID(PID)/Binder’sarchitecture,Init–thekingofdaemons
procfs/ProcFS
projects
building/Buildingsubcomponents–targetsandprojects
properties
creating/Creatingandlabelingnewproperties
labeling/Creatingandlabelingnewproperties
propertyservice
about/Thepropertyservice
property_contexts
labelingvia/Labelingviaproperty_contexts
building/Buildingproperty_contexts
www.it-ebooks.info
R
RadioInterfaceLayerDaemon(RILD)/Android’ssecuritymodel,Init–thekingof
daemons
README
testkey/Thecasetosecurethezygote
platform/Thecasetosecurethezygote
shared/Thecasetosecurethezygote
media/Thecasetosecurethezygote
role-basedaccesscontrols(RBAC)
about/Roles
roles,labels/Roles
www.it-ebooks.info
S
seapp_contexts/seapp_contexts
building/Buildingseapp_contexts
security
andBinder/Binderandsecurity
securityid(sid)/Labelingfilesystems
securityidentifier(sid)/Theinitial_contextsdirectory
securitymodel
systemcomponentservices/Android’ssecuritymodel
applications/Android’ssecuritymodel
SELinux
about/Gettingbacktothebasics
implementing/Multilevelsecurity
benefits/Puttingittogether
bestpractices/Complexitiesandbestpractices
complexities/Complexitiesandbestpractices
enabling,inkernel/It’salive
SELinuxdeniallogs
interpreting/InterpretingSELinuxdeniallogs
SELinuxFS
about/Policyload
SELinuxproperties/SELinuxproperties
sepolicy
building/Buildingsepolicy
sepolicy-analyzetool/sepolicy-analyze
sepolicy-checktool/sepolicy-check
SEPolicymaster
updating/UpdatingtoSEPolicymaster
setsockcreatecon()function/Init–thekingofdaemons
sharedfolders
about/Savetimewithsharedfolders
Skypevulnerability/Skypevulnerability
source
retrieving/Retrievingthesource
specialproperties
about/Specialproperties
controlproperties/Controlproperties
persistentproperties/Persistentproperties
SELinuxproperties/SELinuxproperties
standalonetools
about/Standalonetools
sepolicy-check/sepolicy-check
sepolicy-analyze/sepolicy-analyze
www.it-ebooks.info
statusfile/Thestatusfile
subject
about/Gettingbacktothebasics
switch
flipping/Flippingtheswitch
systemapps
about/Thecasetosecurethezygote
systemcomponentservices/Android’ssecuritymodel
systemserver
about/Android’ssecuritymodel
www.it-ebooks.info
T
target
about/Gettingbacktothebasics
targets
building/Buildingsubcomponents–targetsandprojects
tools,filesystems
about/Examplesandtools
/datafilesystem,fixingup/Fixingup/data
security/Asidenoteonsecurity
typeenforcement(TE)
about/Types,Dynamicdomaintransitions
typefieldvalue,filesystemobject
about/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
U
UbuntuLinux12.04
about/UbuntuLinux12.04(precisepangolin)
URL/UbuntuLinux12.04(precisepangolin)
UDOOdocumentation
URL/Retrievingthesource
UDOOserial
about/UDOOserialandAndroidDebugBridge
user-basedaccesscontrols(UBAC)
about/Users
users,labels/Users
userspaceobjectmanager/Thestatusfile
www.it-ebooks.info
V
variables
BOARD_SEPOLICY_DIRS/Controllingthepolicybuild
BOARD_SEPOLICY_UNION/Controllingthepolicybuild
BOARD_SEPOLICY_REPLACE/Controllingthepolicybuild
BOARD_SEPOLICY_IGNORE/Controllingthepolicybuild
VirtualBox
about/VirtualBox
URL/VirtualBox
extensionpack/VirtualBoxextensionpack
guestadditions/VirtualBoxguestadditions
virtualmachine(VM)/Zygote–applicationspawn
www.it-ebooks.info
Z
Zygote
about/Zygote–applicationspawn
zygote
securing/Thecasetosecurethezygote
fortifying/Fortifyingthezygote
socket,plumbing/Plumbingthezygotesocket
mac_permissions.xmlfile/Themac_permissions.xmlfile
keys.conf/keys.conf
seapp_contexts/seapp_contexts
zygotesocket
plumbing/Plumbingthezygotesocket
www.it-ebooks.info