Updated CTS test for Android Security b/174047492

Bug: 174047492
Bug: 185153206
Test: Ran the new testcase on android-10.0.0_r39 to test with/without patch

Change-Id: I2c7b345234a86cffcf0169a44b5a47a323f28549
Merged-In: I2c7b345234a86cffcf0169a44b5a47a323f28549
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/CVE_2021_0523.java b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2021_0523.java
index db0a1b2..77c9188 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/CVE_2021_0523.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2021_0523.java
@@ -1,4 +1,4 @@
-/**
+/*
  * Copyright (C) 2021 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,85 +16,42 @@
 
 package android.security.cts;
 
+import android.platform.test.annotations.AppModeFull;
 import android.platform.test.annotations.AsbSecurityTest;
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
-import java.util.regex.Pattern;
-import java.util.regex.Matcher;
-import org.junit.Test;
+import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
+import org.junit.Assert;
+import org.junit.Before;
 import org.junit.runner.RunWith;
-
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertThat;
+import org.junit.Test;
 
 @RunWith(DeviceJUnit4ClassRunner.class)
-public class CVE_2021_0523 extends SecurityTestCase {
+public class CVE_2021_0523 extends BaseHostJUnit4Test {
+    private static final String TEST_PKG = "android.security.cts.cve_2021_0523";
+    private static final String TEST_CLASS = TEST_PKG + "." + "DeviceTest";
+    private static final String TEST_APP = "CVE-2021-0523.apk";
 
-    private static void extractInt(String str, int[] displaySize) {
-        str = ((str.replaceAll("[^\\d]", " ")).trim()).replaceAll(" +", " ");
-        if (str.equals("")) {
-            return;
-        }
-        String s[] = str.split(" ");
-        for (int i = 0; i < s.length; ++i) {
-            displaySize[i] = Integer.parseInt(s[i]);
-        }
+    @Before
+    public void setUp() throws Exception {
+        ITestDevice device = getDevice();
+        uninstallPackage(device, TEST_PKG);
+        /* Wake up the screen */
+        AdbUtils.runCommandLine("input keyevent KEYCODE_WAKEUP", device);
+        AdbUtils.runCommandLine("input keyevent KEYCODE_MENU", device);
+        AdbUtils.runCommandLine("input keyevent KEYCODE_HOME", device);
     }
 
     /**
      * b/174047492
      */
-    @Test
+    @AppModeFull
     @AsbSecurityTest(cveBugId = 174047492)
+    @Test
     public void testPocCVE_2021_0523() throws Exception {
-        final int SLEEP_INTERVAL_MILLISEC = 30 * 1000;
-        String apkName = "CVE-2021-0523.apk";
-        String appPath = AdbUtils.TMP_PATH + apkName;
-        String packageName = "android.security.cts.cve_2021_0523";
-        String crashPattern =
-            "Device is vulnerable to b/174047492 hence any app with " +
-            "SYSTEM_ALERT_WINDOW can overlay the WifiScanModeActivity screen";
-        ITestDevice device = getDevice();
-
-        try {
-            /* Push the app to /data/local/tmp */
-            pocPusher.appendBitness(false);
-            pocPusher.pushFile(apkName, appPath);
-
-            /* Wake up the screen */
-            AdbUtils.runCommandLine("input keyevent KEYCODE_WAKEUP", device);
-            AdbUtils.runCommandLine("input keyevent KEYCODE_MENU", device);
-            AdbUtils.runCommandLine("input keyevent KEYCODE_HOME", device);
-
-            /* Install the application */
-            AdbUtils.runCommandLine("pm install " + appPath, device);
-
-            /* Grant "Draw over other apps" permission */
-            AdbUtils.runCommandLine(
-                    "pm grant " + packageName + " android.permission.SYSTEM_ALERT_WINDOW", device);
-
-            /* Start the application */
-            AdbUtils.runCommandLine("am start -n " + packageName + "/.PocActivity", getDevice());
-            Thread.sleep(SLEEP_INTERVAL_MILLISEC);
-
-            /* Get screen width and height */
-            int[] displaySize = new int[2];
-            extractInt(AdbUtils.runCommandLine("wm size", device), displaySize);
-            int width = displaySize[0];
-            int height = displaySize[1];
-
-            /* Give a tap command for center of screen */
-            AdbUtils.runCommandLine("input tap " + width / 2 + " " + height / 2, device);
-        } catch (Exception e) {
-            e.printStackTrace();
-        } finally {
-            /* Un-install the app after the test */
-            AdbUtils.runCommandLine("pm uninstall " + packageName, device);
-
-            /* Detection of crash pattern in the logs */
-            String logcat = AdbUtils.runCommandLine("logcat -d *:S AndroidRuntime:E", device);
-            Pattern pattern = Pattern.compile(crashPattern, Pattern.MULTILINE);
-            assertThat(crashPattern, pattern.matcher(logcat).find(), is(false));
-        }
+        installPackage(TEST_APP);
+        AdbUtils.runCommandLine("pm grant " + TEST_PKG + " android.permission.SYSTEM_ALERT_WINDOW",
+                getDevice());
+        Assert.assertTrue(runDeviceTests(TEST_PKG, TEST_CLASS, "testOverlayButtonPresence"));
     }
 }
