[AAPM] Introduce new Service for Android Advanced Protection Mode

We add a new service and manager, behind a feature flag. This service
will be used to enroll devices into a security conscious protection
mode, and to allow clients to customise behaviour based on the state of
this mode.

Both the query API and callback are protected by a install permission.
This may be revisited as the feature evolves.

AAPM can be turned on for testing via

adb shell cmd advanced_protection set-protection-enabled true

Bug: 352420507
Test: atest AdvancedProtectionServiceTest AdvancedProtectionManagerTest
Flag: android.security.aapm_api
Change-Id: Ibf8478235b147e9f844d80d083a5e04819e1b052
diff --git a/core/api/current.txt b/core/api/current.txt
index d1c0c42..7c035a8 100644
--- a/core/api/current.txt
+++ b/core/api/current.txt
@@ -239,6 +239,7 @@
     field @Deprecated public static final String PROCESS_OUTGOING_CALLS = "android.permission.PROCESS_OUTGOING_CALLS";
     field public static final String PROVIDE_OWN_AUTOFILL_SUGGESTIONS = "android.permission.PROVIDE_OWN_AUTOFILL_SUGGESTIONS";
     field public static final String PROVIDE_REMOTE_CREDENTIALS = "android.permission.PROVIDE_REMOTE_CREDENTIALS";
+    field @FlaggedApi("android.security.aapm_api") public static final String QUERY_ADVANCED_PROTECTION_MODE = "android.permission.QUERY_ADVANCED_PROTECTION_MODE";
     field public static final String QUERY_ALL_PACKAGES = "android.permission.QUERY_ALL_PACKAGES";
     field public static final String READ_ASSISTANT_APP_SEARCH_DATA = "android.permission.READ_ASSISTANT_APP_SEARCH_DATA";
     field public static final String READ_BASIC_PHONE_STATE = "android.permission.READ_BASIC_PHONE_STATE";
@@ -10798,6 +10799,7 @@
     field public static final String ACCESSIBILITY_SERVICE = "accessibility";
     field public static final String ACCOUNT_SERVICE = "account";
     field public static final String ACTIVITY_SERVICE = "activity";
+    field @FlaggedApi("android.security.aapm_api") public static final String ADVANCED_PROTECTION_SERVICE = "advanced_protection";
     field public static final String ALARM_SERVICE = "alarm";
     field public static final String APPWIDGET_SERVICE = "appwidget";
     field @FlaggedApi("android.app.appfunctions.flags.enable_app_function_manager") public static final String APP_FUNCTION_SERVICE = "app_function";
@@ -39662,6 +39664,20 @@
 
 }
 
+package android.security.advancedprotection {
+
+  @FlaggedApi("android.security.aapm_api") public class AdvancedProtectionManager {
+    method @RequiresPermission(android.Manifest.permission.QUERY_ADVANCED_PROTECTION_MODE) public boolean isAdvancedProtectionEnabled();
+    method @RequiresPermission(android.Manifest.permission.QUERY_ADVANCED_PROTECTION_MODE) public void registerAdvancedProtectionCallback(@NonNull java.util.concurrent.Executor, @NonNull android.security.advancedprotection.AdvancedProtectionManager.Callback);
+    method @RequiresPermission(android.Manifest.permission.QUERY_ADVANCED_PROTECTION_MODE) public void unregisterAdvancedProtectionCallback(@NonNull android.security.advancedprotection.AdvancedProtectionManager.Callback);
+  }
+
+  @FlaggedApi("android.security.aapm_api") public static interface AdvancedProtectionManager.Callback {
+    method public void onAdvancedProtectionChanged(boolean);
+  }
+
+}
+
 package android.security.identity {
 
   public class AccessControlProfile {
diff --git a/core/api/system-current.txt b/core/api/system-current.txt
index 7e43e46..99dc4e2 100644
--- a/core/api/system-current.txt
+++ b/core/api/system-current.txt
@@ -362,6 +362,7 @@
     field public static final String SERIAL_PORT = "android.permission.SERIAL_PORT";
     field @FlaggedApi("android.security.fsverity_api") public static final String SETUP_FSVERITY = "android.permission.SETUP_FSVERITY";
     field public static final String SET_ACTIVITY_WATCHER = "android.permission.SET_ACTIVITY_WATCHER";
+    field @FlaggedApi("android.security.aapm_api") public static final String SET_ADVANCED_PROTECTION_MODE = "android.permission.SET_ADVANCED_PROTECTION_MODE";
     field public static final String SET_CLIP_SOURCE = "android.permission.SET_CLIP_SOURCE";
     field public static final String SET_DEFAULT_ACCOUNT_FOR_CONTACTS = "android.permission.SET_DEFAULT_ACCOUNT_FOR_CONTACTS";
     field public static final String SET_HARMFUL_APP_WARNINGS = "android.permission.SET_HARMFUL_APP_WARNINGS";
@@ -12310,6 +12311,14 @@
 
 }
 
+package android.security.advancedprotection {
+
+  @FlaggedApi("android.security.aapm_api") public class AdvancedProtectionManager {
+    method @RequiresPermission(android.Manifest.permission.SET_ADVANCED_PROTECTION_MODE) public void setAdvancedProtectionEnabled(boolean);
+  }
+
+}
+
 package android.security.keystore {
 
   public class AndroidKeyStoreProvider extends java.security.Provider {
diff --git a/core/java/android/app/SystemServiceRegistry.java b/core/java/android/app/SystemServiceRegistry.java
index ea4148c..cad96e3 100644
--- a/core/java/android/app/SystemServiceRegistry.java
+++ b/core/java/android/app/SystemServiceRegistry.java
@@ -235,6 +235,8 @@
 import android.scheduling.SchedulingFrameworkInitializer;
 import android.security.FileIntegrityManager;
 import android.security.IFileIntegrityService;
+import android.security.advancedprotection.AdvancedProtectionManager;
+import android.security.advancedprotection.IAdvancedProtectionService;
 import android.security.attestationverification.AttestationVerificationManager;
 import android.security.attestationverification.IAttestationVerificationManagerService;
 import android.service.oemlock.IOemLockService;
@@ -1771,6 +1773,21 @@
                         return new SupervisionManager(ctx, service);
                     }
                 });
