Merge "Allow policy tests to support space in file names"
diff --git a/microdroid/system/private/microdroid_manager.te b/microdroid/system/private/microdroid_manager.te
index 1db1c2a..6539e2c 100644
--- a/microdroid/system/private/microdroid_manager.te
+++ b/microdroid/system/private/microdroid_manager.te
@@ -14,6 +14,11 @@
 # microdroid_manager verifies DM-verity mounted APK payload
 allow microdroid_manager dm_device:blk_file r_file_perms;
 
+# Allow microdroid_manager to do blkflsbuf on instance disk image. The ioctl
+# requires sys_admin cap as well.
+allowxperm microdroid_manager vd_device:blk_file ioctl BLKFLSBUF;
+allow microdroid_manager self:global_capability_class_set sys_admin;
+
 # Allow microdroid_manager to start payload tasks
 domain_auto_trans(microdroid_manager, microdroid_app_exec, microdroid_app)
 domain_auto_trans(microdroid_manager, compos_exec, compos)
diff --git a/private/bpfloader.te b/private/bpfloader.te
index 650117e..02337a0 100644
--- a/private/bpfloader.te
+++ b/private/bpfloader.te
@@ -3,6 +3,9 @@
 type bpfloader_exec, system_file_type, exec_type, file_type;
 typeattribute bpfloader coredomain;
 
+# allow bpfloader to write to the kernel log (starts early)
+allow bpfloader kmsg_device:chr_file w_file_perms;
+
 # These permissions are required to pin ebpf maps & programs.
 allow bpfloader { fs_bpf fs_bpf_tethering }:dir { add_name create search write };
 allow bpfloader { fs_bpf fs_bpf_tethering }:file { create read setattr };
diff --git a/private/compat/32.0/32.0.ignore.cil b/private/compat/32.0/32.0.ignore.cil
index 4d55168..f834ca3 100644
--- a/private/compat/32.0/32.0.ignore.cil
+++ b/private/compat/32.0/32.0.ignore.cil
@@ -47,6 +47,7 @@
     nearby_service
     proc_watermark_boost_factor
     proc_watermark_scale_factor
+    remotelyprovisionedkeypool_service
     resources_manager_service
     selection_toolbar_service
     snapuserd_proxy_socket
diff --git a/private/credstore.te b/private/credstore.te
index 8d87e2f..c410d76 100644
--- a/private/credstore.te
+++ b/private/credstore.te
@@ -4,3 +4,9 @@
 
 # talk to Identity Credential
 hal_client_domain(credstore, hal_identity)
