Add userdebug exceptions for vcd and dmd ports in ListeningPortsTest

The ListeningPortsTest will report a failure if an unexpected system
process (uid < 10000) is listening on a port and can be accessed by
other apps on the device. The dmd and vcd processes are expected
to be listening on the loopback interface to ports 50002 and 60002
on userdebug builds, so this commit adds exceptions to not report
these ports if the device is running a userdebug or eng build.

Fixes: 281490175
Test: atest ListeningPortsTest
Change-Id: I625e310cb34378e0dd97cdb50a3489689c086664
diff --git a/hostsidetests/appsecurity/test-apps/ListeningPortsApp/src/android/appsecurity/cts/listeningports/ListeningPortsTest.java b/hostsidetests/appsecurity/test-apps/ListeningPortsApp/src/android/appsecurity/cts/listeningports/ListeningPortsTest.java
index 072effb..0768ea2 100644
--- a/hostsidetests/appsecurity/test-apps/ListeningPortsApp/src/android/appsecurity/cts/listeningports/ListeningPortsTest.java
+++ b/hostsidetests/appsecurity/test-apps/ListeningPortsApp/src/android/appsecurity/cts/listeningports/ListeningPortsTest.java
@@ -18,6 +18,7 @@
 
 import android.app.UiAutomation;
 import android.content.pm.PackageManager;
+import android.os.Build;
 import android.os.Bundle;
 import android.os.Process;
 import android.os.UserHandle;
@@ -95,6 +96,13 @@
         EXCEPTION_PATTERNS.add("0.0.0.0:68");
     }
 
+    private static final List<String> USERDEBUG_EXCEPTION_PATTERNS = new ArrayList<>(2);
+
+    static {
+        USERDEBUG_EXCEPTION_PATTERNS.add("127.0.0.1:50002");  // Diagnostic Monitor Daemon port
+        USERDEBUG_EXCEPTION_PATTERNS.add("127.0.0.1:60002");  // vcd port
+    }
+
     /**
      * Remotely accessible ports (loopback==false) are often used by
      * attackers to gain unauthorized access to computers systems without
@@ -122,6 +130,7 @@
 
             if (isPortListening(entry.state, isTcp)
                     && !(isException(addrPort) || isException(addrUid) || isException(addrPortUid))
+                    && !(isUserDebugException(addrPort))
                     && (!entry.localAddress.isLoopbackAddress() ^ loopback)) {
                 if (isTcp && !isTcpConnectable(entry.localAddress, entry.port)) {
                     continue;
@@ -190,6 +199,13 @@
         return isPatternMatch(EXCEPTION_PATTERNS, localAddress);
     }
 
+    private static boolean isUserDebugException(String localAddress) {
+        if (!(Build.IS_USERDEBUG || Build.IS_ENG)) {
+            return false;
+        }
+        return isPatternMatch(USERDEBUG_EXCEPTION_PATTERNS, localAddress);
+    }
+
     private static boolean isPatternMatch(List<String> patterns, String input) {
         for (String pattern : patterns) {
             pattern = Pattern.quote(pattern);