+        if (android.security.Flags.aapmApi()) {
+            registerService(Context.ADVANCED_PROTECTION_SERVICE, AdvancedProtectionManager.class,
+                    new CachedServiceFetcher<>() {
+                        @Override
+                        public AdvancedProtectionManager createService(ContextImpl ctx)
+                                throws ServiceNotFoundException {
+                            IBinder iBinder = ServiceManager.getServiceOrThrow(
+                                    Context.ADVANCED_PROTECTION_SERVICE);
+                            IAdvancedProtectionService service =
+                                    IAdvancedProtectionService.Stub.asInterface(iBinder);
+                            return new AdvancedProtectionManager(service);
+                        }
+                    });
+        }
+
         // DO NOT do a flag check like this unless the flag is read-only.
         // (because this code is executed during preload in zygote.)
         // If the flag is mutable, the check should be inside CachedServiceFetcher.
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index 91f7a8b..4947d1a 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -4325,6 +4325,7 @@
            //@hide: ECM_ENHANCED_CONFIRMATION_SERVICE,
             CONTACT_KEYS_SERVICE,
             RANGING_SERVICE,
+            ADVANCED_PROTECTION_SERVICE,
 
     })
     @Retention(RetentionPolicy.SOURCE)
@@ -6368,6 +6369,15 @@
 
     /**
      * Use with {@link #getSystemService(String)} to retrieve an
+     * {@link android.security.advancedprotection.AdvancedProtectionManager}
+     * @see #getSystemService(String)
+     * @see android.security.advancedprotection.AdvancedProtectionManager
+     */
+    @FlaggedApi(android.security.Flags.FLAG_AAPM_API)
+    public static final String ADVANCED_PROTECTION_SERVICE = "advanced_protection";
+
+    /**
+     * Use with {@link #getSystemService(String)} to retrieve an
      * {@link android.security.FileIntegrityManager}.
      * @see #getSystemService(String)
      * @see android.security.FileIntegrityManager
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 1a15d09..cd858bb 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -12819,6 +12819,12 @@
          */
         @Readable
         public static final String CONTEXTUAL_SEARCH_PACKAGE = "contextual_search_package";
