Merge "Fix vendor contexts files in mixed build"
diff --git a/Android.bp b/Android.bp
index 9a13c9c..d22010c 100644
--- a/Android.bp
+++ b/Android.bp
@@ -661,6 +661,14 @@
     ],
 }
 
+reqd_mask_policy          = [":se_build_files{.reqd_mask}"]
+plat_public_policy        = [":se_build_files{.plat_public}"]
+plat_private_policy       = [":se_build_files{.plat_private}"]
+system_ext_public_policy  = [":se_build_files{.system_ext_public}"]
+system_ext_private_policy = [":se_build_files{.system_ext_private}"]
+product_public_policy     = [":se_build_files{.product_public}"]
+product_private_policy    = [":se_build_files{.product_private}"]
+
 // reqd_policy_mask - a policy.conf file which contains only the bare minimum
 // policy necessary to use checkpolicy.
 //
@@ -671,7 +679,7 @@
 // policy and subsequent removal of CIL policy that should not be exported.
 se_policy_conf {
     name: "reqd_policy_mask.conf",
-    srcs: [":se_build_files{.reqd_mask}"],
+    srcs: reqd_mask_policy,
     installable: false,
 }
 
@@ -706,7 +714,10 @@
 //
 se_policy_conf {
     name: "pub_policy.conf",
-    srcs: [":se_build_files{.product_public}"], // product_ includes system and system_ext
+    srcs: plat_public_policy +
+        system_ext_public_policy +
+        product_public_policy +
+        reqd_mask_policy,
     installable: false,
 }
 
@@ -720,7 +731,9 @@
 
 se_policy_conf {
     name: "system_ext_pub_policy.conf",
-    srcs: [":se_build_files{.system_ext_public}"], // system_ext_public includes system
+    srcs: plat_public_policy +
+        system_ext_public_policy +
+        reqd_mask_policy,
     installable: false,
 }
 
@@ -734,7 +747,8 @@
 
 se_policy_conf {
     name: "plat_pub_policy.conf",
-    srcs: [":se_build_files{.plat_public}"],
+    srcs: plat_public_policy +
+        reqd_mask_policy,
     installable: false,
 }
 
@@ -753,7 +767,8 @@
 // currently being attributized.
 se_policy_conf {
     name: "plat_sepolicy.conf",
-    srcs: [":se_build_files{.plat}"],
+    srcs: plat_public_policy +
+        plat_private_policy,
     installable: false,
 }
 
@@ -766,7 +781,8 @@
 // userdebug_plat_policy.conf - the userdebug version plat_sepolicy.cil
 se_policy_conf {
     name: "userdebug_plat_sepolicy.conf",
-    srcs: [":se_build_files{.plat}"],
+    srcs: plat_public_policy +
+        plat_private_policy,
     build_variant: "userdebug",
     installable: false,
 }
@@ -815,7 +831,10 @@
 // policy which will ship with the device. System_ext policy is not attributized
 se_policy_conf {
     name: "system_ext_sepolicy.conf",
-    srcs: [":se_build_files{.system_ext}"],
+    srcs: plat_public_policy +
+        plat_private_policy +
+        system_ext_public_policy +
+        system_ext_private_policy,
     installable: false,
 }
 
@@ -831,7 +850,12 @@
 // which will ship with the device. Product policy is not attributized
 se_policy_conf {
     name: "product_sepolicy.conf",
-    srcs: [":se_build_files{.product}"],
+    srcs: plat_public_policy +
+        plat_private_policy +
+        system_ext_public_policy +
+        system_ext_private_policy +
+        product_public_policy +
+        product_private_policy,
     installable: false,
 }
 
