Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 39087e18 authored by Pavel Grafov's avatar Pavel Grafov Committed by Android (Google) Code Review
Browse files

Merge "Migrate sec log to policy engine" into main

parents e48ea8e7 479c5911
Loading
Loading
Loading
Loading
+1 −0
Original line number Diff line number Diff line
@@ -7958,6 +7958,7 @@ package android.app.admin {
    field public static final String PERMISSION_GRANT_POLICY = "permissionGrant";
    field public static final String PERSISTENT_PREFERRED_ACTIVITY_POLICY = "persistentPreferredActivity";
    field public static final String RESET_PASSWORD_TOKEN_POLICY = "resetPasswordToken";
    field @FlaggedApi("android.app.admin.flags.security_log_v2_enabled") public static final String SECURITY_LOGGING_POLICY = "securityLogging";
    field public static final String STATUS_BAR_DISABLED_POLICY = "statusBarDisabled";
    field @FlaggedApi("android.app.admin.flags.policy_engine_migration_v2_enabled") public static final String USB_DATA_SIGNALING_POLICY = "usbDataSignaling";
    field public static final String USER_CONTROL_DISABLED_PACKAGES_POLICY = "userControlDisabledPackages";
+8 −0
Original line number Diff line number Diff line
@@ -16,6 +16,8 @@

package android.app.admin;

import static android.app.admin.flags.Flags.FLAG_SECURITY_LOG_V2_ENABLED;

import android.annotation.FlaggedApi;
import android.annotation.NonNull;
import android.annotation.TestApi;
@@ -44,6 +46,12 @@ public final class DevicePolicyIdentifiers {
     */
    public static final String PERMISSION_GRANT_POLICY = "permissionGrant";

    /**
     * String identifier for {@link DevicePolicyManager#setSecurityLoggingEnabled}.
     */
    @FlaggedApi(FLAG_SECURITY_LOG_V2_ENABLED)
    public static final String SECURITY_LOGGING_POLICY = "securityLogging";

    /**
     * String identifier for {@link DevicePolicyManager#setLockTaskPackages}.
     */
+18 −0
Original line number Diff line number Diff line
@@ -13976,6 +13976,24 @@ public class DevicePolicyManager {
     * privacy-sensitive events happening outside the managed profile would have been redacted
     * already.
     *
     * Starting from {@link Build.VERSION_CODES#VANILLA_ICE_CREAM}, after the security logging
     * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
     * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
     * successfully set or not. This callback will contain:
     * <ul>
     * <li> The policy identifier {@link DevicePolicyIdentifiers#SECURITY_LOGGING_POLICY}
     * <li> The {@link TargetUser} that this policy relates to
     * <li> The {@link PolicyUpdateResult}, which will be
     * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
     * reason the policy failed to be set
     * e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
     * </ul>
     * If there has been a change to the policy,
     * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
     * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
     * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
     * will contain the reason why the policy changed.
     *
     * @param admin Which device admin this request is associated with, or {@code null}
     *              if called by a delegated app.
     * @param enabled whether security logging should be enabled or not.
+5 −0
Original line number Diff line number Diff line
@@ -333,4 +333,9 @@ public abstract class DevicePolicyManagerInternal {
     */
    public abstract List<EnforcingUser> getUserRestrictionSources(String restriction,
                @UserIdInt int userId);

    /**
     * Enforces resolved security logging policy, should only be invoked from device policy engine.
     */
    public abstract void enforceSecurityLoggingPolicy(boolean enabled);
}
+159 −49
Original line number Diff line number Diff line
@@ -237,6 +237,7 @@ import static android.app.admin.flags.Flags.dumpsysPolicyEngineMigrationEnabled;
import static android.app.admin.flags.Flags.headlessDeviceOwnerSingleUserEnabled;
import static android.app.admin.flags.Flags.policyEngineMigrationV2Enabled;
import static android.app.admin.flags.Flags.assistContentUserRestrictionEnabled;
import static android.app.admin.flags.Flags.securityLogV2Enabled;
import static android.content.Intent.ACTION_MANAGED_PROFILE_AVAILABLE;
import static android.content.Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
@@ -3376,9 +3377,10 @@ public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
                    applyProfileRestrictionsIfDeviceOwnerLocked();
                    // TODO: Is this the right place to trigger the migration?
                    if (shouldMigrateToDevicePolicyEngine()) {
                        migratePoliciesToDevicePolicyEngine();
                    if (shouldMigrateV1ToDevicePolicyEngine()) {
                        migrateV1PoliciesToDevicePolicyEngine();
                    }
                    migratePoliciesToPolicyEngineLocked();
                }
                maybeStartSecurityLogMonitorOnActivityManagerReady();
                break;
@@ -3392,6 +3394,48 @@ public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
        }
    }
    @GuardedBy("getLockObject()")
    private void maybeMigrateSecurityLoggingPolicyLocked() {
        if (!securityLogV2Enabled() || mOwners.isSecurityLoggingMigrated()) {
            return;
        }
        try {
            migrateSecurityLoggingPolicyInternalLocked();
        } catch (Exception e) {
            Slog.e(LOG_TAG, "Failed to properly migrate security logging to policy engine", e);
        }
        Slog.i(LOG_TAG, "Marking security logging policy migration complete");
        mOwners.markSecurityLoggingMigrated();
    }
    @GuardedBy("getLockObject()")
    private void migrateSecurityLoggingPolicyInternalLocked() {
        Slog.i(LOG_TAG, "Migrating security logging policy to policy engine");
        if (!mInjector.securityLogGetLoggingEnabledProperty()) {
            Slog.i(LOG_TAG, "Security logs not enabled, exiting");
            return;
        }
        // Security logging can be enabled either by DO or by COPE PO.
        final ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
        if (admin == null) {
            Slog.wtf(LOG_TAG, "Security logging is enabled, but no appropriate admin found");
            return;
        }
        EnforcingAdmin enforcingAdmin =
                EnforcingAdmin.createEnterpriseEnforcingAdmin(
                        admin.info.getComponent(),
                        admin.getUserHandle().getIdentifier(),
                        admin);
        mDevicePolicyEngine.setGlobalPolicy(
                PolicyDefinition.SECURITY_LOGGING,
                enforcingAdmin,
                new BooleanPolicyValue(true));
    }
    private void applyManagedSubscriptionsPolicyIfRequired() {
        int copeProfileUserId = getOrganizationOwnedProfileUserId();
        // This policy is relevant only for COPE devices.
@@ -15721,6 +15765,11 @@ public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
            return enforcingUsers;
        }
        @Override
        public void enforceSecurityLoggingPolicy(boolean enabled) {
            enforceLoggingPolicy(enabled);
        }
        private List<EnforcingUser> getEnforcingUsers(Set<EnforcingAdmin> admins) {
            List<EnforcingUser> enforcingUsers = new ArrayList();
            ComponentName deviceOwner = mOwners.getDeviceOwnerComponent();
@@ -15738,6 +15787,20 @@ public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
        }
    }
    private void enforceLoggingPolicy(boolean securityLoggingEnabled) {
        Slogf.i(LOG_TAG, "Enforcing security logging, securityLoggingEnabled: %b",
                securityLoggingEnabled);
        SecurityLog.setLoggingEnabledProperty(securityLoggingEnabled);
        if (securityLoggingEnabled) {
            mSecurityLogMonitor.start(getSecurityLoggingEnabledUser());
            synchronized (getLockObject()) {
                maybePauseDeviceWideLoggingLocked();
            }
        } else {
            mSecurityLogMonitor.stop();
        }
    }
    private Intent createShowAdminSupportIntent(int userId) {
        // This method is called with AMS lock held, so don't take DPMS lock
        final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
@@ -17586,19 +17649,32 @@ public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
    }
    @Override
    public void setSecurityLoggingEnabled(ComponentName admin, String packageName,
    public void setSecurityLoggingEnabled(ComponentName who, String packageName,
            boolean enabled) {
        if (!mHasFeature) {
            return;
        }
        final CallerIdentity caller = getCallerIdentity(admin, packageName);
        final CallerIdentity caller = getCallerIdentity(who, packageName);
        synchronized (getLockObject()) {
            if (isPermissionCheckFlagEnabled()) {
                enforcePermission(MANAGE_DEVICE_POLICY_SECURITY_LOGGING, caller.getPackageName(),
                        UserHandle.USER_ALL);
        if (securityLogV2Enabled()) {
            EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
                    who,
                    MANAGE_DEVICE_POLICY_SECURITY_LOGGING,
                    caller.getPackageName(),
                    caller.getUserId());
            if (enabled) {
                mDevicePolicyEngine.setGlobalPolicy(
                        PolicyDefinition.SECURITY_LOGGING,
                        admin,
                        new BooleanPolicyValue(true));
            } else {
                if (admin != null) {
                mDevicePolicyEngine.removeGlobalPolicy(
                        PolicyDefinition.SECURITY_LOGGING,
                        admin);
            }
        } else {
            synchronized (getLockObject()) {
                if (who != null) {
                    Preconditions.checkCallAuthorization(
                            isProfileOwnerOfOrganizationOwnedDevice(caller)
                                    || isDefaultDeviceOwner(caller));
@@ -17607,7 +17683,6 @@ public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
                    Preconditions.checkCallAuthorization(
                            isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING));
                }
            }
                if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
                    return;
@@ -17620,6 +17695,7 @@ public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
                    mSecurityLogMonitor.stop();
                }
            }
        }
        DevicePolicyEventLogger
                .createEvent(DevicePolicyEnums.SET_SECURITY_LOGGING_ENABLED)
                .setAdmin(caller.getPackageName())
@@ -17633,13 +17709,24 @@ public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
            return false;
        }
        synchronized (getLockObject()) {
            if (!isSystemUid(getCallerIdentity())) {
        final CallerIdentity caller = getCallerIdentity(admin, packageName);
                if (isPermissionCheckFlagEnabled()) {
                    enforcePermission(MANAGE_DEVICE_POLICY_SECURITY_LOGGING,
                            caller.getPackageName(), UserHandle.USER_ALL);
        if (isSystemUid(caller)) {
            // Settings uses this for privacy transparency.
            // TODO: create a separate @hidden API for settings.
            return mInjector.securityLogGetLoggingEnabledProperty();
        }
        if (securityLogV2Enabled()) {
            final EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    admin,
                    MANAGE_DEVICE_POLICY_SECURITY_LOGGING,
                    caller.getPackageName(),
                    caller.getUserId());
            final Boolean policy = mDevicePolicyEngine.getGlobalPolicySetByAdmin(
                    PolicyDefinition.SECURITY_LOGGING, enforcingAdmin);
            return Boolean.TRUE.equals(policy);
        } else {
            synchronized (getLockObject()) {
                if (admin != null) {
                    Preconditions.checkCallAuthorization(
                            isProfileOwnerOfOrganizationOwnedDevice(caller)
@@ -17649,11 +17736,10 @@ public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
                    Preconditions.checkCallAuthorization(
                            isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING));
                }
                }
            }
                return mInjector.securityLogGetLoggingEnabledProperty();
            }
        }
    }
    private void recordSecurityLogRetrievalTime() {
        synchronized (getLockObject()) {
@@ -17727,12 +17813,27 @@ public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
        }
        final CallerIdentity caller = getCallerIdentity(admin, packageName);
        if (isPermissionCheckFlagEnabled()) {
        if (securityLogV2Enabled()) {
            EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
                    admin,
                    MANAGE_DEVICE_POLICY_SECURITY_LOGGING,
                    caller.getPackageName(),
                    caller.getUserId());
            synchronized (getLockObject()) {
                Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile()
                        || areAllUsersAffiliatedWithDeviceLocked());
            }
            enforcePermission(MANAGE_DEVICE_POLICY_SECURITY_LOGGING, caller.getPackageName(),
                    UserHandle.USER_ALL);
            Boolean policy = mDevicePolicyEngine.getGlobalPolicySetByAdmin(
                    PolicyDefinition.SECURITY_LOGGING, enforcingAdmin);
            if (!Boolean.TRUE.equals(policy)) {
                Slogf.e(LOG_TAG, "%s hasn't enabled security logging but tries to retrieve logs",
                        caller.getPackageName());
                return null;
            }
        } else {
            if (admin != null) {
                Preconditions.checkCallAuthorization(
@@ -17745,11 +17846,11 @@ public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
            }
            Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile()
                    || areAllUsersAffiliatedWithDeviceLocked());
        }
            if (!mInjector.securityLogGetLoggingEnabledProperty()) {
                return null;
            }
        }
        recordSecurityLogRetrievalTime();