+
+        /**
+         * Inetger property which determines whether advanced protection is on or not.
+         * @hide
+         */
+        public static final String ADVANCED_PROTECTION_MODE = "advanced_protection_mode";
     }
 
     /**
diff --git a/core/java/android/security/advancedprotection/AdvancedProtectionManager.java b/core/java/android/security/advancedprotection/AdvancedProtectionManager.java
new file mode 100644
index 0000000..59dd680f
--- /dev/null
+++ b/core/java/android/security/advancedprotection/AdvancedProtectionManager.java
@@ -0,0 +1,164 @@
+/*
+ * Copyright (C) 2024 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.advancedprotection;
+
+import android.Manifest;
+import android.annotation.CallbackExecutor;
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
+import android.annotation.RequiresPermission;
+import android.annotation.SystemApi;
+import android.annotation.SystemService;
+import android.content.Context;
+import android.os.Binder;
+import android.os.RemoteException;
+import android.security.Flags;
+import android.util.Log;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executor;
+
+/**
+ * <p>Advanced Protection is a mode that users can enroll their device into, that enhances security
+ * by enabling features and restrictions across both the platform and user apps.
+ *
+ * <p>This class provides methods to query and control the advanced protection mode
+ * for the device.
+ */
+@FlaggedApi(Flags.FLAG_AAPM_API)
+@SystemService(Context.ADVANCED_PROTECTION_SERVICE)
+public class AdvancedProtectionManager {
+    private static final String TAG = "AdvancedProtectionM";
+
+    private final ConcurrentHashMap<Callback, IAdvancedProtectionCallback>
+            mCallbackMap = new ConcurrentHashMap<>();
+
+    @NonNull
+    private final IAdvancedProtectionService mService;
+
+    /** @hide */
+    public AdvancedProtectionManager(@NonNull IAdvancedProtectionService service) {
+        mService = service;
+    }
+
+    /**
+     * Checks if advanced protection is enabled on the device.
+     *
+     * @return {@code true} if advanced protection is enabled, {@code false} otherwise.
+     */
+    @RequiresPermission(Manifest.permission.QUERY_ADVANCED_PROTECTION_MODE)
+    public boolean isAdvancedProtectionEnabled() {
+        try {
+            return mService.isAdvancedProtectionEnabled();
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Registers a {@link Callback} to be notified of changes to the Advanced Protection state.
+     *
+     * <p>The provided callback will be called on the specified executor with the updated
+     * {@link AdvancedProtectionState}. Methods are called when the state changes, as well as once
+     * on initial registration.
+     *
+     * @param executor The executor of where the callback will execute.
+     * @param callback The {@link Callback} object to register..
+     */
+    @RequiresPermission(Manifest.permission.QUERY_ADVANCED_PROTECTION_MODE)
+    public void registerAdvancedProtectionCallback(@NonNull @CallbackExecutor Executor executor,
+            @NonNull Callback callback) {
+        if (mCallbackMap.get(callback) != null) {
+            Log.d(TAG, "registerAdvancedProtectionCallback callback already present");
+            return;
+        }
+
+        IAdvancedProtectionCallback delegate = new IAdvancedProtectionCallback.Stub() {
+            @Override
+            public void onAdvancedProtectionChanged(boolean enabled) {
+                final long identity = Binder.clearCallingIdentity();
+                try {
+                    executor.execute(() -> callback.onAdvancedProtectionChanged(enabled));
+                } finally {
+                    Binder.restoreCallingIdentity(identity);
+                }
+            }
+        };
+
+        try {
+            mService.registerAdvancedProtectionCallback(delegate);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+
+        mCallbackMap.put(callback, delegate);
+    }
+
+    /**
+     * Unregister an existing {@link Callback}.
+     *
+     * @param callback The {@link Callback} object to unregister.
+     */
+    @RequiresPermission(Manifest.permission.QUERY_ADVANCED_PROTECTION_MODE)
+    public void unregisterAdvancedProtectionCallback(@NonNull Callback callback) {
+        IAdvancedProtectionCallback delegate = mCallbackMap.get(callback);
+        if (delegate == null) {
+            Log.d(TAG, "unregisterAdvancedProtectionCallback callback not present");
+            return;
+        }
+
+        try {
+            mService.unregisterAdvancedProtectionCallback(delegate);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+
+        mCallbackMap.remove(callback);
+    }
+
+    /**
+     * Enables or disables advanced protection on the device.
+     *
+     * @param enabled {@code true} to enable advanced protection, {@code false} to disable it.
+     * @hide
+     */
+    @SystemApi
+    @RequiresPermission(Manifest.permission.SET_ADVANCED_PROTECTION_MODE)
+    public void setAdvancedProtectionEnabled(boolean enabled) {
+        try {
+            mService.setAdvancedProtectionEnabled(enabled);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * A callback class for monitoring changes to Advanced Protection state
+     *
+     * <p>To register a callback, implement this interface, and register it with
+     * {@link AdvancedProtectionManager#registerAdvancedProtectionCallback(Executor, Callback)}.
+     * Methods are called when the state changes, as well as once on initial registration.
+     */
+    @FlaggedApi(Flags.FLAG_AAPM_API)
+    public interface Callback {
+        /**
+         * Called when advanced protection state changes
+         * @param enabled the new state
+         */
+        void onAdvancedProtectionChanged(boolean enabled);
+    }
+}
diff --git a/core/java/android/security/advancedprotection/IAdvancedProtectionCallback.aidl b/core/java/android/security/advancedprotection/IAdvancedProtectionCallback.aidl
new file mode 100644
index 0000000..828ce47
--- /dev/null
+++ b/core/java/android/security/advancedprotection/IAdvancedProtectionCallback.aidl
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2024 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.advancedprotection;
+
+/**
+ * A callback class for monitoring changes to Advanced Protection state
+ * @hide
+ */
+oneway interface IAdvancedProtectionCallback {
+    void onAdvancedProtectionChanged(boolean enabled);
+}
\ No newline at end of file
diff --git a/core/java/android/security/advancedprotection/IAdvancedProtectionService.aidl b/core/java/android/security/advancedprotection/IAdvancedProtectionService.aidl
new file mode 100644
index 0000000..ef0abf4
--- /dev/null
+++ b/core/java/android/security/advancedprotection/IAdvancedProtectionService.aidl
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2024 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.advancedprotection;
+
+import android.security.advancedprotection.IAdvancedProtectionCallback;
+
+/**
+ * Binder interface for apps to communicate with system server implementations of
+ * AdvancedProtectionService.
+ * @hide
+ */
+interface IAdvancedProtectionService {
+    @EnforcePermission("QUERY_ADVANCED_PROTECTION_MODE")
+    boolean isAdvancedProtectionEnabled();
+    @EnforcePermission("QUERY_ADVANCED_PROTECTION_MODE")
+    void registerAdvancedProtectionCallback(IAdvancedProtectionCallback callback);
+    @EnforcePermission("QUERY_ADVANCED_PROTECTION_MODE")
+    void unregisterAdvancedProtectionCallback(IAdvancedProtectionCallback callback);
+    @EnforcePermission("SET_ADVANCED_PROTECTION_MODE")
+    void setAdvancedProtectionEnabled(boolean enabled);
+}
\ No newline at end of file
diff --git a/core/java/android/security/responsible_apis_flags.aconfig b/core/java/android/security/responsible_apis_flags.aconfig
index 5457bbe..b593902a9 100644
--- a/core/java/android/security/responsible_apis_flags.aconfig
+++ b/core/java/android/security/responsible_apis_flags.aconfig
@@ -33,7 +33,6 @@
   }
 }
 
-
 flag {
     name: "content_uri_permission_apis"
     is_exported: true
@@ -65,6 +64,14 @@
 }
 
 flag {
+    name: "aapm_api"
+    namespace: "responsible_apis"
+    description: "Android Advanced Protection Mode Service and Manager"
+    bug: "352420507"
+    is_fixed_read_only: true
+}
+
+flag {
     name: "prevent_intent_redirect"
     namespace: "responsible_apis"
     description: "Prevent intent redirect attacks"
diff --git a/core/res/Android.bp b/core/res/Android.bp
index 17d7bfa..aa324fc 100644
--- a/core/res/Android.bp
+++ b/core/res/Android.bp
@@ -167,6 +167,7 @@
         "android.os.flags-aconfig",
         "android.os.vibrator.flags-aconfig",
         "android.media.tv.flags-aconfig",
+        "android.security.flags-aconfig",
         "com.android.hardware.input.input-aconfig",
     ],
 }
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index f067b51..0cd5434 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -846,6 +846,7 @@
     <protected-broadcast android:name="com.android.uwb.uwbcountrycode.GEOCODE_RETRY" />
     <protected-broadcast android:name="android.telephony.action.ACTION_SATELLITE_SUBSCRIBER_ID_LIST_CHANGED" />
 
+
     <!-- ====================================================================== -->
     <!--                          RUNTIME PERMISSIONS                           -->
     <!-- ====================================================================== -->
@@ -4099,6 +4100,24 @@
                 android:protectionLevel="signature|installer" />
     <uses-permission android:name="android.permission.MANAGE_ENHANCED_CONFIRMATION_STATES" />
 
+    <!-- Allows an application to toggle the device's advanced protection mode status.
+        @FlaggedApi("android.security.aapm_api")
+        @SystemApi
+        @hide -->
+    <permission android:name="android.permission.SET_ADVANCED_PROTECTION_MODE"
+        android:protectionLevel="signature|privileged"
+        android:featureFlag="android.security.aapm_api"/>
+    <uses-permission android:name="android.permission.SET_ADVANCED_PROTECTION_MODE"
+        android:featureFlag="android.security.aapm_api"/>
+
+    <!-- Allows an application to query the device's advanced protection mode status.
+        @FlaggedApi("android.security.aapm_api") -->
+    <permission android:name="android.permission.QUERY_ADVANCED_PROTECTION_MODE"
+        android:protectionLevel="normal"
+        android:featureFlag="android.security.aapm_api"/>
+    <uses-permission android:name="android.permission.QUERY_ADVANCED_PROTECTION_MODE"
+        android:featureFlag="android.security.aapm_api"/>
+
     <!-- @SystemApi @hide Allows an application to set a device owner on retail demo devices.-->
     <permission android:name="android.permission.PROVISION_DEMO_DEVICE"
                 android:protectionLevel="signature|setup|knownSigner"
diff --git a/data/etc/privapp-permissions-platform.xml b/data/etc/privapp-permissions-platform.xml
index 2e72f0e..358f0f5 100644
--- a/data/etc/privapp-permissions-platform.xml
+++ b/data/etc/privapp-permissions-platform.xml
@@ -587,6 +587,9 @@
         <permission name="android.permission.NFC_SET_CONTROLLER_ALWAYS_ON" />
         <!-- Permission required for CTS test - CtsAppTestCases -->
         <permission name="android.permission.KILL_UID" />
+        <!-- Permission required for CTS test - AdvancedProtectionManagerTest -->
+        <permission name="android.permission.SET_ADVANCED_PROTECTION_MODE" />
+        <permission name="android.permission.QUERY_ADVANCED_PROTECTION_MODE" />
     </privapp-permissions>
 
     <privapp-permissions package="com.android.statementservice">
diff --git a/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java b/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java
index 4dc8424..d3ee400 100644
--- a/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java
+++ b/packages/SettingsProvider/src/android/provider/settings/backup/SecureSettings.java
@@ -282,5 +282,6 @@
         Settings.Secure.ON_DEVICE_INTELLIGENCE_IDLE_TIMEOUT_MS,
         Settings.Secure.MANDATORY_BIOMETRICS,
         Settings.Secure.MANDATORY_BIOMETRICS_REQUIREMENTS_SATISFIED,
+        Settings.Secure.ADVANCED_PROTECTION_MODE,
     };
 }
diff --git a/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java b/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java
index 688676d..d34ccc5 100644
--- a/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java
+++ b/packages/SettingsProvider/src/android/provider/settings/validators/SecureSettingsValidators.java
@@ -442,5 +442,6 @@
         VALIDATORS.put(Secure.MANDATORY_BIOMETRICS, new InclusiveIntegerRangeValidator(0, 1));
         VALIDATORS.put(Secure.MANDATORY_BIOMETRICS_REQUIREMENTS_SATISFIED,
                 new InclusiveIntegerRangeValidator(0, 1));
+        VALIDATORS.put(Secure.ADVANCED_PROTECTION_MODE, BOOLEAN_VALIDATOR);
     }
 }