@@ -1017,7 +1041,8 @@
 //////////////////////////////////
 se_policy_conf {
     name: "general_sepolicy.conf",
-    srcs: [":se_build_files{.plat}"],
+    srcs: plat_public_policy +
+        plat_private_policy,
     build_variant: "user",
     cts: true,
     exclude_build_test: true,
@@ -1032,7 +1057,8 @@
 //////////////////////////////////
 se_policy_conf {
     name: "base_plat_sepolicy.conf",
-    srcs: [":se_build_files{.plat}"],
+    srcs: plat_public_policy +
+        plat_private_policy,
     build_variant: "user",
     installable: false,
 }
@@ -1053,7 +1079,10 @@
 
 se_policy_conf {
     name: "base_system_ext_sepolicy.conf",
-    srcs: [":se_build_files{.system_ext}"],
+    srcs: plat_public_policy +
+        plat_private_policy +
+        system_ext_public_policy +
+        system_ext_private_policy,
     build_variant: "user",
     installable: false,
 }
@@ -1076,7 +1105,12 @@
 
 se_policy_conf {
     name: "base_product_sepolicy.conf",
-    srcs: [":se_build_files{.product}"],
+    srcs: plat_public_policy +
+        plat_private_policy +
+        system_ext_public_policy +
+        system_ext_private_policy +
+        product_public_policy +
+        product_private_policy,
     build_variant: "user",
     installable: false,
 }
@@ -1099,7 +1133,8 @@
 
 se_policy_conf {
     name: "base_plat_pub_policy.conf",
-    srcs: [":se_build_files{.plat_public}"],
+    srcs: plat_public_policy +
+        reqd_mask_policy,
     build_variant: "user",
     installable: false,
 }
@@ -1114,7 +1149,9 @@
 
 se_policy_conf {
     name: "base_system_ext_pub_policy.conf",
-    srcs: [":se_build_files{.system_ext_public}"], // system_ext_public includes system
+    srcs: plat_public_policy +
+        system_ext_public_policy +
+        reqd_mask_policy,
     build_variant: "user",
     installable: false,
 }
@@ -1129,7 +1166,10 @@
 
 se_policy_conf {
     name: "base_product_pub_policy.conf",
-    srcs: [":se_build_files{.product_public}"], // product_ includes system and system_ext
+    srcs: plat_public_policy +
+        system_ext_public_policy +
+        product_public_policy +
+        reqd_mask_policy,
     build_variant: "user",
     installable: false,
 }
diff --git a/build/soong/build_files.go b/build/soong/build_files.go
index 5de6122..8f77e4f 100644
--- a/build/soong/build_files.go
+++ b/build/soong/build_files.go
@@ -17,7 +17,6 @@
 import (
 	"fmt"
 	"path/filepath"
-	"sort"
 	"strings"
 
 	"android/soong/android"
@@ -29,8 +28,8 @@
 
 // se_build_files gathers policy files from sepolicy dirs, and acts like a filegroup. A tag with
 // partition(plat, system_ext, product) and scope(public, private) is used to select directories.
-// Supported tags are: "plat", "plat_public", "system_ext", "system_ext_public", "product",
-// "product_public", and "reqd_mask".
+// Supported tags are: "plat_public", "plat_private", "system_ext_public", "system_ext_private",
+// "product_public", "product_private", and "reqd_mask".
 func buildFilesFactory() android.Module {
 	module := &buildFiles{}
 	module.AddProperties(&module.properties)
@@ -86,114 +85,18 @@
 
 var _ android.OutputFileProducer = (*buildFiles)(nil)
 
-type partition int
-
-const (
-	system partition = iota
-	system_ext
-	product
-)
-
-type scope int
-
-const (
-	public scope = iota
-	private
-)
-
 type sepolicyDir struct {
-	partition partition
-	scope     scope
-	paths     []string
-}
-
-func (p partition) String() string {
-	switch p {
-	case system:
-		return "plat"
-	case system_ext:
-		return "system_ext"
-	case product:
-		return "product"
-	default:
-		panic(fmt.Sprintf("Unknown partition %#v", p))
-	}
+	tag   string
+	paths []string
 }
 
 func (b *buildFiles) GenerateAndroidBuildActions(ctx android.ModuleContext) {
-	// Sepolicy directories should be included in the following order.
-	//   - system_public
-	//   - system_private
-	//   - system_ext_public
-	//   - system_ext_private
-	//   - product_public
-	//   - product_private
-	dirs := []sepolicyDir{
-		sepolicyDir{partition: system, scope: public, paths: []string{filepath.Join(ctx.ModuleDir(), "public")}},
-		sepolicyDir{partition: system, scope: private, paths: []string{filepath.Join(ctx.ModuleDir(), "private")}},
-		sepolicyDir{partition: system_ext, scope: public, paths: ctx.DeviceConfig().SystemExtPublicSepolicyDirs()},
-		sepolicyDir{partition: system_ext, scope: private, paths: ctx.DeviceConfig().SystemExtPrivateSepolicyDirs()},
-		sepolicyDir{partition: product, scope: public, paths: ctx.Config().ProductPublicSepolicyDirs()},
-		sepolicyDir{partition: product, scope: private, paths: ctx.Config().ProductPrivateSepolicyDirs()},
-	}
-
-	if !sort.SliceIsSorted(dirs, func(i, j int) bool {
-		if dirs[i].partition != dirs[j].partition {
-			return dirs[i].partition < dirs[j].partition
-		}
-
-		return dirs[i].scope < dirs[j].scope
-	}) {
-		panic("dirs is not sorted")
-	}
-
-	// Exported cil policy files are built with the following policies.
-	//
-	//   - plat_pub_policy.cil: exported 'system'
-	//   - system_ext_pub_policy.cil: exported 'system' and 'system_ext'
-	//   - pub_policy.cil: exported 'system', 'system_ext', and 'product'
-	//
-	// cil policy files are built with the following policies.
-	//
-	//   - plat_policy.cil: 'system', including private
-	//   - system_ext_policy.cil: 'system_ext', including private
-	//   - product_sepolicy.cil: 'product', including private
-	//
-	// gatherDirsFor collects all needed directories for given partition and scope. For example,
-	//
-	//   - gatherDirsFor(system_ext, private) will return system + system_ext (including private)
-	//   - gatherDirsFor(product, public) will return system + system_ext + product (public only)
-	//
-	// "dirs" should be sorted before calling this.
-	gatherDirsFor := func(p partition, s scope) []string {
-		var ret []string
-
-		for _, d := range dirs {
-			if d.partition <= p && d.scope <= s {
-				ret = append(ret, d.paths...)
-			}
-		}
-
-		return ret
-	}
-
-	reqdMaskDir := filepath.Join(ctx.ModuleDir(), "reqd_mask")
-
 	b.srcs = make(map[string]android.Paths)
-	b.srcs[".reqd_mask"] = b.findSrcsInDirs(ctx, reqdMaskDir)
-
-	for _, p := range []partition{system, system_ext, product} {
-		b.srcs["."+p.String()] = b.findSrcsInDirs(ctx, gatherDirsFor(p, private)...)
-
-		// reqd_mask is needed for public policies
-		b.srcs["."+p.String()+"_public"] = b.findSrcsInDirs(ctx, append(gatherDirsFor(p, public), reqdMaskDir)...)
-	}
-
-	// A special tag, "plat_vendor", includes minimized vendor policies required to boot.
-	//   - system/sepolicy/public
-	//   - system/sepolicy/reqd_mask
-	//   - system/sepolicy/vendor
-	// This is for minimized vendor partition, e.g. microdroid's vendor
-	platVendorDir := filepath.Join(ctx.ModuleDir(), "vendor")
-	b.srcs[".plat_vendor"] = b.findSrcsInDirs(ctx, append(gatherDirsFor(system, public), reqdMaskDir, platVendorDir)...)
+	b.srcs[".reqd_mask"] = b.findSrcsInDirs(ctx, filepath.Join(ctx.ModuleDir(), "reqd_mask"))
+	b.srcs[".plat_public"] = b.findSrcsInDirs(ctx, filepath.Join(ctx.ModuleDir(), "public"))
+	b.srcs[".plat_private"] = b.findSrcsInDirs(ctx, filepath.Join(ctx.ModuleDir(), "private"))
+	b.srcs[".system_ext_public"] = b.findSrcsInDirs(ctx, ctx.DeviceConfig().SystemExtPublicSepolicyDirs()...)
+	b.srcs[".system_ext_private"] = b.findSrcsInDirs(ctx, ctx.DeviceConfig().SystemExtPrivateSepolicyDirs()...)
+	b.srcs[".product_public"] = b.findSrcsInDirs(ctx, ctx.Config().ProductPublicSepolicyDirs()...)
+	b.srcs[".product_private"] = b.findSrcsInDirs(ctx, ctx.Config().ProductPrivateSepolicyDirs()...)
 }
diff --git a/build/soong/policy.go b/build/soong/policy.go
index 82fabe3..8d0e1a4 100644
--- a/build/soong/policy.go
+++ b/build/soong/policy.go
@@ -17,7 +17,9 @@
 import (
 	"fmt"
 	"os"
+	"sort"
 	"strconv"
+	"strings"
 
 	"github.com/google/blueprint/proptools"
 
@@ -31,6 +33,31 @@
 	PolicyVers = 30
 )
 
+// This order should be kept. checkpolicy syntax requires it.
+var policyConfOrder = []string{
+	"security_classes",
+	"initial_sids",
+	"access_vectors",
+	"global_macros",
+	"neverallow_macros",
+	"mls_macros",
+	"mls_decl",
+	"mls",
+	"policy_capabilities",
+	"te_macros",
+	"attributes",
+	"ioctl_defines",
+	"ioctl_macros",
+	"*.te",
+	"roles_decl",
+	"roles",
+	"users",
+	"initial_sid_contexts",
+	"fs_use",
+	"genfs_contexts",
+	"port_contexts",
+}
+
 func init() {
 	android.RegisterModuleType("se_policy_conf", policyConfFactory)
 	android.RegisterModuleType("se_policy_cil", policyCilFactory)
@@ -143,9 +170,25 @@
 	return strconv.FormatBool(ctx.DeviceConfig().BuildDebugfsRestrictionsEnabled())
 }
 
+func findPolicyConfOrder(name string) int {
+	for idx, pattern := range policyConfOrder {
+		if pattern == name || (pattern == "*.te" && strings.HasSuffix(name, ".te")) {
+			return idx
+		}
+	}
+	// name is not matched
+	return len(policyConfOrder)
+}
+
 func (c *policyConf) transformPolicyToConf(ctx android.ModuleContext) android.OutputPath {
 	conf := android.PathForModuleOut(ctx, "conf").OutputPath
 	rule := android.NewRuleBuilder(pctx, ctx)
+
+	srcs := android.PathsForModuleSrc(ctx, c.properties.Srcs)
+	sort.SliceStable(srcs, func(x, y int) bool {
+		return findPolicyConfOrder(srcs[x].Base()) < findPolicyConfOrder(srcs[y].Base())
+	})
+
 	rule.Command().Tool(ctx.Config().PrebuiltBuildTool(ctx, "m4")).
 		Flag("--fatal-warnings").
 		FlagForEachArg("-D ", ctx.DeviceConfig().SepolicyM4Defs()).
@@ -164,7 +207,7 @@
 		FlagWithArg("-D target_requires_insecure_execmem_for_swiftshader=", strconv.FormatBool(ctx.DeviceConfig().RequiresInsecureExecmemForSwiftshader())).
 		FlagWithArg("-D target_enforce_debugfs_restriction=", c.enforceDebugfsRestrictions(ctx)).
 		Flag("-s").
-		Inputs(android.PathsForModuleSrc(ctx, c.properties.Srcs)).
+		Inputs(srcs).
 		Text("> ").Output(conf)
 
 	rule.Build("conf", "Transform policy to conf: "+ctx.ModuleName())
diff --git a/microdroid/TEST_MAPPING b/microdroid/TEST_MAPPING
new file mode 100644
index 0000000..f6e1c4f
--- /dev/null
+++ b/microdroid/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+  "imports": [
+    {
+      "path": "packages/modules/Virtualization"
+    }
+  ]
+}
diff --git a/microdroid/system/private/apkdmverity.te b/microdroid/system/private/apkdmverity.te
index c3f718b..84e1575 100644
--- a/microdroid/system/private/apkdmverity.te
+++ b/microdroid/system/private/apkdmverity.te
@@ -36,7 +36,6 @@
 allow apkdmverity kmsg_device:chr_file w_file_perms;
 
 # apkdmverity is forked from microdroid_manager
-# TODO(inseob): remove this
 allow apkdmverity microdroid_manager:fd use;
 
 # Only microdroid_manager can run apkdmverity
diff --git a/microdroid/system/private/domain.te b/microdroid/system/private/domain.te
index c852268..ad2c645 100644
--- a/microdroid/system/private/domain.te
+++ b/microdroid/system/private/domain.te
@@ -271,6 +271,362 @@
 # Properties that microdroid doesn't have but some still want to read.
 dontaudit domain { heapprofd_prop timezone_prop }:file r_file_perms;
 
+###
+### neverallow rules
+###
+
 # Don't allow raw read/write/open access to generic devices.
 # Rather force a relabel to a more specific type.
 neverallow domain device:chr_file { open read write };
+
+# No executable memory unless backed by an unmodified file
+neverallow * self:process { execmem execheap execstack };
+neverallow * *:file execmod;
+
+# All ioctls on file-like objects (except chr_file and blk_file) and
+# sockets must be restricted to an allowlist.
+neverallowxperm * *:{ dir notdevfile_class_set socket_class_set blk_file } ioctl { 0 };
+
+# b/68014825 and https://android-review.googlesource.com/516535
+# rfc6093 says that processes should not use the TCP urgent mechanism
+neverallowxperm domain domain:socket_class_set ioctl { SIOCATMARK };
+
+# TIOCSTI is only ever used for exploits. Block it.
+# b/33073072, b/7530569
+# http://www.openwall.com/lists/oss-security/2016/09/26/14
+neverallowxperm * devpts:chr_file ioctl TIOCSTI;
+
+# Do not allow any domain other than init to create unlabeled files.
+neverallow { domain -init } unlabeled:dir_file_class_set create;
+
+# Limit device node creation to these allowed domains.
+neverallow {
+  domain
+  -kernel
+  -init
+  -ueventd
+} self:global_capability_class_set mknod;
+
+# No process can map low memory (< CONFIG_LSM_MMAP_MIN_ADDR).
+neverallow * self:memprotect mmap_zero;
+
+# No domain needs mac_override as it is unused by SELinux.
+neverallow * self:global_capability2_class_set mac_override;
+
+# Disallow attempts to set contexts not defined in current policy
+# This helps guarantee that unknown or dangerous contents will not ever
+# be set.
+neverallow * self:global_capability2_class_set mac_admin;
+
+# Once the policy has been loaded there shall be none to modify the policy.
+# It is sealed.
+neverallow * kernel:security load_policy;
+
+# Only init prior to switching context should be able to set enforcing mode.
+# init starts in kernel domain and switches to init domain via setcon in
+# the init.rc, so the setenforce occurs while still in kernel. After
+# switching domains, there is never any need to setenforce again by init.
+neverallow * kernel:security setenforce;
+neverallow { domain -kernel } kernel:security setcheckreqprot;
+
+# No booleans in AOSP policy, so no need to ever set them.
+neverallow * kernel:security setbool;
+
+# Adjusting the AVC cache threshold.
+# Not presently allowed to anything in policy, but possibly something
+# that could be set from init.rc.
+neverallow { domain -init } kernel:security setsecparam;
+
+# Only the kernel hwrng thread should be able to read from the HW RNG.
+neverallow {
+  domain
+  -shell # For CTS, restricted to just getattr in shell.te
+  -ueventd # To create the /dev/hw_random file
+} hw_random_device:chr_file *;
+
+# Ensure that all entrypoint executables are in exec_type.
+neverallow * { file_type -exec_type }:file entrypoint;
+
+# Only init should be able to configure kernel usermodehelpers or
+# security-sensitive proc settings.
+neverallow { domain -init } usermodehelper:file { append write };
+neverallow { domain -init -ueventd } sysfs_usermodehelper:file { append write };
+neverallow { domain -init -vendor_init } proc_security:file { append open read write };
+
+# Init can't do anything with binder calls. If this neverallow rule is being
+# triggered, it's probably due to a service with no SELinux domain.
+neverallow * init:binder *;
+neverallow * vendor_init:binder *;
+
+# Don't allow raw read/write/open access to block_device
+# Rather force a relabel to a more specific type
+neverallow { domain -kernel -init } block_device:blk_file { open read write };
+
+# Do not allow renaming of block files or character files
+# Ability to do so can lead to possible use in an exploit chain
+# e.g. https://googleprojectzero.blogspot.com/2016/12/chrome-os-exploit-one-byte-overflow-and.html
+neverallow * *:{ blk_file chr_file } rename;
+
+# Only the init property service should write to /data/property and /dev/__properties__
+neverallow { domain -init } property_type:file { no_w_file_perms no_x_file_perms };
+neverallow { domain -init } properties_device:file { no_w_file_perms no_x_file_perms };
+neverallow { domain -init } properties_serial:file { no_w_file_perms no_x_file_perms };
+
+# Nobody should be doing writes to /system & /vendor
+# These partitions are intended to be read-only and must never be
+# modified. Doing so would violate important Android security guarantees
+# and invalidate dm-verity signatures.
+neverallow {
+    domain
+    with_asan(`-asan_extract')
+} {
+    system_file_type
+    vendor_file_type
+    exec_type
+}:dir_file_class_set { create write setattr relabelfrom append unlink link rename };
+
+neverallow { domain -kernel with_asan(`-asan_extract') } { system_file_type vendor_file_type exec_type }:dir_file_class_set relabelto;
+
+# Don't allow mounting on top of /system files or directories
+neverallow * exec_type:dir_file_class_set mounton;
+
+# Nothing should be writing to files in the rootfs.
+neverallow * rootfs:file { create write setattr relabelto append unlink link rename };
+
+# Restrict context mounts to specific types marked with
+# the contextmount_type attribute.
+neverallow * {fs_type -contextmount_type}:filesystem relabelto;
+
+# Ensure that context mount types are not writable, to ensure that
+# the write to /system restriction above is not bypassed via context=
+# mount to another type.
+neverallow * { contextmount_type -authfs_fuse }:dir_file_class_set
+    { create relabelfrom relabelto append link rename };
+neverallow domain { contextmount_type -authfs_fuse }:dir_file_class_set { write unlink };
+
+# Do not allow service_manager add for default service labels.
+# Instead domains should use a more specific type such as
+# system_app_service rather than the generic type.
+# New service_types are defined in {,hw,vnd}service.te and new mappings
+# from service name to service_type are defined in {,hw,vnd}service_contexts.
+neverallow * default_android_service:service_manager *;
+
+# Looking up the base class/interface of all HwBinder services is a bad idea.
+# hwservicemanager currently offer such lookups only to make it so that security
+# decisions are expressed in SELinux policy. However, it's unclear whether this
+# lookup has security implications. If it doesn't, hwservicemanager should be
+# modified to not offer this lookup.
+# This rule can be removed if hwservicemanager is modified to not permit these
+# lookups.
+neverallow * hidl_base_hwservice:hwservice_manager find;
+
+neverallow { domain -init -vendor_init } vendor_default_prop:property_service set;
+
+neverallow { domain -init } build_prop:property_service set;
+
+# Only (hw|vnd|)servicemanager should be able to register with binder as the context manager
+# The service managers are only allowed to access their own device node
+neverallow servicemanager hwbinder_device:chr_file no_rw_file_perms;
+neverallow servicemanager vndbinder_device:chr_file no_rw_file_perms;
+neverallow hwservicemanager binder_device:chr_file no_rw_file_perms;
+neverallow hwservicemanager vndbinder_device:chr_file no_rw_file_perms;
+
+# system services cant add vendor services
+neverallow {
+  coredomain
+} vendor_service:service_manager add;
+
+neverallow {
+  domain
+  -tombstoned
+  -crash_dump
+
+  # Processes that can't exec crash_dump
+  -hal_codec2_server
+  -hal_omx_server
+} tombstoned_crash_socket:unix_stream_socket connectto;
+
+# Never allow anyone to connect or write to
+# the tombstoned intercept socket.
+neverallow { domain } tombstoned_intercept_socket:sock_file write;
+neverallow { domain } tombstoned_intercept_socket:unix_stream_socket connectto;
+
+# Android does not support System V IPCs.
+#
+# The reason for this is due to the fact that, by design, they lead to global
+# kernel resource leakage.
+#
+# For example, there is no way to automatically release a SysV semaphore
+# allocated in the kernel when:
+#
+# - a buggy or malicious process exits
+# - a non-buggy and non-malicious process crashes or is explicitly killed.
+#
+# Killing processes automatically to make room for new ones is an
+# important part of Android's application lifecycle implementation. This means
+# that, even assuming only non-buggy and non-malicious code, it is very likely
+# that over time, the kernel global tables used to implement SysV IPCs will fill
+# up.
+neverallow * *:{ shm sem msg msgq } *;
+
+# Do not mount on top of symlinks, fifos, or sockets.
+# Feature parity with Chromium LSM.
+neverallow * { file_type fs_type dev_type }:{ lnk_file fifo_file sock_file } mounton;
+
+# Nobody should be able to execute su on user builds.
+# On userdebug/eng builds, only shell, and
+# su itself execute su.
+neverallow { domain userdebug_or_eng(`-shell -su') } su_exec:file no_x_file_perms;
+
+neverallow { domain -init } proc:{ file dir } mounton;
+
+# Ensure that all types assigned to processes are included
+# in the domain attribute, so that all allow and neverallow rules
+# written on domain are applied to all processes.
+# This is achieved by ensuring that it is impossible to transition
+# from a domain to a non-domain type and vice versa.
+# TODO - rework this: neverallow domain ~domain:process { transition dyntransition };
+neverallow ~domain domain:process { transition dyntransition };
+
+#
+# Only system_app and system_server should be creating or writing
+# their files. The proper way to share files is to setup
+# type transitions to a more specific type or assigning a type
+# to its parent directory via a file_contexts entry.
+# Example type transition:
+#  mydomain.te:file_type_auto_trans(mydomain, system_data_file, new_file_type)
+#
+neverallow {
+  domain
+  -init
+  -vendor_init
+  -toolbox # TODO(b/141108496) We want to remove toolbox
+  with_asan(`-asan_extract')
+} system_data_file:file no_w_file_perms;
+
+#
+# Only these domains should transition to shell domain. This domain is
+# permissible for the "shell user". If you need a process to exec a shell
+# script with differing privilege, define a domain and set up a transition.
+#
+neverallow {
+  domain
+  -adbd
+  -init
+  -runas
+} shell:process { transition dyntransition };
+
+# Minimize read access to shell-writable symlinks.
+# This is to prevent malicious symlink attacks.
+neverallow {
+  domain
+  -shell
+} shell_data_file:lnk_file read;
+
+# In addition to the symlink reading restrictions above, restrict
+# write access to shell owned directories. The /data/local/tmp
+# directory is untrustworthy, and non-allowed domains should
+# not be trusting any content in those directories.
+neverallow {
+  domain
+  -adbd
+  -init
+  -vendor_init
+  -shell
+} shell_data_file:dir no_w_dir_perms;
+
+neverallow {
+  domain
+  -adbd
+  -init
+  -vendor_init
+  -shell
+} shell_data_file:dir { open search };
+
+# servicemanager is the only process which handles the
+# service_manager list request
+neverallow * ~{
+    servicemanager
+    }:service_manager list;
+
+# hwservicemanager is the only process which handles hw list requests
+neverallow * ~{
+    hwservicemanager
+    }:hwservice_manager list;
+
+# only service_manager_types can be added to service_manager
+# TODO - rework this: neverallow * ~service_manager_type:service_manager { add find };
+
+# Prevent assigning non property types to properties
+# TODO - rework this: neverallow * ~property_type:property_service set;
+
+# Domain types should never be assigned to any files other
+# than the /proc/pid files associated with a process. The
+# executable file used to enter a domain should be labeled
+# with its own _exec type, not with the domain type.
+# Conventionally, this looks something like:
+# $ cat mydaemon.te
+# type mydaemon, domain;
+# type mydaemon_exec, exec_type, file_type;
+# init_daemon_domain(mydaemon)
+# $ grep mydaemon file_contexts
+# /system/bin/mydaemon -- u:object_r:mydaemon_exec:s0
+neverallow * domain:file { execute execute_no_trans entrypoint };
+
+# Do not allow access to the generic debugfs label. This is too broad.
+# Instead, if access to part of debugfs is desired, it should have a
+# more specific label.
+neverallow { domain -init -vendor_init } debugfs:{ file lnk_file } no_rw_file_perms;
+
+# Do not allow executable files in debugfs.
+neverallow domain debugfs_type:file { execute execute_no_trans };
+
+# Don't allow access to the FUSE control filesystem, except to init's
+neverallow { domain -init -vendor_init } fusectlfs:file no_rw_file_perms;
+
+# Enforce restrictions on kernel module origin.
+# Do not allow kernel module loading except from system,
+# vendor, and boot partitions.
+neverallow * ~{ system_file_type vendor_file_type rootfs }:system module_load;
+
+# Only allow filesystem caps to be set at build time. Runtime changes
+# to filesystem capabilities are not permitted.
+neverallow * self:global_capability_class_set setfcap;
+
+# Enforce AT_SECURE for executing crash_dump.
+neverallow domain crash_dump:process noatsecure;
+
+# Do not permit non-core domains to register HwBinder services which are
+# guaranteed to be provided by core domains only.
+neverallow ~coredomain coredomain_hwservice:hwservice_manager add;
+
+# Do not permit the registeration of HwBinder services which are guaranteed to
+# be passthrough only (i.e., run in the process of their clients instead of a
+# separate server process).
+neverallow * same_process_hwservice:hwservice_manager add;
+
+# If an already existing file is opened with O_CREAT, the kernel might generate
+# a false report of a create denial. Silence these denials and make sure that
+# inappropriate permissions are not granted.
+
+# These filesystems don't allow files or directories to be created, so the permission
+# to do so should never be granted.
+neverallow domain {
+  proc_type
+  sysfs_type
+}:dir { add_name create link remove_name rename reparent rmdir write };
+
+# cgroupfs directories can be created, but not files within them.
+neverallow domain cgroup:file create;
+neverallow domain cgroup_v2:file create;
+
+# Only apps targetting < Q are allowed to open /dev/ashmem directly.
+# Apps must use ASharedMemory NDK API. Native code must use libcutils API.
+neverallow {
+  domain
+} ashmem_device:chr_file open;
+
+neverallow { domain -init -vendor_init } debugfs_tracing_printk_formats:file *;
+
+# Linux lockdown "integrity" level is enforced for user builds.
+neverallow { domain userdebug_or_eng(`-domain') } self:lockdown integrity;
diff --git a/microdroid/system/private/microdroid_payload.te b/microdroid/system/private/microdroid_payload.te
index 5419f52..2fa101f 100644
--- a/microdroid/system/private/microdroid_payload.te
+++ b/microdroid/system/private/microdroid_payload.te
@@ -31,7 +31,7 @@
 neverallow microdroid_manager { domain -crash_dump -microdroid_payload -apkdmverity -zipfuse }:process transition;
 
 # Allow microdroid_payload to open binder servers via vsock.
-allow microdroid_payload self:vsock_socket { create_socket_perms listen accept };
+allow microdroid_payload self:vsock_socket { create_socket_perms_no_ioctl listen accept };
 
 # Allow microdroid_payload to ioctl /dev/vsock.
 # TODO(b/199259751): remove the below rules
diff --git a/microdroid/system/private/odrefresh.te b/microdroid/system/private/odrefresh.te
index 3dd2d2c..c281896 100644
--- a/microdroid/system/private/odrefresh.te
+++ b/microdroid/system/private/odrefresh.te
@@ -19,5 +19,11 @@
 # the current APEXes.
 allow odrefresh apex_info_file:file r_file_perms;
 
+# Minijail uses pipe for the parent process to signal the child (as a fallback
+# mechanism, since Android does not support minijail's preload).
+# TODO(196109647): We can probably remove this once the minijail preload is
+# supported on Android.
+allow odrefresh compos:fifo_file read;
+
 # Do not audit unused resources from parent processes.
 dontaudit odrefresh compos:fd use;
diff --git a/microdroid/system/private/zipfuse.te b/microdroid/system/private/zipfuse.te
index b88c014..da0cd0f 100644
--- a/microdroid/system/private/zipfuse.te
+++ b/microdroid/system/private/zipfuse.te
@@ -42,7 +42,6 @@
 allow zipfuse extra_apk_file:dir mounton;
 
 # zipfuse is forked from microdroid_manager
-# TODO(inseob): remove this
 allow zipfuse microdroid_manager:fd use;
 
 # Only microdroid_manager can run zipfuse
diff --git a/microdroid/system/public/attributes b/microdroid/system/public/attributes
index 50c2c81..6479c55 100644
--- a/microdroid/system/public/attributes
+++ b/microdroid/system/public/attributes
@@ -195,12 +195,6 @@
 # i.e. files that can be read by lower and written by higher
 attribute mlstrustedobject;
 
-# All domains used for apps.
-attribute appdomain;
-
-# All third party apps (except isolated_app and ephemeral_app)
-attribute untrusted_app_all;
-
 # All domains used for apps with network access.
 attribute netdomain;
 
@@ -260,27 +254,6 @@
 attribute system_writes_mnt_vendor_violators;
 expandattribute system_writes_mnt_vendor_violators false;
 
-# hwservices that are accessible from untrusted applications
-# WARNING: Use of this attribute should be avoided unless
-# absolutely necessary.  It is a temporary allowance to aid the
-# transition to treble and will be removed in a future platform
-# version, requiring all hwservices that are labeled with this
-# attribute to be submitted to AOSP in order to maintain their
-# app-visibility.
-attribute untrusted_app_visible_hwservice_violators;
-expandattribute untrusted_app_visible_hwservice_violators false;
-
-# halserver domains that are accessible to untrusted applications.  These
-# domains are typically those hosting  hwservices attributed by the
-# untrusted_app_visible_hwservice_violators.
-# WARNING: Use of this attribute should be avoided unless absolutely necessary.
-# It is a temporary allowance to aid the transition to treble and will be
-# removed in the future platform version, requiring all halserver domains that
-# are labeled with this attribute to be submitted to AOSP in order to maintain
-# their app-visibility.
-attribute untrusted_app_visible_halserver_violators;
-expandattribute untrusted_app_visible_halserver_violators false;
-
 # PDX services
 attribute pdx_endpoint_dir_type;
 attribute pdx_endpoint_socket_type;
diff --git a/private/charger_type.te b/private/charger_type.te
index cb699de..3647496 100644
--- a/private/charger_type.te
+++ b/private/charger_type.te
@@ -15,18 +15,18 @@
     -vendor_init
 } charger_config_prop:property_service set;
 
-# charger_status_prop: Only init, vendor_init, charger, and hal_health_server
+# charger_status_prop: Only init, vendor_init, charger, and charger_vendor
 # are allowed to set it
 neverallow {
     domain
     -init
     -vendor_init
     -charger
-    -hal_health_server
+    -charger_vendor
 } charger_status_prop:property_service set;
 
 # Both charger_config_prop and charger_status_prop:
-# Only init, vendor_init, dumpstate, charger, and hal_health_server
+# Only init, vendor_init, dumpstate, charger, and charger_vendor
 # are allowed to read it
 neverallow {
     domain
@@ -34,5 +34,5 @@
     -dumpstate
     -vendor_init
     -charger
-    -hal_health_server
+    -charger_vendor
 } { charger_config_prop charger_status_prop }:file no_rw_file_perms;
diff --git a/private/compat/32.0/32.0.ignore.cil b/private/compat/32.0/32.0.ignore.cil
index 6eb9e46..dce2649 100644
--- a/private/compat/32.0/32.0.ignore.cil
+++ b/private/compat/32.0/32.0.ignore.cil
@@ -8,6 +8,7 @@
     apexd_select_prop
     artd_service
     attestation_verification_service
+    charger_vendor
     device_config_nnapi_native_prop
     dice_maintenance_service
     dice_node_service
@@ -37,6 +38,7 @@
     locale_service
     proc_watermark_boost_factor
     proc_watermark_scale_factor
+    selection_toolbar_service
     snapuserd_proxy_socket
     supplemental_process_service
     sysfs_fs_fuse_bpf
diff --git a/private/netd.te b/private/netd.te
index 670a4bf..d87b9a6 100644
--- a/private/netd.te
+++ b/private/netd.te
@@ -9,6 +9,9 @@
 domain_auto_trans(netd, clatd_exec, clatd)
 allow netd clatd:process signal;
 
+# Allow netd to setup packet socket and pass to clatd
+allow netd self:packet_socket { bind create setopt };
+
 # give netd permission to setup iptables rule with xt_bpf, attach program to cgroup, and read/write
 # the map created by bpfloader
 allow netd bpfloader:bpf { prog_run map_read map_write };
diff --git a/private/service_contexts b/private/service_contexts
index 327b4f7..c378aec 100644
--- a/private/service_contexts
+++ b/private/service_contexts
@@ -274,6 +274,7 @@
 search_ui                                 u:object_r:search_ui_service:s0
 secure_element                            u:object_r:secure_element_service:s0
 sec_key_att_app_id_provider               u:object_r:sec_key_att_app_id_provider_service:s0
+selection_toolbar                         u:object_r:selection_toolbar_service:s0
 sensorservice                             u:object_r:sensorservice_service:s0
 sensor_privacy                            u:object_r:sensor_privacy_service:s0
 serial                                    u:object_r:serial_service:s0
diff --git a/public/charger_vendor.te b/public/charger_vendor.te
new file mode 100644
index 0000000..2dd106f
--- /dev/null
+++ b/public/charger_vendor.te
@@ -0,0 +1,4 @@
+# Context when health HAL runs charger mode
+
+type charger_vendor, charger_type, domain;
+hal_server_domain(charger_vendor, hal_health)
diff --git a/public/hal_nlinterceptor.te b/public/hal_nlinterceptor.te
index 2076de8..1a738a5 100644
--- a/public/hal_nlinterceptor.te
+++ b/public/hal_nlinterceptor.te
@@ -5,4 +5,4 @@
 
 allow hal_nlinterceptor self:global_capability_class_set net_admin;
 allow hal_nlinterceptor self:netlink_generic_socket create_socket_perms_no_ioctl;
-allow hal_nlinterceptor self:netlink_route_socket { nlmsg_readpriv nlmsg_write };
+allow hal_nlinterceptor self:netlink_route_socket { create_socket_perms_no_ioctl nlmsg_readpriv nlmsg_write };
diff --git a/public/service.te b/public/service.te
index 9fb8df3..e4cdc13 100644
--- a/public/service.te
+++ b/public/service.te
@@ -193,6 +193,7 @@
 type search_service, app_api_service, ephemeral_app_api_service, system_server_service, service_manager_type;
 type search_ui_service, app_api_service, system_server_service, service_manager_type;
 type sec_key_att_app_id_provider_service, app_api_service, system_server_service, service_manager_type;
+type selection_toolbar_service, app_api_service, ephemeral_app_api_service, system_server_service, service_manager_type;
 type sensorservice_service, app_api_service, ephemeral_app_api_service, system_server_service, service_manager_type;
 type sensor_privacy_service, app_api_service, ephemeral_app_api_service, system_server_service, service_manager_type;
 type serial_service, system_api_service, system_server_service, service_manager_type;
diff --git a/vendor/hal_health_default.te b/vendor/hal_health_default.te
index 9b2b921..a48c7b8 100644
--- a/vendor/hal_health_default.te
+++ b/vendor/hal_health_default.te
@@ -4,3 +4,7 @@
 
 type hal_health_default_exec, exec_type, vendor_file_type, file_type;
 init_daemon_domain(hal_health_default)
+
+# When executing the service in offline-charging mode,
+# allow to transition to charger_vendor domain.
+domain_trans(init, hal_health_default_exec, charger_vendor)