Move tests from treble_sepolicy_tests

Contrast to its name, sepolicy_tests also contains tests related to
Treble. Also tests other than the compat mapping test in
treble_sepoliy_tests don't need to be run several times.

Moving tests except for compat mapping test to sepolicy_tests to
simplify treble_sepolicy_tests and to reduce build time.

Bug: 288807412
Test: m selinux_policy
Test: atest SELinuxHostTest
Change-Id: I102fa48faf49b7028dc1bb5f21de65fa99babe6f
diff --git a/tests/sepolicy_tests.py b/tests/sepolicy_tests.py
index 63144dd..4ef161b 100644
--- a/tests/sepolicy_tests.py
+++ b/tests/sepolicy_tests.py
@@ -84,8 +84,11 @@
     return pol.AssertPathTypesHaveAttr(partitions, exceptions, "vendor_file_type")
 
 def TestCoreDataTypeViolations(pol):
-    return pol.AssertPathTypesHaveAttr(["/data/"], ["/data/vendor",
+    ret = pol.AssertPathTypesHaveAttr(["/data/"], ["/data/vendor",
             "/data/vendor_ce", "/data/vendor_de"], "core_data_file_type")
+    ret += pol.AssertPathTypesDoNotHaveAttr(["/data/vendor/", "/data/vendor_ce/",
+        "/data/vendor_de/"], [], "core_data_file_type")
+    return ret
 
 def TestPropertyTypeViolations(pol):
     return pol.AssertPropertyOwnersAreExclusive()
@@ -115,7 +118,152 @@
     return pol.AssertPathTypesHaveAttr(["/dev/dma_heap/"], [],
                                        "dmabuf_heap_device_type")
 
+def TestCoredomainViolations(test_policy):
+    # verify that all domains launched from /system have the coredomain
+    # attribute
+    ret = ""
 
+    for d in test_policy.alldomains:
+        domain = test_policy.alldomains[d]
+        if domain.fromSystem and domain.fromVendor:
+            ret += "The following domain is system and vendor: " + d + "\n"
+
+    for domain in test_policy.alldomains.values():
+        ret += domain.error
+
+    violators = []
+    for d in test_policy.alldomains:
+        domain = test_policy.alldomains[d]
+        if domain.fromSystem and "coredomain" not in domain.attributes:
+                violators.append(d);
+    if len(violators) > 0:
+        ret += "The following domain(s) must be associated with the "
+        ret += "\"coredomain\" attribute because they are executed off of "
+        ret += "/system:\n"
+        ret += " ".join(str(x) for x in sorted(violators)) + "\n"
+
+    # verify that all domains launched form /vendor do not have the coredomain
+    # attribute
+    violators = []
+    for d in test_policy.alldomains:
+        domain = test_policy.alldomains[d]
+        if domain.fromVendor and "coredomain" in domain.attributes:
+            violators.append(d)
+    if len(violators) > 0:
+        ret += "The following domains must not be associated with the "
+        ret += "\"coredomain\" attribute because they are executed off of "
+        ret += "/vendor or /system/vendor:\n"
+        ret += " ".join(str(x) for x in sorted(violators)) + "\n"
+
+    return ret
+
+def TestViolatorAttribute(test_policy, attribute):
+    # TODO(b/113124961): re-enable once all violator attributes are removed.
+    return ""
+
+    # ret = ""
+    # return ret
+
+    # violators = test_policy.DomainsWithAttribute(attribute)
+    # if len(violators) > 0:
+    #    ret += "SELinux: The following domains violate the Treble ban "
+    #    ret += "against use of the " + attribute + " attribute: "
+    #    ret += " ".join(str(x) for x in sorted(violators)) + "\n"
+    # return ret
+
+def TestViolatorAttributes(test_policy):
+    ret = ""
+    ret += TestViolatorAttribute(test_policy, "socket_between_core_and_vendor_violators")
+    ret += TestViolatorAttribute(test_policy, "vendor_executes_system_violators")
+    return ret
+
+def TestIsolatedAttributeConsistency(test_policy):
+    permissionAllowList = {
+        # access given from technical_debt.cil
+        "codec2_config_prop" : ["file"],
+        "device_config_nnapi_native_prop":["file"],
+        "hal_allocator_default":["binder", "fd"],
+        "hal_codec2": ["binder", "fd"],
+        "hal_codec2_hwservice":["hwservice_manager"],
+        "hal_graphics_allocator": ["binder", "fd"],
+        "hal_graphics_allocator_service":["service_manager"],
+        "hal_graphics_allocator_hwservice":["hwservice_manager"],
+        "hal_graphics_allocator_server":["binder", "service_manager"],
+        "hal_graphics_mapper_hwservice":["hwservice_manager"],
+        "hal_neuralnetworks": ["binder", "fd"],
+        "hal_neuralnetworks_service": ["service_manager"],
+        "hal_neuralnetworks_hwservice":["hwservice_manager"],
+        "hal_omx_hwservice":["hwservice_manager"],
+        "hidl_allocator_hwservice":["hwservice_manager"],
+        "hidl_manager_hwservice":["hwservice_manager"],
+        "hidl_memory_hwservice":["hwservice_manager"],
+        "hidl_token_hwservice":["hwservice_manager"],
+        "hwservicemanager":["binder"],
+        "hwservicemanager_prop":["file"],
+        "mediacodec":["binder", "fd"],
+        "mediaswcodec":["binder", "fd"],
+        "media_variant_prop":["file"],
+        "nnapi_ext_deny_product_prop":["file"],
+        "servicemanager":["fd"],
+        "toolbox_exec": ["file"],
+        # extra types being granted to isolated_compute_app
+        "isolated_compute_allowed":["service_manager", "chr_file"],
+    }
+
+    def resolveHalServerSubtype(target):
+        # permission given as a client in technical_debt.cil
+        hal_server_attributes = [
+            "hal_codec2_server",
+            "hal_graphics_allocator_server",
+            "hal_neuralnetworks_server"]
+
+        for attr in hal_server_attributes:
+            if target in test_policy.pol.QueryTypeAttribute(Type=attr, IsAttr=True):
+                return attr.rsplit("_", 1)[0]
+        return target
+
+    def checkIsolatedComputeAllowed(tctx, tclass):
+        # check if the permission is in isolated_compute_allowed
+        allowedMemberTypes = test_policy.pol.QueryTypeAttribute(Type="isolated_compute_allowed_service", IsAttr=True) \
+            .union(test_policy.pol.QueryTypeAttribute(Type="isolated_compute_allowed_device", IsAttr=True))
+        return tctx in allowedMemberTypes and tclass in permissionAllowList["isolated_compute_allowed"]
+
+    def checkPermissions(permissions):
+        violated_permissions = []
+        for perm in permissions:
+            tctx, tclass, p = perm.split(":")
+            tctx = resolveHalServerSubtype(tctx)
+            # check unwanted permissions
+            if not checkIsolatedComputeAllowed(tctx, tclass) and \
+                ( tctx not in permissionAllowList \
+                    or tclass not in permissionAllowList[tctx] \
+                    or ( p == "write") \
+                    or ( p == "rw_file_perms") ):
+                violated_permissions += [perm]
+        return violated_permissions
+
+    ret = ""
+
+    isolatedMemberTypes = test_policy.pol.QueryTypeAttribute(Type="isolated_app_all", IsAttr=True)
+    baseRules = test_policy.pol.QueryExpandedTERule(scontext=["isolated_app"])
+    basePermissionSet = set([":".join([rule.tctx, rule.tclass, perm])
+                            for rule in baseRules for perm in rule.perms])
+    for subType in isolatedMemberTypes:
+        if subType == "isolated_app" : continue
+        currentTypeRule = test_policy.pol.QueryExpandedTERule(scontext=[subType])
+        typePermissionSet = set([":".join([rule.tctx, rule.tclass, perm])
+                                for rule in currentTypeRule for perm in rule.perms
+                                if not rule.tctx in [subType, subType + "_userfaultfd"]])
+        deltaPermissionSet = typePermissionSet.difference(basePermissionSet)
+        violated_permissions = checkPermissions(list(deltaPermissionSet))
+        for perm in violated_permissions:
+            ret += "allow %s %s:%s %s \n" % (subType, *perm.split(":"))
+
+    if ret:
+        ret = ("Found prohibited permission granted for isolated like types. " + \
+            "Please replace your allow statements that involve \"-isolated_app\" with " + \
+            "\"-isolated_app_all\". Violations are shown as the following: \n")  + ret
+    return ret
 
 ###
 # extend OptionParser to allow the same option flag to be used multiple times.
@@ -147,6 +295,9 @@
     "TestPropertyTypeViolations",
     "TestAppDataTypeViolations",
     "TestDmaHeapDevTypeViolations",
+    "TestCoredomainViolations",
+    "TestViolatorAttributes",
+    "TestIsolatedAttributeConsistency",
 ]
 
 def do_main(libpath):
@@ -179,6 +330,8 @@
                     parser.usage)
 
     pol = policy.Policy(options.policy, options.file_contexts, libpath)
+    test_policy = policy.TestPolicy()
+    test_policy.setup(pol)
 
     results = ""
     # If an individual test is not specified, run all tests.
@@ -206,6 +359,12 @@
         results += TestAppDataTypeViolations(pol)
     if options.test is None or "TestDmaHeapDevTypeViolations" in options.test:
         results += TestDmaHeapDevTypeViolations(pol)
+    if options.test is None or "TestCoredomainViolations" in options.test:
+        results += TestCoredomainViolations(test_policy)
+    if options.test is None or "TestViolatorAttributes" in options.test:
+        results += TestViolatorAttributes(test_policy)
+    if options.test is None or "TestIsolatedAttributeConsistency" in options.test:
+        results += TestIsolatedAttributeConsistency(test_policy)
 
     if len(results) > 0:
         sys.exit(results)