@@ -17758,7 +17859,7 @@ public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
                .createEvent(DevicePolicyEnums.RETRIEVE_SECURITY_LOGS)
                .setAdmin(caller.getPackageName())
                .write();
        return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
        return logs != null ? new ParceledListSlice<>(logs) : null;
    }
    @Override
@@ -23477,10 +23578,10 @@ public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
                hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
        return mInjector.binderWithCleanCallingIdentity(() -> {
            boolean canForceMigration = forceMigration && !hasNonTestOnlyActiveAdmins();
            if (!canForceMigration && !shouldMigrateToDevicePolicyEngine()) {
            if (!canForceMigration && !shouldMigrateV1ToDevicePolicyEngine()) {
                return false;
            }
            return migratePoliciesToDevicePolicyEngine();
            return migrateV1PoliciesToDevicePolicyEngine();
        });
    }
@@ -23503,14 +23604,15 @@ public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
        });
    }
    private boolean shouldMigrateToDevicePolicyEngine() {
    private boolean shouldMigrateV1ToDevicePolicyEngine() {
        return mInjector.binderWithCleanCallingIdentity(() -> !mOwners.isMigratedToPolicyEngine());
    }
    /**
     * Migrates the initial set of policies to use policy engine.
     * @return {@code true} if policies were migrated successfully, {@code false} otherwise.
     */
    private boolean migratePoliciesToDevicePolicyEngine() {
    private boolean migrateV1PoliciesToDevicePolicyEngine() {
        return mInjector.binderWithCleanCallingIdentity(() -> {
            try {
                synchronized (getLockObject()) {
@@ -23537,6 +23639,14 @@ public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
        });
    }
    /**
     * Migrates the rest of policies to use policy engine.
     */
    @GuardedBy("getLockObject()")
    private void migratePoliciesToPolicyEngineLocked() {
        maybeMigrateSecurityLoggingPolicyLocked();
    }
    private void migrateAutoTimezonePolicy() {
        Slogf.i(LOG_TAG, "Skipping Migration of AUTO_TIMEZONE policy to device policy engine,"
                + "as no way to identify if the value was set by the admin or the user.");
Loading