diff --git a/packages/Shell/Android.bp b/packages/Shell/Android.bp
index 2531454..3350efc 100644
--- a/packages/Shell/Android.bp
+++ b/packages/Shell/Android.bp
@@ -8,7 +8,10 @@
 }
 
 // used both for the android_app and android_library
-shell_srcs = ["src/**/*.java",":dumpstate_aidl"]
+shell_srcs = [
+    "src/**/*.java",
+    ":dumpstate_aidl",
+]
 shell_static_libs = ["androidx.legacy_legacy-support-v4"]
 
 android_app {
@@ -22,6 +25,9 @@
     libs: [
         "device_policy_aconfig_flags_lib",
     ],
+    flags_packages: [
+        "android.security.flags-aconfig",
+    ],
     platform_apis: true,
     certificate: "platform",
     privileged: true,
@@ -43,4 +49,7 @@
     static_libs: shell_static_libs,
     platform_apis: true,
     manifest: "AndroidManifest.xml",
+    flags_packages: [
+        "android.security.flags-aconfig",
+    ],
 }
diff --git a/packages/Shell/AndroidManifest.xml b/packages/Shell/AndroidManifest.xml
index 456fedf..03c06bb 100644
--- a/packages/Shell/AndroidManifest.xml
+++ b/packages/Shell/AndroidManifest.xml
@@ -947,6 +947,11 @@
 
     <!-- Permission required for CTS test - CtsNfcTestCases -->
     <uses-permission android:name="android.permission.NFC_SET_CONTROLLER_ALWAYS_ON" />
