CTS test for Android Security b/277740082

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

Change-Id: Id698b1eded1a95a355b4d41dd14fa7f088bfc8da
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/CVE_2023_21286.java b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2023_21286.java
new file mode 100644
index 0000000..31494b2
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2023_21286.java
@@ -0,0 +1,89 @@
+/*
+ * 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 org.junit.Assume.assumeNoException;
+import static org.junit.Assume.assumeTrue;
+
+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.IRunUtil;
+import com.android.tradefed.util.RunUtil;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class CVE_2023_21286 extends NonRootSecurityTestCase {
+
+    @AsbSecurityTest(cveBugId = 277740082)
+    @Test
+    public void testPocCVE_2023_21286() {
+        try {
+            ITestDevice device = getDevice();
+            final String testPkg = "android.security.cts.CVE_2023_21286";
+
+            // Install test app in device
+            installPackage("CVE-2023-21286.apk", "-g");
+
+            // 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_21286_user")
+                            .doSwitch()
+                            .withUser()) {
+                int userId = device.getCurrentUser();
+                device.executeShellCommand("input keyevent KEYCODE_SYSRQ");
+
+                // Wait for screenshot to get saved in the created user
+                final long timeout = 5_000L;
+                final long waitPerIteration = 500L;
+                boolean screenshotSaved = false;
+                IRunUtil runUtil = RunUtil.getDefault();
+                long start = System.currentTimeMillis();
+                do {
+                    screenshotSaved =
+                            device.executeShellCommand(
+                                            "content query --user "
+                                                    + userId
+                                                    + " --projection _id --uri"
+                                                    + " content://media/external/images/media/")
+                                    .contains("Row");
+                    if (screenshotSaved) {
+                        break;
+                    }
+                    runUtil.sleep(waitPerIteration);
+                } while (System.currentTimeMillis() - start <= timeout);
+                assumeTrue(
+                        "Screenshot was not saved in the created userId = " + userId,
+                        screenshotSaved);
+                // Switch back to original user
+                assumeTrue(device.switchUser(currentUserId));
+
+                // Run DeviceTest
+                runDeviceTests(testPkg, testPkg + ".DeviceTest", "testPocCVE_2023_21286");
+            }
+        } catch (Exception e) {
+            assumeNoException(e);
+        }
+    }
+}
diff --git a/hostsidetests/securitybulletin/test-apps/CVE-2023-21286/Android.bp b/hostsidetests/securitybulletin/test-apps/CVE-2023-21286/Android.bp
new file mode 100644
index 0000000..c0e20ea
--- /dev/null
+++ b/hostsidetests/securitybulletin/test-apps/CVE-2023-21286/Android.bp
@@ -0,0 +1,38 @@
+/*
+ * 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-21286",
+    defaults: [
+        "cts_defaults",
+    ],
+    srcs: [
+        "src/**/*.java",
+    ],
+    test_suites: [
+        "sts",
+    ],
+    static_libs: [
+        "androidx.test.core",
+        "androidx.test.rules",
+        "androidx.test.uiautomator_uiautomator",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/test-apps/CVE-2023-21286/AndroidManifest.xml b/hostsidetests/securitybulletin/test-apps/CVE-2023-21286/AndroidManifest.xml
new file mode 100644
index 0000000..ad513e9
--- /dev/null
+++ b/hostsidetests/securitybulletin/test-apps/CVE-2023-21286/AndroidManifest.xml
@@ -0,0 +1,24 @@
+<?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_21286">
+    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
+
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+        android:targetPackage="android.security.cts.CVE_2023_21286" />
+</manifest>
diff --git a/hostsidetests/securitybulletin/test-apps/CVE-2023-21286/res/layout/cve_2023_21286_layout.xml b/hostsidetests/securitybulletin/test-apps/CVE-2023-21286/res/layout/cve_2023_21286_layout.xml
new file mode 100644
index 0000000..abb85d3
--- /dev/null
+++ b/hostsidetests/securitybulletin/test-apps/CVE-2023-21286/res/layout/cve_2023_21286_layout.xml
@@ -0,0 +1,21 @@
+<?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.
+  -->
+
+<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/cve_2023_21286_img"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent" />
diff --git a/hostsidetests/securitybulletin/test-apps/CVE-2023-21286/res/layout/cve_2023_21286_layout_outer.xml b/hostsidetests/securitybulletin/test-apps/CVE-2023-21286/res/layout/cve_2023_21286_layout_outer.xml
new file mode 100644
index 0000000..e3588ce
--- /dev/null
+++ b/hostsidetests/securitybulletin/test-apps/CVE-2023-21286/res/layout/cve_2023_21286_layout_outer.xml
@@ -0,0 +1,21 @@
+<?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.
+  -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/cve_2023_21286_outer"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent" />
diff --git a/hostsidetests/securitybulletin/test-apps/CVE-2023-21286/src/android/security/cts/CVE_2023_21286/DeviceTest.java b/hostsidetests/securitybulletin/test-apps/CVE-2023-21286/src/android/security/cts/CVE_2023_21286/DeviceTest.java
new file mode 100644
index 0000000..55c75be
--- /dev/null
+++ b/hostsidetests/securitybulletin/test-apps/CVE-2023-21286/src/android/security/cts/CVE_2023_21286/DeviceTest.java
@@ -0,0 +1,145 @@
+/*
+ * 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_21286;
+
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+
+import static org.junit.Assert.assertNull;
+import static org.junit.Assume.assumeNoException;
+import static org.junit.Assume.assumeTrue;
+
+import android.app.Instrumentation;
+import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.app.UiAutomation;
+import android.content.Context;
+import android.content.pm.UserInfo;
+import android.graphics.drawable.Icon;
+import android.net.Uri;
+import android.os.UserManager;
+import android.provider.MediaStore;
+import android.widget.RemoteViews;
+
+import androidx.test.runner.AndroidJUnit4;
+import androidx.test.uiautomator.By;
+import androidx.test.uiautomator.UiDevice;
+import androidx.test.uiautomator.UiObject2;
+import androidx.test.uiautomator.Until;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.List;
+
+@RunWith(AndroidJUnit4.class)
+public class DeviceTest {
+
+    private AutoCloseable withAdoptShellPermissionIdentity(
+            UiAutomation uiAutomation, String permission) {
+        uiAutomation.adoptShellPermissionIdentity(permission);
+
+        // Remove permissions
+        return () -> uiAutomation.dropShellPermissionIdentity();
+    }
+
+    @Test
+    public void testPocCVE_2023_21286() {
+        UiDevice uiDevice = null;
+        try {
+            final String cveId = "cve_2023_21286_";
+            final String title = cveId + "title";
+
+            Instrumentation instrumentation = getInstrumentation();
+            Context context = instrumentation.getContext();
+            UiAutomation uiAutomation = instrumentation.getUiAutomation();
+            uiDevice = UiDevice.getInstance(instrumentation);
+            int userId = -1;
+
+            // Retrieve created user Id
+            try (AutoCloseable withAdoptShellPermissionIdentity =
+                    withAdoptShellPermissionIdentity(
+                            uiAutomation, android.Manifest.permission.CREATE_USERS)) {
+                final List<UserInfo> list = context.getSystemService(UserManager.class).getUsers();
+                for (UserInfo info : list) {
+                    if (info.name.contains(cveId)) {
+                        userId = info.id;
+                        break;
+                    }
+                }
+            }
+            assumeTrue(userId != -1);
+
+            // Post a notification with a content view containing image from other user
+            RemoteViews rvPortrait =
+                    new RemoteViews(context.getPackageName(), R.layout.cve_2023_21286_layout);
+            rvPortrait.setImageViewUri(
+                    R.id.cve_2023_21286_img,
+                    Uri.parse("content://" + userId + "@media/external/images/media/"));
+            NotificationChannel notificationChannel =
+                    new NotificationChannel(cveId, cveId, NotificationManager.IMPORTANCE_DEFAULT);
+            RemoteViews rvOuter =
+                    new RemoteViews(context.getPackageName(), R.layout.cve_2023_21286_layout_outer);
+            rvOuter.addView(R.id.cve_2023_21286_outer, rvPortrait);
+            NotificationManager notificationManager =
+                    context.getSystemService(NotificationManager.class);
+            notificationManager.createNotificationChannel(notificationChannel);
+            Notification notification =
+                    new Notification.Builder(context, cveId)
+                            .setContentTitle(title)
+                            .setSmallIcon(
+                                    Icon.createWithData(
+                                            new byte[0] /* data */, 0 /* offset */, 0 /* length */))
+                            .setCustomContentView(rvOuter)
+                            .setCustomBigContentView(rvOuter)
+                            .build();
+            try {
+                notificationManager.notify(0 /* id */, notification);
+            } catch (SecurityException securityException) {
+                if (securityException
+                        .getLocalizedMessage()
+                        .toLowerCase()
+                        .contains(MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString())) {
+                    // Ignore exception thrown with fix and exit the test
+                    return;
+                } else {
+                    throw securityException;
+                }
+            }
+
+            // Open notification shade
+            assumeTrue("Opening notification shade unsuccessful", uiDevice.openNotification());
+
+            // Wait for notification to appear and detect if the remote view is present
+            uiDevice.wait(Until.hasObject(By.text(title)), 3000 /* timeout */);
+            UiObject2 exposedImg =
+                    uiDevice.findObject(By.res(context.getPackageName(), cveId + "img"));
+            assertNull(
+                    "Device is vulnerable to b/277740082, Other user's images can be exposed in"
+                            + " notifications using remote views",
+                    exposedImg);
+        } catch (Exception e) {
+            assumeNoException(e);
+        } finally {
+            try {
+                uiDevice.pressHome();
+            } catch (Exception e) {
+                // Ignore exceptions as the test has finished
+            }
+        }
+    }
+}