diff --git a/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/Android.bp b/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/Android.bp
index 8d8b8cb..899f4be 100644
--- a/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/Android.bp
+++ b/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/Android.bp
@@ -17,18 +17,17 @@
 
 android_test_helper_app {
     name: "CVE-2021-0523",
-    srcs: [
-        "src/android/security/cts/CVE_2021_0523/PocActivity.java",
-        "src/android/security/cts/CVE_2021_0523/PocService.java",
-    ],
+    defaults: ["cts_support_defaults"],
+    srcs: ["src/**/*.java"],
     test_suites: [
         "cts",
         "vts10",
         "sts",
-        "general-tests",
     ],
-    sdk_version: "system_current",
     static_libs: [
-        "androidx.test.ext.junit",
+        "androidx.test.rules",
+        "androidx.test.uiautomator_uiautomator",
+        "androidx.test.core",
     ],
+    sdk_version: "current",
 }
diff --git a/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/AndroidManifest.xml b/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/AndroidManifest.xml
index 594e427..3425504 100644
--- a/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/AndroidManifest.xml
+++ b/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/AndroidManifest.xml
@@ -20,24 +20,29 @@
     android:versionName="1.0">
 
     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
-    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
-    <uses-permission android:name="android.permission.WAKE_LOCK" />
+    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
     <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
 
     <application
         android:allowBackup="true"
         android:label="CVE-2021-0523"
         android:supportsRtl="true">
+        <uses-library android:name="android.test.runner" />
         <service
             android:name=".PocService"
             android:enabled="true"
             android:exported="false" />
 
-        <activity android:name=".PocActivity">
+        <activity android:name=".PocActivity"
+            android:taskAffinity="android.security.cts.cve_2021_0523.PocActivity">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
     </application>
+
+   <instrumentation
+        android:name="androidx.test.runner.AndroidJUnitRunner"
+        android:targetPackage="android.security.cts.cve_2021_0523" />
 </manifest>
