Merge changes from topic "privapp_allowlist_prop"

* changes:
  add privapp_allowlist property to android_app
  Add script for modifying privapp permission allowlists
This commit is contained in:
Sam Delmerico
2023-05-04 13:57:17 +00:00
committed by Gerrit Code Review
8 changed files with 287 additions and 8 deletions

View File

@@ -1828,6 +1828,7 @@ type androidApp interface {
Certificate() java.Certificate
BaseModuleName() string
LintDepSets() java.LintDepSets
PrivAppAllowlist() android.OptionalPath
}
var _ androidApp = (*java.AndroidApp)(nil)
@@ -1848,7 +1849,7 @@ func sanitizedBuildIdForPath(ctx android.BaseModuleContext) string {
return buildId
}
func apexFileForAndroidApp(ctx android.BaseModuleContext, aapp androidApp) apexFile {
func apexFilesForAndroidApp(ctx android.BaseModuleContext, aapp androidApp) []apexFile {
appDir := "app"
if aapp.Privileged() {
appDir = "priv-app"
@@ -1870,7 +1871,15 @@ func apexFileForAndroidApp(ctx android.BaseModuleContext, aapp androidApp) apexF
}); ok {
af.overriddenPackageName = app.OverriddenManifestPackageName()
}
return af
apexFiles := []apexFile{af}
if allowlist := aapp.PrivAppAllowlist(); allowlist.Valid() {
dirInApex := filepath.Join("etc", "permissions")
privAppAllowlist := newApexFile(ctx, allowlist.Path(), aapp.BaseModuleName()+"privapp", dirInApex, etc, aapp)
apexFiles = append(apexFiles, privAppAllowlist)
}
return apexFiles
}
func apexFileForRuntimeResourceOverlay(ctx android.BaseModuleContext, rro java.RuntimeResourceOverlayModule) apexFile {
@@ -2315,12 +2324,12 @@ func (a *apexBundle) depVisitor(vctx *visitorContext, ctx android.ModuleContext,
case androidAppTag:
switch ap := child.(type) {
case *java.AndroidApp:
vctx.filesInfo = append(vctx.filesInfo, apexFileForAndroidApp(ctx, ap))
vctx.filesInfo = append(vctx.filesInfo, apexFilesForAndroidApp(ctx, ap)...)
return true // track transitive dependencies
case *java.AndroidAppImport:
vctx.filesInfo = append(vctx.filesInfo, apexFileForAndroidApp(ctx, ap))
vctx.filesInfo = append(vctx.filesInfo, apexFilesForAndroidApp(ctx, ap)...)
case *java.AndroidTestHelperApp:
vctx.filesInfo = append(vctx.filesInfo, apexFileForAndroidApp(ctx, ap))
vctx.filesInfo = append(vctx.filesInfo, apexFilesForAndroidApp(ctx, ap)...)
case *java.AndroidAppSet:
appDir := "app"
if ap.Privileged() {

View File

@@ -6045,6 +6045,8 @@ func TestApexWithApps(t *testing.T) {
sdk_version: "current",
system_modules: "none",
privileged: true,
privapp_allowlist: "perms.xml",
package_name: "com.android.AppFooPriv",
stl: "none",
apex_available: [ "myapex" ],
}
@@ -6074,6 +6076,7 @@ func TestApexWithApps(t *testing.T) {
ensureContains(t, copyCmds, "image.apex/app/AppFoo@TEST.BUILD_ID/AppFoo.apk")
ensureContains(t, copyCmds, "image.apex/priv-app/AppFooPriv@TEST.BUILD_ID/AppFooPriv.apk")
ensureContains(t, copyCmds, "image.apex/etc/permissions/privapp_allowlist_com.android.AppFooPriv.xml")
appZipRule := ctx.ModuleForTests("AppFoo", "android_common_apex10000").Description("zip jni libs")
// JNI libraries are uncompressed

View File

@@ -33,8 +33,17 @@ import (
func init() {
RegisterAppBuildComponents(android.InitRegistrationContext)
pctx.HostBinToolVariable("ModifyAllowlistCmd", "modify_permissions_allowlist")
}
var (
modifyAllowlist = pctx.AndroidStaticRule("modifyAllowlist",
blueprint.RuleParams{
Command: "${ModifyAllowlistCmd} $in $packageName $out",
CommandDeps: []string{"${ModifyAllowlistCmd}"},
}, "packageName")
)
func RegisterAppBuildComponents(ctx android.RegistrationContext) {
ctx.RegisterModuleType("android_app", AndroidAppFactory)
ctx.RegisterModuleType("android_test", AndroidTestFactory)
@@ -115,6 +124,9 @@ type appProperties struct {
// Prefer using other specific properties if build behaviour must be changed; avoid using this
// flag for anything but neverallow rules (unless the behaviour change is invisible to owners).
Updatable *bool
// Specifies the file that contains the allowlist for this app.
Privapp_allowlist *string `android:"path"`
}
// android_app properties that can be overridden by override_android_app
@@ -179,6 +191,8 @@ type AndroidApp struct {
android.ApexBundleDepsInfo
javaApiUsedByOutputFile android.ModuleOutPath
privAppAllowlist android.OptionalPath
}
func (a *AndroidApp) IsInstallable() bool {
@@ -205,6 +219,10 @@ func (a *AndroidApp) JniCoverageOutputs() android.Paths {
return a.jniCoverageOutputs
}
func (a *AndroidApp) PrivAppAllowlist() android.OptionalPath {
return a.privAppAllowlist
}
var _ AndroidLibraryDependency = (*AndroidApp)(nil)
type Certificate struct {
@@ -269,6 +287,10 @@ func (a *AndroidApp) OverridablePropertiesDepsMutator(ctx android.BottomUpMutato
ctx.AddDependency(ctx.Module(), certificateTag, cert)
}
if a.appProperties.Privapp_allowlist != nil && !Bool(a.appProperties.Privileged) {
ctx.PropertyErrorf("privapp_allowlist", "privileged must be set in order to use privapp_allowlist")
}
for _, cert := range a.appProperties.Additional_certificates {
cert = android.SrcIsModule(cert)
if cert != "" {
@@ -598,6 +620,27 @@ func (a *AndroidApp) InstallApkName() string {
return a.installApkName
}
func (a *AndroidApp) createPrivappAllowlist(ctx android.ModuleContext) *android.OutputPath {
if a.appProperties.Privapp_allowlist == nil {
return nil
}
if a.overridableAppProperties.Package_name == nil {
ctx.PropertyErrorf("privapp_allowlist", "package_name must be set to use privapp_allowlist")
}
packageName := *a.overridableAppProperties.Package_name
fileName := "privapp_allowlist_" + packageName + ".xml"
outPath := android.PathForModuleOut(ctx, fileName).OutputPath
ctx.Build(pctx, android.BuildParams{
Rule: modifyAllowlist,
Input: android.PathForModuleSrc(ctx, *a.appProperties.Privapp_allowlist),
Output: outPath,
Args: map[string]string{
"packageName": packageName,
},
})
return &outPath
}
func (a *AndroidApp) generateAndroidBuildActions(ctx android.ModuleContext) {
var apkDeps android.Paths
@@ -733,18 +776,27 @@ func (a *AndroidApp) generateAndroidBuildActions(ctx android.ModuleContext) {
BuildBundleModule(ctx, bundleFile, a.exportPackage, jniJarFile, dexJarFile)
a.bundleFile = bundleFile
allowlist := a.createPrivappAllowlist(ctx)
if allowlist != nil {
a.privAppAllowlist = android.OptionalPathForPath(allowlist)
}
apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
// Install the app package.
if (Bool(a.Module.properties.Installable) || ctx.Host()) && apexInfo.IsForPlatform() &&
!a.appProperties.PreventInstall {
shouldInstallAppPackage := (Bool(a.Module.properties.Installable) || ctx.Host()) && apexInfo.IsForPlatform() && !a.appProperties.PreventInstall
if shouldInstallAppPackage {
var extraInstalledPaths android.Paths
for _, extra := range a.extraOutputFiles {
installed := ctx.InstallFile(a.installDir, extra.Base(), extra)
extraInstalledPaths = append(extraInstalledPaths, installed)
}
ctx.InstallFile(a.installDir, a.outputFile.Base(), a.outputFile, extraInstalledPaths...)
if a.privAppAllowlist.Valid() {
installPath := android.PathForModuleInstall(ctx, "etc", "permissions")
ctx.InstallFile(installPath, a.privAppAllowlist.Path().Base(), a.privAppAllowlist.Path())
}
}
a.buildAppDependencyInfo(ctx)

View File

@@ -423,6 +423,10 @@ func (a *AndroidAppImport) ProvenanceMetaDataFile() android.OutputPath {
return a.provenanceMetaDataFile
}
func (a *AndroidAppImport) PrivAppAllowlist() android.OptionalPath {
return android.OptionalPath{}
}
var dpiVariantGroupType reflect.Type
var archVariantGroupType reflect.Type
var supportedDpis = []string{"ldpi", "mdpi", "hdpi", "xhdpi", "xxhdpi", "xxxhdpi"}

View File

@@ -3539,3 +3539,51 @@ func TestTargetSdkVersionMtsTests(t *testing.T) {
android.AssertStringDoesContain(t, testCase.desc, manifestFixerArgs, "--targetSdkVersion "+testCase.targetSdkVersionExpected)
}
}
func TestPrivappAllowlist(t *testing.T) {
testJavaError(t, "privileged must be set in order to use privapp_allowlist", `
android_app {
name: "foo",
srcs: ["a.java"],
privapp_allowlist: "perms.xml",
}
`)
result := PrepareForTestWithJavaDefaultModules.RunTestWithBp(
t,
`
android_app {
name: "foo",
srcs: ["a.java"],
privapp_allowlist: "perms.xml",
privileged: true,
package_name: "com.android.foo",
sdk_version: "current",
}
override_android_app {
name: "bar",
base: "foo",
package_name: "com.google.android.foo",
}
`,
)
app := result.ModuleForTests("foo", "android_common")
overrideApp := result.ModuleForTests("foo", "android_common_bar")
// verify that privapp allowlist is created
app.Output("out/soong/.intermediates/foo/android_common/privapp_allowlist_com.android.foo.xml")
overrideApp.Output("out/soong/.intermediates/foo/android_common_bar/privapp_allowlist_com.google.android.foo.xml")
expectedAllowlist := "perms.xml"
actualAllowlist := app.Rule("modifyAllowlist").Input.String()
if expectedAllowlist != actualAllowlist {
t.Errorf("expected allowlist to be %q; got %q", expectedAllowlist, actualAllowlist)
}
overrideActualAllowlist := overrideApp.Rule("modifyAllowlist").Input.String()
if expectedAllowlist != overrideActualAllowlist {
t.Errorf("expected override allowlist to be %q; got %q", expectedAllowlist, overrideActualAllowlist)
}
// verify that permissions are copied to device
app.Output("out/soong/target/product/test_device/system/etc/permissions/privapp_allowlist_com.android.foo.xml")
overrideApp.Output("out/soong/target/product/test_device/system/etc/permissions/privapp_allowlist_com.google.android.foo.xml")
}

View File

@@ -237,3 +237,20 @@ sh_binary_host {
name: "jars-to-module-info-java",
src: "jars-to-module-info-java.sh",
}
python_binary_host {
name: "modify_permissions_allowlist",
main: "modify_permissions_allowlist.py",
srcs: [
"modify_permissions_allowlist.py",
],
}
python_test_host {
name: "modify_permissions_allowlist_test",
main: "modify_permissions_allowlist_test.py",
srcs: [
"modify_permissions_allowlist_test.py",
"modify_permissions_allowlist.py",
],
}

View File

@@ -0,0 +1,70 @@
#!/usr/bin/env python
#
# Copyright (C) 2022 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""A tool for modifying privileged permission allowlists."""
from __future__ import print_function
import argparse
import sys
from xml.dom import minidom
class InvalidRootNodeException(Exception):
pass
class InvalidNumberOfPrivappPermissionChildren(Exception):
pass
def modify_allowlist(allowlist_dom, package_name):
if allowlist_dom.documentElement.tagName != 'permissions':
raise InvalidRootNodeException
nodes = allowlist_dom.getElementsByTagName('privapp-permissions')
if nodes.length != 1:
raise InvalidNumberOfPrivappPermissionChildren
privapp_permissions = nodes[0]
privapp_permissions.setAttribute('package', package_name)
def parse_args():
"""Parse commandline arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('input', help='input allowlist template file')
parser.add_argument(
'package_name', help='package name to use in the allowlist'
)
parser.add_argument('output', help='output allowlist file')
return parser.parse_args()
def main():
try:
args = parse_args()
doc = minidom.parse(args.input)
modify_allowlist(doc, args.package_name)
with open(args.output, 'w') as output_file:
doc.writexml(output_file, encoding='utf-8')
except Exception as err:
print('error: ' + str(err), file=sys.stderr)
sys.exit(-1)
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,76 @@
#!/usr/bin/env python
#
# Copyright (C) 2022 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Unit tests for modify_permissions_allowlist.py."""
from __future__ import print_function
import unittest
from xml.dom import minidom
from modify_permissions_allowlist import InvalidRootNodeException, InvalidNumberOfPrivappPermissionChildren, modify_allowlist
class ModifyPermissionsAllowlistTest(unittest.TestCase):
def test_invalid_root(self):
xml_data = '<foo></foo>'
xml_dom = minidom.parseString(xml_data)
self.assertRaises(InvalidRootNodeException, modify_allowlist, xml_dom, 'x')
def test_no_packages(self):
xml_data = '<permissions></permissions>'
xml_dom = minidom.parseString(xml_data)
self.assertRaises(
InvalidNumberOfPrivappPermissionChildren, modify_allowlist, xml_dom, 'x'
)
def test_multiple_packages(self):
xml_data = (
'<permissions>'
' <privapp-permissions package="foo.bar"></privapp-permissions>'
' <privapp-permissions package="bar.baz"></privapp-permissions>'
'</permissions>'
)
xml_dom = minidom.parseString(xml_data)
self.assertRaises(
InvalidNumberOfPrivappPermissionChildren, modify_allowlist, xml_dom, 'x'
)
def test_modify_package_name(self):
xml_data = (
'<permissions>'
' <privapp-permissions package="foo.bar">'
' <permission name="myperm1"/>'
' </privapp-permissions>'
'</permissions>'
)
xml_dom = minidom.parseString(xml_data)
modify_allowlist(xml_dom, 'bar.baz')
expected_data = (
'<?xml version="1.0" ?>'
'<permissions>'
' <privapp-permissions package="bar.baz">'
' <permission name="myperm1"/>'
' </privapp-permissions>'
'</permissions>'
)
self.assertEqual(expected_data, xml_dom.toxml())
if __name__ == '__main__':
unittest.main(verbosity=2)