+    <!-- Permission required for CTS test - AdvancedProtectionManagerTest -->
+    <uses-permission android:name="android.permission.SET_ADVANCED_PROTECTION_MODE"
+        android:featureFlag="android.security.aapm_api"/>
+    <uses-permission android:name="android.permission.QUERY_ADVANCED_PROTECTION_MODE"
+        android:featureFlag="android.security.aapm_api"/>
 
     <!-- Permission required for CTS test - CtsAppTestCases -->
     <uses-permission android:name="android.permission.KILL_UID" />
diff --git a/services/core/java/com/android/server/security/advancedprotection/AdvancedProtectionService.java b/services/core/java/com/android/server/security/advancedprotection/AdvancedProtectionService.java
new file mode 100644
index 0000000..9a63c823
--- /dev/null
+++ b/services/core/java/com/android/server/security/advancedprotection/AdvancedProtectionService.java
@@ -0,0 +1,247 @@
+/*
+ * Copyright (C) 2024 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 com.android.server.security.advancedprotection;
+
+import static android.provider.Settings.Secure.ADVANCED_PROTECTION_MODE;
+
+import android.Manifest;
+import android.annotation.EnforcePermission;
+import android.annotation.NonNull;
+import android.content.Context;
+import android.os.Binder;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.Looper;
+import android.os.Message;
+import android.os.PermissionEnforcer;
+import android.os.RemoteException;
+import android.os.ResultReceiver;
+import android.os.ShellCallback;
+import android.provider.Settings;
+import android.security.advancedprotection.IAdvancedProtectionCallback;
+import android.security.advancedprotection.IAdvancedProtectionService;
+import android.util.ArrayMap;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.FgThread;
+import com.android.server.LocalServices;
+import com.android.server.SystemService;
+import com.android.server.pm.UserManagerInternal;
+
+import java.io.FileDescriptor;
+import java.util.ArrayList;
+
+/** @hide */
+public class AdvancedProtectionService extends IAdvancedProtectionService.Stub  {
+    private static final int MODE_CHANGED = 0;
+    private static final int CALLBACK_ADDED = 1;
+
+    private final Handler mHandler;
+    private final AdvancedProtectionStore mStore;
+    private final ArrayMap<IBinder, IAdvancedProtectionCallback> mCallbacks = new ArrayMap<>();
+
+    private AdvancedProtectionService(@NonNull Context context) {
+        super(PermissionEnforcer.fromContext(context));
+        mHandler = new AdvancedProtectionHandler(FgThread.get().getLooper());
+        mStore = new AdvancedProtectionStore(context);
+    }
+
+    @VisibleForTesting
+    AdvancedProtectionService(@NonNull Context context, @NonNull AdvancedProtectionStore store,
+            @NonNull Looper looper, @NonNull PermissionEnforcer permissionEnforcer) {
+        super(permissionEnforcer);
+        mStore = store;
+        mHandler = new AdvancedProtectionHandler(looper);
+    }
+
+    @Override
+    @EnforcePermission(Manifest.permission.QUERY_ADVANCED_PROTECTION_MODE)
+    public boolean isAdvancedProtectionEnabled() {
+        isAdvancedProtectionEnabled_enforcePermission();
+        final long identity = Binder.clearCallingIdentity();
+        try {
+            return isAdvancedProtectionEnabledInternal();
+        } finally {
+            Binder.restoreCallingIdentity(identity);
+        }
+    }
+
+    // Without permission check
+    private boolean isAdvancedProtectionEnabledInternal() {
+        return mStore.retrieve();
+    }
+
+    @Override
+    @EnforcePermission(Manifest.permission.QUERY_ADVANCED_PROTECTION_MODE)
+    public void registerAdvancedProtectionCallback(@NonNull IAdvancedProtectionCallback callback)
+            throws RemoteException {
+        registerAdvancedProtectionCallback_enforcePermission();
+        IBinder b = callback.asBinder();
+        b.linkToDeath(new DeathRecipient(b), 0);
+        synchronized (mCallbacks) {
+            mCallbacks.put(b, callback);
+            sendCallbackAdded(isAdvancedProtectionEnabledInternal(), callback);
+        }
+    }
+
+    @Override
+    @EnforcePermission(Manifest.permission.QUERY_ADVANCED_PROTECTION_MODE)
+    public void unregisterAdvancedProtectionCallback(@NonNull IAdvancedProtectionCallback callback)
+            throws RemoteException {
+        unregisterAdvancedProtectionCallback_enforcePermission();
+        synchronized (mCallbacks) {
+            mCallbacks.remove(callback.asBinder());
+        }
+    }
+
+    @Override
+    @EnforcePermission(Manifest.permission.SET_ADVANCED_PROTECTION_MODE)
+    public void setAdvancedProtectionEnabled(boolean enabled) {
+        setAdvancedProtectionEnabled_enforcePermission();
+        final long identity = Binder.clearCallingIdentity();
+        try {
+            synchronized (mCallbacks) {
+                if (enabled != isAdvancedProtectionEnabledInternal()) {
+                    mStore.store(enabled);
+                    sendModeChanged(enabled);
+                }
+            }
+        } finally {
+            Binder.restoreCallingIdentity(identity);
+        }
+    }
+
+    @Override
+    public void onShellCommand(FileDescriptor in, FileDescriptor out,
+            FileDescriptor err, @NonNull String[] args, ShellCallback callback,
+            @NonNull ResultReceiver resultReceiver) {
+        (new AdvancedProtectionShellCommand(this))
+                .exec(this, in, out, err, args, callback, resultReceiver);
+    }
+
+    void sendModeChanged(boolean enabled) {
+        Message.obtain(mHandler, MODE_CHANGED, /*enabled*/ enabled ? 1 : 0, /*unused */ -1)
+                .sendToTarget();
+    }
+
+    void sendCallbackAdded(boolean enabled, IAdvancedProtectionCallback callback) {
+        Message.obtain(mHandler, MODE_CHANGED, /*enabled*/ enabled ? 1 : 0, /*unused*/ -1,
+                        /*callback*/ callback)
+                .sendToTarget();
+    }
+
+    public static final class Lifecycle extends SystemService {
+        private final AdvancedProtectionService mService;
+
+        public Lifecycle(@NonNull Context context) {
+            super(context);
+            mService = new AdvancedProtectionService(context);
+        }
+
+        @Override
+        public void onStart() {
+            publishBinderService(Context.ADVANCED_PROTECTION_SERVICE, mService);
+        }
+    }
+
+    @VisibleForTesting
+    static class AdvancedProtectionStore {
+        private final Context mContext;
+        private static final int APM_ON = 1;
+        private static final int APM_OFF = 0;
+        private final UserManagerInternal mUserManager;
+
+        AdvancedProtectionStore(@NonNull Context context) {
+            mContext = context;
+            mUserManager = LocalServices.getService(UserManagerInternal.class);
+        }
+
+        void store(boolean enabled) {
+            Settings.Secure.putIntForUser(mContext.getContentResolver(),
+                    ADVANCED_PROTECTION_MODE, enabled ? APM_ON : APM_OFF,
+                    mUserManager.getMainUserId());
+        }
+
+        boolean retrieve() {
+            return Settings.Secure.getIntForUser(mContext.getContentResolver(),
+                    ADVANCED_PROTECTION_MODE, APM_OFF, mUserManager.getMainUserId()) == APM_ON;
+        }
+    }
+
+    private class AdvancedProtectionHandler extends Handler {
+        private AdvancedProtectionHandler(@NonNull Looper looper) {
+            super(looper);
+        }
+
+        @Override
+        public void handleMessage(@NonNull Message msg) {
+            switch (msg.what) {
+                //arg1 == enabled
+                case MODE_CHANGED:
+                    handleAllCallbacks(msg.arg1 == 1);
+                    break;
+                //arg1 == enabled
+                //obj == callback
+                case CALLBACK_ADDED:
+                    handleSingleCallback(msg.arg1 == 1, (IAdvancedProtectionCallback) msg.obj);
+                    break;
+            }
+        }
+
+        private void handleAllCallbacks(boolean enabled) {
+            ArrayList<IAdvancedProtectionCallback> deadObjects = new ArrayList<>();
+
+            synchronized (mCallbacks) {
+                for (int i = 0; i < mCallbacks.size(); i++) {
+                    IAdvancedProtectionCallback callback = mCallbacks.valueAt(i);
+                    try {
+                        callback.onAdvancedProtectionChanged(enabled);
+                    } catch (RemoteException e) {
+                        deadObjects.add(callback);
+                    }
+                }
+
+                for (int i = 0; i < deadObjects.size(); i++) {
+                    mCallbacks.remove(deadObjects.get(i).asBinder());
+                }
+            }
+        }
+
+        private void handleSingleCallback(boolean enabled, IAdvancedProtectionCallback callback) {
+            try {
+                callback.onAdvancedProtectionChanged(enabled);
+            } catch (RemoteException e) {
+                mCallbacks.remove(callback.asBinder());
+            }
+        }
+    }
+
+    private final class DeathRecipient implements IBinder.DeathRecipient {
+        private final IBinder mBinder;
+
+        DeathRecipient(IBinder  binder) {
+            mBinder = binder;
+        }
+
+        @Override
+        public void binderDied() {
+            synchronized (mCallbacks) {
+                mCallbacks.remove(mBinder);
+            }
+        }
+    }
+}
diff --git a/services/core/java/com/android/server/security/advancedprotection/AdvancedProtectionShellCommand.java b/services/core/java/com/android/server/security/advancedprotection/AdvancedProtectionShellCommand.java
new file mode 100644
index 0000000..42505ad
--- /dev/null
+++ b/services/core/java/com/android/server/security/advancedprotection/AdvancedProtectionShellCommand.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2024 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 com.android.server.security.advancedprotection;
+
+import android.annotation.NonNull;
+import android.annotation.SuppressLint;
+import android.os.RemoteException;
+import android.os.ShellCommand;
+
+import java.io.PrintWriter;
+
+class AdvancedProtectionShellCommand extends ShellCommand {
+    private AdvancedProtectionService mService;
+
+    AdvancedProtectionShellCommand(@NonNull AdvancedProtectionService service) {
+        mService = service;
+    }
+
+    @Override
+    public int onCommand(String cmd) {
+        if (cmd == null) {
+            return handleDefaultCommands(cmd);
+        }
+        final PrintWriter pw = getOutPrintWriter();
+        try {
+            switch (cmd) {
+                case "help":
+                    onHelp();
+                    return 0;
+                case "set-protection-enabled":
+                    return setProtectionEnabled();
+                case "is-protection-enabled":
+                    return isProtectionEnabled(pw);
+            }
+        } catch (RemoteException e) {
+            pw.println("Remote exception: " + e);
+        }
+        return -1;
+    }
+
+    @Override
+    public void onHelp() {
+        PrintWriter pw = getOutPrintWriter();
+        dumpHelp(pw);
+    }
+
+    private void dumpHelp(@NonNull PrintWriter pw) {
+        pw.println("Advanced Protection Mode commands:");
+        pw.println("  help");
+        pw.println("      Print this help text.");
+        pw.println("  set-protection-enabled [true|false]");
+        pw.println("  is-protection-enabled");
+    }
+
+    @SuppressLint("AndroidFrameworkRequiresPermission")
+    private int setProtectionEnabled() throws RemoteException {
+        String protectionMode = getNextArgRequired();
+        mService.setAdvancedProtectionEnabled(Boolean.parseBoolean(protectionMode));
+        return 0;
+    }
+
+    @SuppressLint("AndroidFrameworkRequiresPermission")
+    private int isProtectionEnabled(@NonNull PrintWriter pw) throws RemoteException {
+        boolean protectionMode = mService.isAdvancedProtectionEnabled();
+        pw.println(protectionMode);
+        return 0;
+    }
+}
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 7ea1dcd..dd6278e 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -246,6 +246,7 @@
 import com.android.server.security.FileIntegrityService;
 import com.android.server.security.KeyAttestationApplicationIdProviderService;
 import com.android.server.security.KeyChainSystemService;