diff --git a/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/res/values/strings.xml b/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/res/values/strings.xml
new file mode 100644
index 0000000..dcdbe0a
--- /dev/null
+++ b/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/res/values/strings.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  Copyright 2021 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.
+  -->
+<resources>
+    <string name="overlay_button">OverlayButton</string>
+</resources>
diff --git a/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/src/android/security/cts/CVE_2021_0523/DeviceTest.java b/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/src/android/security/cts/CVE_2021_0523/DeviceTest.java
new file mode 100644
index 0000000..e0fc337
--- /dev/null
+++ b/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/src/android/security/cts/CVE_2021_0523/DeviceTest.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2021 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_2021_0523;
+
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.provider.Settings;
+import androidx.test.runner.AndroidJUnit4;
+import androidx.test.uiautomator.By;
+import androidx.test.uiautomator.BySelector;
+import androidx.test.uiautomator.UiDevice;
+import androidx.test.uiautomator.Until;
+import java.io.IOException;
+import java.util.regex.Pattern;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.junit.Test;
+
+import static androidx.test.core.app.ApplicationProvider.getApplicationContext;
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+@RunWith(AndroidJUnit4.class)
+public class DeviceTest {
+    private static final String TEST_PKG = "android.security.cts.cve_2021_0523";
+    private static final String TEST_PKG_WIFI = "com.android.settings";
+    private static final int LAUNCH_TIMEOUT_MS = 20000;
+    private UiDevice mDevice;
+    String activityDump = "";
+
+    private void startOverlayService() {
+        Context context = getApplicationContext();
+        if (Settings.canDrawOverlays(getApplicationContext())) {
+            Intent intent = new Intent(getApplicationContext(), PocService.class);
+            context.startService(intent);
+        } else {
+            try {
+                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
+                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+                context.startActivity(intent);
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
+    @Before
+    public void startMainActivityFromHomeScreen() {
+        mDevice = UiDevice.getInstance(getInstrumentation());
+        Context context = getApplicationContext();
+        assertNotNull(context);
+        PackageManager packageManager = context.getPackageManager();
+        assertNotNull(packageManager);
+        final Intent intent = packageManager.getLaunchIntentForPackage(TEST_PKG);
+        assertNotNull(intent);
+        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
+        /* Start the launcher activity */
+        context.startActivity(intent);
+        /* Wait for the WifiScanModeActivity */
+        if (!mDevice.wait(Until.hasObject(By.pkg(TEST_PKG_WIFI).depth(0)), LAUNCH_TIMEOUT_MS)) {
+            return;
+        }
+        /* Start the overlay service */
+        startOverlayService();
+    }
+
+    @Test
+    public void testOverlayButtonPresence() {
+        Pattern pattern = Pattern.compile(
+                getApplicationContext().getResources().getString(R.string.overlay_button),
+                Pattern.CASE_INSENSITIVE);
+        BySelector selector = By.text(pattern);
+        /* Wait for an object of the overlay window */
+        if (!mDevice.wait(Until.hasObject(selector.depth(0)), LAUNCH_TIMEOUT_MS)) {
+            return;
+        }
+        /* Check if the currently running activity is WifiScanModeActivity */
+        try {
+            activityDump = mDevice.executeShellCommand("dumpsys activity");
+        } catch (IOException e) {
+            throw new RuntimeException("Could not execute dumpsys activity command");
+        }
+        Pattern activityPattern = Pattern.compile("mResumedActivity.*WifiScanModeActivity.*\n");
+        if (!activityPattern.matcher(activityDump).find()) {
+            return;
+        }
+        String message = "Device is vulnerable to b/174047492 hence any app with "
+                + "SYSTEM_ALERT_WINDOW can overlay the WifiScanModeActivity screen";
+        assertNull(message, mDevice.findObject(selector));
+    }
+}
diff --git a/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/src/android/security/cts/CVE_2021_0523/PocActivity.java b/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/src/android/security/cts/CVE_2021_0523/PocActivity.java
index 0ba69f5..a28b337 100644
--- a/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/src/android/security/cts/CVE_2021_0523/PocActivity.java
+++ b/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/src/android/security/cts/CVE_2021_0523/PocActivity.java
@@ -18,60 +18,16 @@
 
 import android.app.Activity;
 import android.content.Intent;
-import android.content.Context;
 import android.net.wifi.WifiManager;
-import android.os.Build;
 import android.os.Bundle;
-import android.os.PowerManager;
-import android.os.PowerManager.WakeLock;
-import android.provider.Settings;
 
 public class PocActivity extends Activity {
-    private WakeLock mScreenLock;
-    private Context mContext;
-
-    private void startOverlayService() {
-        if (Settings.canDrawOverlays(this)) {
-            Intent intent = new Intent(PocActivity.this, PocService.class);
-            startService(intent);
-        } else {
-            try {
-                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
-                startActivityForResult(intent, 1);
-            } catch (Exception e) {
-                e.printStackTrace();
-            }
-        }
-    }
-
-    private void stopOverlayService() {
-        Intent intent = new Intent(PocActivity.this, PocService.class);
-        stopService(intent);
-    }
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
-        mContext = this.getApplicationContext();
-        PowerManager pm = mContext.getSystemService(PowerManager.class);
-        mScreenLock = pm.newWakeLock(
-                PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
-                "PocActivity");
-        mScreenLock.acquire();
-        try {
-            Thread.sleep(6000);
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
-        startOverlayService();
         Intent intent = new Intent(WifiManager.ACTION_REQUEST_SCAN_ALWAYS_AVAILABLE);
-        startActivityForResult(intent, 2);
-    }
-
-    @Override
-    protected void onDestroy() {
-        super.onDestroy();
-        mScreenLock.release();
+        startActivity(intent);
     }
 }
diff --git a/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/src/android/security/cts/CVE_2021_0523/PocService.java b/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/src/android/security/cts/CVE_2021_0523/PocService.java
index bef2beb..9b013b8 100644
--- a/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/src/android/security/cts/CVE_2021_0523/PocService.java
+++ b/hostsidetests/securitybulletin/test-apps/CVE-2021-0523/src/android/security/cts/CVE_2021_0523/PocService.java
@@ -84,9 +84,8 @@
     private void showFloatingWindow() {
         if (Settings.canDrawOverlays(this)) {
             mButton = new Button(getApplicationContext());
-            mButton.setBackgroundColor(Color.parseColor("#BEBEBE")); // R-BE G-BE B-BE
+            mButton.setText(getResources().getString(R.string.overlay_button));
             mWindowManager.addView(mButton, mLayoutParams);
-            mButton.setOnTouchListener(new FloatingOnTouchListener());
             new Handler().postDelayed(new Runnable() {
                 @Override
                 public void run() {
@@ -96,25 +95,4 @@
             mButton.setTag(mButton.getVisibility());
         }
     }
-
-    private static class FloatingOnTouchListener implements View.OnTouchListener {
-
-        @Override
-        public boolean onTouch(View view, MotionEvent event) {
-            view.setDrawingCacheEnabled(true);
-            view.buildDrawingCache();
-            Bitmap bitmap = view.getDrawingCache();
-            int pixel = bitmap.getPixel(getScreenWidth() / 2, getScreenHeight() / 2);
-            int red = Color.red(pixel);
-            int green = Color.green(pixel);
-            int blue = Color.blue(pixel);
-            view.setDrawingCacheEnabled(false);
-            if ((red == 0xBE) && (green == 0xBE) && (blue == 0xBE)) {
-                throw new RuntimeException(
-                    "Device is vulnerable to b/174047492 hence any app with " +
-                    "SYSTEM_ALERT_WINDOW can overlay the WifiScanModeActivity screen");
-            }
-            return false;
-        }
-    }
 }