+
+# talk to keymint, specifically for IRemotelyProvisionedComponent/default
+hal_client_domain(credstore, hal_keymint)
+
+# credstore needs to get keys from the remotely provisioned pool
+allow credstore remotelyprovisionedkeypool_service:service_manager find;
diff --git a/private/crosvm.te b/private/crosvm.te
index ec58875..426cb28 100644
--- a/private/crosvm.te
+++ b/private/crosvm.te
@@ -89,3 +89,10 @@
   -app_data_file
   userdebug_or_eng(`-shell_data_file')
 }:file read;
+
+# Only virtualizationservice can run crosvm
+neverallow {
+  domain
+  -crosvm
+  -virtualizationservice
+} crosvm_exec:file no_x_file_perms;
diff --git a/private/priv_app.te b/private/priv_app.te
index 2535222..c7d6ab1 100644
--- a/private/priv_app.te
+++ b/private/priv_app.te
@@ -269,3 +269,6 @@
 
 # Do not follow untrusted app provided symlinks
 neverallow priv_app app_data_file:lnk_file { open read getattr };
+
+# Allow reporting off body events to keystore.
+allow priv_app keystore:keystore2 report_off_body;
diff --git a/private/property_contexts b/private/property_contexts
index 1474d00..7106a51 100644
--- a/private/property_contexts
+++ b/private/property_contexts
@@ -473,7 +473,7 @@
 bluetooth.framework.adapter_address_validation       u:object_r:bluetooth_config_prop:s0 exact bool
 
 bluetooth.device.default_name                        u:object_r:bluetooth_config_prop:s0 exact string
-bluetooth.device.class_of_device                     u:object_r:bluetooth_config_prop:s0 exact uint
+bluetooth.device.class_of_device                     u:object_r:bluetooth_config_prop:s0 exact string
 
 bluetooth.profile.a2dp.sink.enabled                  u:object_r:bluetooth_config_prop:s0 exact bool
 bluetooth.profile.a2dp.source.enabled                u:object_r:bluetooth_config_prop:s0 exact bool
@@ -707,7 +707,7 @@
 
 # shell-only props for ARM memory tagging (MTE).
 arm64.memtag. u:object_r:arm64_memtag_prop:s0 prefix string
-persist.arm64.memtag.mode u:object_r:arm64_memtag_prop:s0 exact string
+persist.arm64.memtag.default u:object_r:arm64_memtag_prop:s0 exact string
 
 net.redirect_socket_calls.hooked u:object_r:socket_hook_prop:s0 exact bool
 
@@ -737,7 +737,9 @@
 ro.boot.verifiedbootstate  u:object_r:bootloader_prop:s0 exact string
 ro.boot.veritymode         u:object_r:bootloader_prop:s0 exact string
 # Properties specific to virtualized deployments of Android
+ro.boot.hypervisor.protected_vm.supported   u:object_r:hypervisor_prop:s0 exact bool
 ro.boot.hypervisor.version                  u:object_r:hypervisor_prop:s0 exact string
+ro.boot.hypervisor.vm.supported             u:object_r:hypervisor_prop:s0 exact bool
 
 # These ro.X properties are set to values of ro.boot.X by property_service.
 ro.baseband   u:object_r:bootloader_prop:s0 exact string
diff --git a/private/service_contexts b/private/service_contexts
index 982eae7..1ada543 100644
--- a/private/service_contexts
+++ b/private/service_contexts
@@ -86,6 +86,7 @@
 android.security.maintenance              u:object_r:keystore_maintenance_service:s0
 android.security.metrics                  u:object_r:keystore_metrics_service:s0
 android.security.remoteprovisioning       u:object_r:remoteprovisioning_service:s0
+android.security.remoteprovisioning.IRemotelyProvisionedKeyPool u:object_r:remotelyprovisionedkeypool_service:s0
 android.service.gatekeeper.IGateKeeperService    u:object_r:gatekeeper_service:s0
 android.system.composd                    u:object_r:compos_service:s0
 android.system.virtualizationservice      u:object_r:virtualization_service:s0
@@ -341,7 +342,7 @@
 translation                               u:object_r:translation_service:s0
 transparency                              u:object_r:transparency_service:s0
 trust                                     u:object_r:trust_service:s0
-tv_iapp                                   u:object_r:tv_iapp_service:s0
+tv_interactive_app                        u:object_r:tv_iapp_service:s0
 tv_input                                  u:object_r:tv_input_service:s0
 tv_tuner_resource_mgr                     u:object_r:tv_tuner_resource_mgr_service:s0
 uce                                       u:object_r:uce_service:s0
diff --git a/private/system_app.te b/private/system_app.te
index 8c1fdbf..77cca3d 100644
--- a/private/system_app.te
+++ b/private/system_app.te
@@ -159,6 +159,7 @@
 # Settings app writes to /dev/stune/foreground/tasks.
 allow system_app cgroup:file w_file_perms;
 allow system_app cgroup_v2:file w_file_perms;
+allow system_app cgroup_v2:dir w_dir_perms;
 
 control_logd(system_app)
 read_runtime_log_tags(system_app)
diff --git a/private/system_server.te b/private/system_server.te
index f70744d..79817ef 100644
--- a/private/system_server.te
+++ b/private/system_server.te
@@ -448,6 +448,7 @@
 allow system_server adbd_socket:sock_file rw_file_perms;
 allow system_server rtc_device:chr_file rw_file_perms;
 allow system_server audio_device:dir r_dir_perms;
+allow system_server uhid_device:chr_file rw_file_perms;
 
 # write access to ALSA interfaces (/dev/snd/*) needed for MIDI
 allow system_server audio_device:chr_file rw_file_perms;
@@ -787,6 +788,9 @@
 # Read the net.464xlat.cellular.enabled property (written by init).
 get_prop(system_server, net_464xlat_fromvendor_prop)
 
+# Read hypervisor capabilities ro.boot.hypervisor.*
+get_prop(system_server, hypervisor_prop)
+
 # Create a socket for connections from debuggerd.
 allow system_server system_ndebug_socket:sock_file create_file_perms;
 
diff --git a/private/virtualizationservice.te b/private/virtualizationservice.te
index 5f6375f..05e1664 100644
--- a/private/virtualizationservice.te
+++ b/private/virtualizationservice.te
@@ -64,6 +64,9 @@
 # Allow virtualizationservice to read/write its own sysprop. Only the process can do so.
 set_prop(virtualizationservice, virtualizationservice_prop)
 
+# Allow virtualizationservice to inspect hypervisor capabilities.
+get_prop(virtualizationservice, hypervisor_prop)
+
 # Allow writing stats to statsd
 unix_socket_send(virtualizationservice, statsdw, statsd)
 
diff --git a/public/hal_wifi_hostapd.te b/public/hal_wifi_hostapd.te
index b508aa5..eeb72ba 100644
--- a/public/hal_wifi_hostapd.te
+++ b/public/hal_wifi_hostapd.te
@@ -5,7 +5,7 @@
 hal_attribute_hwservice(hal_wifi_hostapd, hal_wifi_hostapd_hwservice)
 hal_attribute_service(hal_wifi_hostapd, hal_wifi_hostapd_service)
 
-binder_call(hal_wifi_hostapd_server, servicemanager)
+binder_use(hal_wifi_hostapd_server)
 
 allow hal_wifi_hostapd_server dumpstate:fifo_file write;
 
diff --git a/public/keystore.te b/public/keystore.te
index 9535491..e1c58a4 100644
--- a/public/keystore.te
+++ b/public/keystore.te
@@ -13,6 +13,7 @@
 allow keystore keystore_exec:file { getattr };
 
 add_service(keystore, keystore_service)
+add_service(keystore, remotelyprovisionedkeypool_service)
 add_service(keystore, remoteprovisioning_service)
 allow keystore sec_key_att_app_id_provider_service:service_manager find;
 allow keystore dropbox_service:service_manager find;
diff --git a/public/service.te b/public/service.te
index b7d700b..012a781 100644
--- a/public/service.te
+++ b/public/service.te
@@ -37,6 +37,7 @@
 type netd_service,              service_manager_type;
 type nfc_service,               service_manager_type;
 type radio_service,             service_manager_type;
+type remotelyprovisionedkeypool_service, service_manager_type;
 type remoteprovisioning_service,   service_manager_type;
 type secure_element_service,    service_manager_type;
 type service_manager_service,   service_manager_type;
@@ -61,7 +62,7 @@
 type adb_service, system_api_service, system_server_service, service_manager_type;
 type alarm_service, app_api_service, ephemeral_app_api_service, system_server_service, service_manager_type;
 type app_binding_service, system_server_service, service_manager_type;
-type app_hibernation_service, system_api_service, system_server_service, service_manager_type;
+type app_hibernation_service, app_api_service, system_api_service, system_server_service, service_manager_type;
 type app_integrity_service, system_api_service, system_server_service, service_manager_type;
 type app_prediction_service, app_api_service, system_server_service, service_manager_type;
 type app_search_service, app_api_service, ephemeral_app_api_service, system_server_service, service_manager_type;
diff --git a/public/te_macros b/public/te_macros
index 032534f..5c3438f 100644
--- a/public/te_macros
+++ b/public/te_macros
@@ -196,6 +196,8 @@
 # permission to create a vsock; the client can only connect to VMs
 # that it owns.
 allow $1 virtualizationservice:vsock_socket { getattr read write };
+# Allow client to inspect hypervisor capabilities
+get_prop($1, hypervisor_prop)
 ')
 
 #####################################
diff --git a/tools/sepolicy_generate_compat.py b/tools/sepolicy_generate_compat.py
index 317a00e..17a4d75 100644
--- a/tools/sepolicy_generate_compat.py
+++ b/tools/sepolicy_generate_compat.py
@@ -23,11 +23,23 @@
 import policy
 import shutil
 import subprocess
+import sys
 import tempfile
 import zipfile
 """This tool generates a mapping file for {ver} core sepolicy."""
 
 temp_dir = ''
+compat_cil_template = ";; This file can't be empty.\n"
+ignore_cil_template = """;; new_objects - a collection of types that have been introduced that have no
+;;   analogue in older policy.  Thus, we do not need to map these types to
+;;   previous ones.  Add here to pass checkapi tests.
+(type new_objects)
+(typeattribute new_objects)
+(typeattributeset new_objects
+  ( new_objects
+    %s
+  ))
+"""
 
 
 def check_run(cmd, cwd=None):
@@ -88,12 +100,12 @@
 
     cmd = [
         'debugfs', '-R',
-        'cat system/etc/selinux/mapping/%s.cil' % ver, img_path
+        'cat system/etc/selinux/mapping/10000.0.cil', img_path
     ]
     path = os.path.join(destination, '%s.cil' % ver)
     with open(path, 'wb') as f:
         logging.debug('Extracting %s.cil to %s' % (ver, destination))
-        f.write(check_output(cmd).stdout)
+        f.write(check_output(cmd).stdout.replace(b'10000.0',b'33.0').replace(b'10000_0',b'33_0'))
     return path
 
 
@@ -156,6 +168,28 @@
     return base_policy_path, old_policy_path, pub_policy_cil_path
 
 
+def change_api_level(versioned_type, api_from, api_to):
+    """ Verifies the API version of versioned_type, and changes it to new API level.
+
+    For example, change_api_level("foo_32_0", "32.0", "31.0") will return
+    "foo_31_0".
+
+    Args:
+      versioned_type: string, type with version suffix
+      api_from: string, api version of versioned_type
+      api_to: string, new api version for versioned_type
+
+    Returns:
+      string, a new versioned type
+    """
+    old_suffix = api_from.replace('.', '_')
+    new_suffix = api_to.replace('.', '_')
+    if not versioned_type.endswith(old_suffix):
+        raise ValueError('Version of type %s is different from %s' %
+                         (versioned_type, api_from))
+    return versioned_type.removesuffix(old_suffix) + new_suffix
+
+
 def get_args():
     parser = argparse.ArgumentParser()
     parser.add_argument(
@@ -202,12 +236,10 @@
 
         build_top = get_android_build_top()
         sepolicy_path = os.path.join(build_top, 'system', 'sepolicy')
-        target_compat_path = os.path.join(sepolicy_path, 'private', 'compat',
-                                          args.target_version)
 
         # Step 1. Download system/etc/selinux/mapping/{ver}.cil, and remove types/typeattributes
-        mapping_file = download_mapping_file(args.branch, args.build,
-                                             args.target_version)
+        mapping_file = download_mapping_file(
+            args.branch, args.build, args.target_version, destination=temp_dir)
         mapping_file_cil = mini_parser.MiniCilParser(mapping_file)
         mapping_file_cil.types = set()
         mapping_file_cil.typeattributes = set()
@@ -231,7 +263,110 @@
         logging.info('new types: %s' % new_types)
         logging.info('removed types: %s' % removed_types)
 
-        # TODO: Step 4. Map new types and removed types appropriately
+        # Step 4. Map new types and removed types appropriately, based on the latest mapping
+        latest_compat_path = os.path.join(sepolicy_path, 'private', 'compat',
+                                          args.latest_version)
+        latest_mapping_cil = mini_parser.MiniCilParser(
+            os.path.join(latest_compat_path, args.latest_version + '.cil'))
+        latest_ignore_cil = mini_parser.MiniCilParser(
+            os.path.join(latest_compat_path,
+                         args.latest_version + '.ignore.cil'))
+
+        latest_ignored_types = list(latest_ignore_cil.rTypeattributesets.keys())
+        latest_removed_types = latest_mapping_cil.types
+        logging.debug('types ignored in latest policy: %s' %
+                      latest_ignored_types)
+        logging.debug('types removed in latest policy: %s' %
+                      latest_removed_types)
+
+        target_ignored_types = set()
+        target_removed_types = set()
+        invalid_new_types = set()
+        invalid_mapping_types = set()
+        invalid_removed_types = set()
+
+        logging.info('starting mapping')
+        for new_type in new_types:
+            # Either each new type should be in latest_ignore_cil, or mapped to existing types
+            if new_type in latest_ignored_types:
+                logging.debug('adding %s to ignore' % new_type)
+                target_ignored_types.add(new_type)
+            elif new_type in latest_mapping_cil.rTypeattributesets:
+                latest_mapped_types = latest_mapping_cil.rTypeattributesets[
+                    new_type]
+                target_mapped_types = {change_api_level(t, args.latest_version,
+                                        args.target_version)
+                       for t in latest_mapped_types}
+                logging.debug('mapping %s to %s' %
+                              (new_type, target_mapped_types))
+
+                for t in target_mapped_types:
+                    if t not in mapping_file_cil.typeattributesets:
+                        logging.error(
+                            'Cannot find desired type %s in mapping file' % t)
+                        invalid_mapping_types.add(t)
+                        continue
+                    mapping_file_cil.typeattributesets[t].add(new_type)
+            else:
+                logging.error('no mapping information for new type %s' %
+                              new_type)
+                invalid_new_types.add(new_type)
+
+        for removed_type in removed_types:
+            # Removed type should be in latest_mapping_cil
+            if removed_type in latest_removed_types:
+                logging.debug('adding %s to removed' % removed_type)
+                target_removed_types.add(removed_type)
+            else:
+                logging.error('no mapping information for removed type %s' %
+                              removed_type)
+                invalid_removed_types.add(removed_type)
+
+        error_msg = ''
+
+        if invalid_new_types:
+            error_msg += ('The following new types were not in the latest '
+                          'mapping: %s\n') % sorted(invalid_new_types)
+        if invalid_mapping_types:
+            error_msg += (
+                'The following existing types were not in the '
+                'downloaded mapping file: %s\n') % sorted(invalid_mapping_types)
+        if invalid_removed_types:
+            error_msg += ('The following removed types were not in the latest '
+                          'mapping: %s\n') % sorted(invalid_removed_types)
+
+        if error_msg:
+            error_msg += '\n'
+            error_msg += ('Please make sure the source tree and the build ID is'
+                          ' up to date.\n')
+            sys.exit(error_msg)
+
+        # Step 5. Write to system/sepolicy/private/compat
+        target_compat_path = os.path.join(sepolicy_path, 'private', 'compat',
+                                          args.target_version)
+        target_mapping_file = os.path.join(target_compat_path,
+                                           args.target_version + '.cil')
+        target_compat_file = os.path.join(target_compat_path,
+                                          args.target_version + '.compat.cil')
+        target_ignore_file = os.path.join(target_compat_path,
+                                          args.target_version + '.ignore.cil')
+
+        with open(target_mapping_file, 'w') as f:
+            logging.info('writing %s' % target_mapping_file)
+            if removed_types:
+                f.write(';; types removed from current policy\n')
+                f.write('\n'.join(f'(type {x})' for x in sorted(target_removed_types)))
+                f.write('\n\n')
+            f.write(mapping_file_cil.unparse())
+
+        with open(target_compat_file, 'w') as f:
+            logging.info('writing %s' % target_compat_file)
+            f.write(compat_cil_template)
+
+        with open(target_ignore_file, 'w') as f:
+            logging.info('writing %s' % target_ignore_file)
+            f.write(ignore_cil_template %
+                    ('\n    '.join(sorted(target_ignored_types))))
     finally:
         logging.info('Deleting temporary dir: {}'.format(temp_dir))
         shutil.rmtree(temp_dir)