CTS test for Android Security b/296915211

Bug: 296915211
Bug: 304287424
Test: Ran the new testcase on android-11.0.0_r46 with/without patch

Change-Id: Ic9f55b8188f089c8a9df300a8bb7803054192cf5
Merged-In: Ic9f55b8188f089c8a9df300a8bb7803054192cf5
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/CVE_2023_40086.java b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2023_40086.java
new file mode 100644
index 0000000..8d2be6e
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2023_40086.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2023 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.
+ */
+
+package android.security.cts;
+
+import static com.android.sts.common.CommandUtil.runAndCheck;
+
+import static com.google.common.truth.TruthJUnit.assume;
+
+import static org.junit.Assume.assumeNoException;
+
+import android.platform.test.annotations.AsbSecurityTest;
+
+import com.android.sts.common.UserUtils;
+import com.android.sts.common.tradefed.testtype.NonRootSecurityTestCase;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.util.RunUtil;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class CVE_2023_40086 extends NonRootSecurityTestCase {
+
+    @AsbSecurityTest(cveBugId = 296915211)
+    @Test
+    public void testPocCVE_2023_40086() {
+        try {
+            ITestDevice device = getDevice();
+
+            // Install test app in device
+            installPackage("CVE-2023-40086.apk");
+
+            // Create new user and save a screenshot in that user
+            final int currentUserId = device.getCurrentUser();
+            try (AutoCloseable asSecondaryUser =
+                    new UserUtils.SecondaryUser(device)
+                            .name("cve_2023_40086_user")
+                            .doSwitch()
+                            .withUser()) {
+                // Taking screenshot in the secondary user
+                runAndCheck(device, "input keyevent KEYCODE_SYSRQ");
+
+                // Wait for screenshot to get saved in the secondary user
+                boolean screenshotSaved = false;
+                int userId = device.getCurrentUser();
+                long startTime = System.currentTimeMillis();
+                do {
+                    screenshotSaved =
+                            runAndCheck(
+                                            device,
+                                            "content query --user "
+                                                    + userId
+                                                    + " --projection _id --uri"
+                                                    + " content://media/external/images/media/")
+                                    .getStdout()
+                                    .contains("Row");
+                    if (screenshotSaved) {
+                        break;
+                    }
+                    RunUtil.getDefault().sleep(100L /* waitPerIteration */);
+                } while ((System.currentTimeMillis() - startTime) <= 5_000L /* timeout  */);
+                assume().withMessage("Screenshot was not saved in the created userId = " + userId)
+                        .that(screenshotSaved)
+                        .isTrue();
+
+                // Switch back to primary user
+                assume().withMessage("Unable to switch back to original user")
+                        .that(device.switchUser(currentUserId))
+                        .isTrue();
+
+                // Run DeviceTest
+                final String testPkg = "android.security.cts.CVE_2023_40086";
+                runDeviceTests(testPkg, testPkg + ".DeviceTest", "testPocCVE_2023_40086");
+            }
+        } catch (Exception e) {
+            assumeNoException(e);
+        }
+    }
+}
diff --git a/hostsidetests/securitybulletin/test-apps/CVE-2023-40086/Android.bp b/hostsidetests/securitybulletin/test-apps/CVE-2023-40086/Android.bp
new file mode 100644
index 0000000..fcec20c
--- /dev/null
+++ b/hostsidetests/securitybulletin/test-apps/CVE-2023-40086/Android.bp
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2023 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.
+ *
+ */
+
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test_helper_app {
+    name: "CVE-2023-40086",
+    defaults: [
+        "cts_defaults",
+    ],
+    srcs: [
+        "src/**/*.java",
+    ],
+    test_suites: [
+        "sts",
+    ],
+    static_libs: [
+        "androidx.test.core",
+        "androidx.test.rules",
+        "compatibility-device-util-axt",
+        "sts-device-util",
+        "truth-prebuilt",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/test-apps/CVE-2023-40086/AndroidManifest.xml b/hostsidetests/securitybulletin/test-apps/CVE-2023-40086/AndroidManifest.xml
new file mode 100644
index 0000000..4152eee
--- /dev/null
+++ b/hostsidetests/securitybulletin/test-apps/CVE-2023-40086/AndroidManifest.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  Copyright 2023 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.security.cts.CVE_2023_40086">
+
+    <application>
+        <service
+            android:name=".TestConnectionService"
+            android:exported="true"
+            android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE">
+            <intent-filter>
+                <action android:name="android.telecom.ConnectionService" />
+            </intent-filter>
+        </service>
+   </application>
+
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+        android:targetPackage="android.security.cts.CVE_2023_40086" />
+</manifest>
diff --git a/hostsidetests/securitybulletin/test-apps/CVE-2023-40086/src/android/security/cts/CVE_2023_40086/DeviceTest.java b/hostsidetests/securitybulletin/test-apps/CVE-2023-40086/src/android/security/cts/CVE_2023_40086/DeviceTest.java
new file mode 100644
index 0000000..b9b585c
--- /dev/null
+++ b/hostsidetests/securitybulletin/test-apps/CVE-2023-40086/src/android/security/cts/CVE_2023_40086/DeviceTest.java
@@ -0,0 +1,170 @@
+/*
+ * Copyright (C) 2023 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.
+ */
+
+package android.security.cts.CVE_2023_40086;
+
+import static android.Manifest.permission.CREATE_USERS;
+import static android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
+
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+
+import static com.android.compatibility.common.util.SystemUtil.runShellCommand;
+import static com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity;
+import static com.android.sts.common.SystemUtil.poll;
+
+import static com.google.common.truth.Truth.assertWithMessage;
+import static com.google.common.truth.TruthJUnit.assume;
+
+import android.app.Instrumentation;
+import android.content.ComponentName;
+import android.content.ContentProvider;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ResolveInfo;
+import android.content.pm.UserInfo;
+import android.graphics.drawable.Icon;
+import android.net.Uri;
+import android.os.UserManager;
+import android.telecom.PhoneAccount;
+import android.telecom.PhoneAccountHandle;
+import android.telecom.TelecomManager;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+@RunWith(AndroidJUnit4.class)
+public class DeviceTest {
+    private Context mContext;
+
+    @Test
+    public void testPocCVE_2023_40086() {
+        try {
+            Instrumentation instrumentation = getInstrumentation();
+            mContext = instrumentation.getContext();
+            final UserManager userManager = mContext.getSystemService(UserManager.class);
+
+            // Check if the device supports multiple users or not
+            assume().withMessage("This device does not support multiple users")
+                    .that(userManager.supportsMultipleUsers())
+                    .isTrue();
+
+            // Get the user id of 'cve_2023_40086_user'
+            final int testUserId =
+                    runWithShellPermissionIdentity(
+                            () -> {
+                                List<UserInfo> list = userManager.getUsers();
+                                for (UserInfo info : list) {
+                                    if (info.toString().contains("cve_2023_40086_user")) {
+                                        return info.getUserHandle().getIdentifier();
+                                    }
+                                }
+                                return -1;
+                            },
+                            CREATE_USERS);
+            assume().withMessage("Unable to get userId of secondary user")
+                    .that(testUserId)
+                    .isNotEqualTo(-1);
+
+            // PhoneAccount object is created using a phoneAccountHandle to registerPhoneAccount
+            // with TelecomManager, which further leads to reproducing vulnerability.
+            PhoneAccountHandle phoneAccountHandle =
+                    new PhoneAccountHandle(
+                            new ComponentName(mContext, TestConnectionService.class),
+                            "cve_2023_40086_id" /* id */);
+            PhoneAccount phoneAccount =
+                    PhoneAccount.builder(phoneAccountHandle, "cve_2023_40086_label" /* label */)
+                            .setIcon(
+                                    Icon.createWithContentUri(
+                                            ContentProvider.maybeAddUserId(
+                                                    EXTERNAL_CONTENT_URI, testUserId)))
+                            .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
+                            .build();
+
+            try {
+                // Without fix, the PhoneAccount object gets registered successfully with the
+                // invalid uri for icon.
+                mContext.getSystemService(TelecomManager.class).registerPhoneAccount(phoneAccount);
+            } catch (IllegalArgumentException exception) {
+                // With fix, IllegalArgumentException is raised when the userId in the uri does not
+                // match the current userId.
+                if (exception.getMessage().contains("icon belonging to another user")) {
+                    return;
+                } else {
+                    throw exception;
+                }
+            }
+
+            // Launch activity to reproduce the vulnerability
+            final ComponentName componentName =
+                    ComponentName.createRelative(
+                            queryTelecomPkgName(), ".settings.EnableAccountPreferenceActivity");
+            mContext.startActivity(
+                    new Intent()
+                            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+                            .setComponent(componentName));
+
+            // Without fix 'EnableAccountPreferenceActivity' launches and test fails
+            assertWithMessage(
+                            "Device is vulnerable to b/296915211 !! Images can be revealed across"
+                                    + " users via TelecomManager#registerPhoneAccount")
+                    .that(checkActivityLaunched(componentName.flattenToString()))
+                    .isFalse();
+        } catch (Exception e) {
+            assume().that(e).isNull();
+        } finally {
+            try {
+                // Exit the test gracefully
+                runShellCommand("input keyevent KEYCODE_HOME");
+            } catch (Exception ignore) {
+                // Ignore
+            }
+        }
+    }
+
+    private String queryTelecomPkgName() {
+        String telecomPkgName = "com.android.server.telecom";
+        ResolveInfo resolveInfo =
+                mContext.getPackageManager()
+                        .resolveActivity(
+                                new Intent(Intent.ACTION_CALL).setData(Uri.parse("tel:123")),
+                                0 /* flags */);
+        if (resolveInfo != null && resolveInfo.activityInfo != null) {
+            telecomPkgName = resolveInfo.activityInfo.packageName;
+        }
+        return telecomPkgName;
+    }
+
+    private boolean checkActivityLaunched(String activityName) throws Exception {
+        final Pattern resumedPattern =
+                Pattern.compile("mResumed=(?<value>(true|false))", Pattern.CASE_INSENSITIVE);
+        return poll(
+                () -> {
+                    String dumpsys =
+                            runShellCommand(String.format("dumpsys activity " + activityName));
+                    Matcher matcher = resumedPattern.matcher(dumpsys);
+                    if (matcher.find() && matcher.group("value").equals("true")) {
+                        return true;
+                    }
+                    return false;
+                });
+    }
+}
diff --git a/hostsidetests/securitybulletin/test-apps/CVE-2023-40086/src/android/security/cts/CVE_2023_40086/TestConnectionService.java b/hostsidetests/securitybulletin/test-apps/CVE-2023-40086/src/android/security/cts/CVE_2023_40086/TestConnectionService.java
new file mode 100644
index 0000000..0102f63
--- /dev/null
+++ b/hostsidetests/securitybulletin/test-apps/CVE-2023-40086/src/android/security/cts/CVE_2023_40086/TestConnectionService.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright (C) 2023 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.
+ */
+
+package android.security.cts.CVE_2023_40086;
+
+import android.telecom.ConnectionService;
+
+public class TestConnectionService extends ConnectionService {}