+import com.android.server.security.advancedprotection.AdvancedProtectionService;
 import com.android.server.security.rkp.RemoteProvisioningService;
 import com.android.server.selinux.SelinuxAuditLogsService;
 import com.android.server.sensorprivacy.SensorPrivacyService;
@@ -1760,6 +1761,12 @@
                 mSystemServiceManager.startService(AppFunctionManagerService.class);
                 t.traceEnd();
             }
+
+            if (android.security.Flags.aapmApi()) {
+                t.traceBegin("StartAdvancedProtectionService");
+                mSystemServiceManager.startService(AdvancedProtectionService.Lifecycle.class);
+                t.traceEnd();
+            }
         } catch (Throwable e) {
             Slog.e("System", "******************************************");
             Slog.e("System", "************ Failure starting core service");
diff --git a/services/tests/servicestests/src/com/android/server/security/advancedprotection/AdvancedProtectionServiceTest.java b/services/tests/servicestests/src/com/android/server/security/advancedprotection/AdvancedProtectionServiceTest.java
new file mode 100644
index 0000000..727b435
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/security/advancedprotection/AdvancedProtectionServiceTest.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2024 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 com.android.server.security.advancedprotection;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+
+import android.Manifest;
+import android.annotation.SuppressLint;
+import android.content.Context;
+import android.os.RemoteException;
+import android.os.test.FakePermissionEnforcer;
+import android.os.test.TestLooper;
+import android.provider.Settings;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class AdvancedProtectionServiceTest {
+    private AdvancedProtectionService mService;
+    private FakePermissionEnforcer mPermissionEnforcer;
+    private Context mContext;
+
+    @Before
+    @SuppressLint("VisibleForTests")
+    public void setup() throws Settings.SettingNotFoundException {
+        mContext = mock(Context.class);
+        mPermissionEnforcer = new FakePermissionEnforcer();
+        mPermissionEnforcer.grant(Manifest.permission.SET_ADVANCED_PROTECTION_MODE);
+        mPermissionEnforcer.grant(Manifest.permission.QUERY_ADVANCED_PROTECTION_MODE);
+
+        AdvancedProtectionService.AdvancedProtectionStore store =
+                new AdvancedProtectionService.AdvancedProtectionStore(mContext) {
+                    private boolean mEnabled = false;
+
+                    @Override
+                    boolean retrieve() {
+                        return mEnabled;
+                    }
+
+                    @Override
+                    void store(boolean enabled) {
+                        this.mEnabled = enabled;
+                    }
+                };
+
+        mService = new AdvancedProtectionService(mContext, store, new TestLooper().getLooper(),
+                mPermissionEnforcer);
+    }
+
+    @Test
+    public void testEnableProtection() throws RemoteException {
+        mService.setAdvancedProtectionEnabled(true);
+        assertTrue(mService.isAdvancedProtectionEnabled());
+    }
+
+    @Test
+    public void testDisableProtection() throws RemoteException {
+        mService.setAdvancedProtectionEnabled(false);
+        assertFalse(mService.isAdvancedProtectionEnabled());
+    }
+
+    @Test
+    public void testSetProtection_withoutPermission() {
+        mPermissionEnforcer.revoke(Manifest.permission.SET_ADVANCED_PROTECTION_MODE);
+        assertThrows(SecurityException.class, () -> mService.setAdvancedProtectionEnabled(true));
+    }
+
+    @Test
+    public void testGetProtection_withoutPermission() {
+        mPermissionEnforcer.revoke(Manifest.permission.QUERY_ADVANCED_PROTECTION_MODE);
+        assertThrows(SecurityException.class, () -> mService.isAdvancedProtectionEnabled());
+    }
+}