Validate EXTRA_INSTALLER_PACKAGE_NAME

When installing an app via ACTION_INSTALL_PACKAGE, the caller could
use this extra field to specify the installer package name. As using
PackageInstaller APIs, we should limit setting the installer package
name that is not the caller only when apps with INSTALL_PACKAGES
permission. Also applying the max package name length restriction.

Bug: 236687884
Test: atest CtsPackageInstallTestCases
Test: manually using the PoC in the buganizer to ensure the symptom
      no longer exists.
Change-Id: I74eb4ea2e2733321b5fbf328a9835a3ca7d0dfa9
diff --git a/packages/PackageInstaller/src/com/android/packageinstaller/InstallStart.java b/packages/PackageInstaller/src/com/android/packageinstaller/InstallStart.java
index bfab9be..e4bdab8 100644
--- a/packages/PackageInstaller/src/com/android/packageinstaller/InstallStart.java
+++ b/packages/PackageInstaller/src/com/android/packageinstaller/InstallStart.java
@@ -28,6 +28,7 @@
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageInstaller;
+import android.content.pm.PackageInstaller.SessionParams;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
 import android.content.pm.ProviderInfo;
@@ -35,6 +36,8 @@
 import android.os.Build;
 import android.os.Bundle;
 import android.os.RemoteException;
+import android.text.TextUtils;
+import android.util.EventLog;
 import android.util.Log;
 
 import java.util.Arrays;
@@ -96,6 +99,23 @@
                 mAbortInstall = true;
             }
         }
+
+        final String installerPackageNameFromIntent = getIntent().getStringExtra(
+                Intent.EXTRA_INSTALLER_PACKAGE_NAME);
+        if (installerPackageNameFromIntent != null) {
+            final String callingPkgName = getLaunchedFromPackage();
+            if (installerPackageNameFromIntent.length() >= SessionParams.MAX_PACKAGE_NAME_LENGTH
+                    || (!TextUtils.equals(installerPackageNameFromIntent, callingPkgName)
+                    && mPackageManager.checkPermission(Manifest.permission.INSTALL_PACKAGES,
+                    callingPkgName) != PackageManager.PERMISSION_GRANTED)) {
+                Log.e(LOG_TAG, "The given installer package name " + installerPackageNameFromIntent
+                        + " is invalid. Remove it.");
+                EventLog.writeEvent(0x534e4554, "236687884", getLaunchedFromUid(),
+                        "Invalid EXTRA_INSTALLER_PACKAGE_NAME");
+                getIntent().removeExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME);
+            }
+        }
+
         if (mAbortInstall) {
             setResult(RESULT_CANCELED);
             finish();