Boot completed permission android

Содержание
  1. Автозапуск приложения при загрузке
  2. Практика: ошибки и особенности эксплуатации
  3. Отладка ресивера в эмуляторе и на реальных устройствах
  4. Итоги
  5. Boot completed permission android
  6. Android. Автозапуск приложения при загрузке: теория и практика
  7. 1. Теория
  8. 2. Практика: ошибки и особенности эксплуатации
  9. 3. Отладка ресивера в эмуляторе и на реальных устройствах.
  10. Итоги
  11. Android permissions for system developers
  12. Definitions
  13. Permissions for regular apps
  14. Install time permissions
  15. Defining a permission
  16. Requesting a permission
  17. Checking a permission
  18. Verifying an app has an install time permission
  19. End-to-end: Protecting an RPC call via a permission
  20. Runtime permissions
  21. Defining a runtime permission
  22. Requesting a runtime permission
  23. Checking a runtime permission
  24. Verifying an app has a runtime time permission
  25. End-to-end: Protecting an RPC call via a runtime permission
  26. Restricted permissions
  27. System fixed permission
  28. Background access
  29. Pre granting
  30. Permission restricted components
  31. End-to-end A service only the system can bind to
  32. Permissions for system apps
  33. Multiple permission levels
  34. App-op permissions
  35. Defining an app-op permission
  36. Checking an app-op permission
  37. Granting an app-op permission
  38. Signature permissions
  39. Preinstalled permissions
  40. Privileged permissions
  41. Restricted by tests
  42. Whitelist
  43. Limited permissions
  44. Role protected permissions
  45. Development permissions
  46. Other protection levels

Автозапуск приложения при загрузке

Тема получения сообщения ACTION_BOOT_COMPLETED остается актуальной и по сей день. Многие новички сталкиваются с проблемой: они не получают в своих приложениях данное сообщение.

Можно выделить следующие правила:

В манифесте указать разрешение:

В манифесте в блоке application зарегистрировать приёмник на приём сообщения ACTION_BOOT_COMPLETED:

В описании без необходимости не указывайте атрибуты «enabled», «exported» и т.д. Вполне достаточно настроек и атрибутов по умолчанию.

Код вашего широковещательного приёмника:

Если ваш приёмник используется только для сообщения ACTION_BOOT_COMPLETED, то проверка «if» не обязательна. Однако иногда разработчики используют один и тот же ресивер для разных сообщений. В этом случае фильтруйте сообщения, проверяя их внутри метода onReceive().

Приложение должно быть установлено на внутреннюю память. Android устроена таким образом, что сообщение ACTION_BOOT_COMPLETED отправляется приложениям перед монтированием внешний памяти. Поэтому приложения, установленные на внешней памяти, никогда не получат это сообщение. Чтобы указать системе не устанавливать приложение на внешнюю память, в манифесте НЕ нужно прописывать для атрибута «@android:installLocation» значения «auto» или «preferExternal». По умолчанию, т.е. если этот атрибут не указан, Android установит ваше приложение только на внутреннюю память. Однако согласно официальной документации лучше явно указать значение «internalOnly», чтобы у вас и других разработчиков не возникло искушение в будущем указать иное значение.

После установки или принудительной остановки (force stop) приложение должно быть запущено хотя бы один раз, чтобы система «запомнила» это приложение для отправки ему сообщения ACTION_BOOT_COMPLETED. Такое поведение было реализовано в версии Android 3.1 в целях безопасности. В чем суть? Все только что установленные приложения находятся в состоянии «stopped» (не путать с активити, т.к. система управляет этим состоянием у приложений и активностей по-разному). В это же состояние приложение «уходит», когда пользователь в настройках телефона принудительно его останавливает. Пока приложение находится в таком состоянии, оно не будет запущено системой ни по какой причине (например, через ACTION_BOOT_COMPLETED), исключая, конечно же, запуск самим пользователем. Благодаря такому нововведению немалая часть вирусов и троянцев» перестала работать, т.к. уже нет возможности запуститься автоматом после установки.

Исключение составляют системные приложения.

Особенности режима Fast boot в HTC-устройствах: Известно, что HTC-устройства не перезагружаются в классическом смысле, а используют так называемый режим Fast boot (это одна из форм гибернации), сохраняя состояние ОС на диск. Поэтому сообщение ACTION_BOOT_COMPLETED не отправляется системой, т.к. в действительности перезагрузка не происходит. Вместо ACTION_BOOT_COMPLETED система может отправить следующие сообщения:

В вашем приложении укажите в теге «receiver» кроме ACTION_BOOT_COMPLETED также вышеуказанные сообщения. Кроме этого необходимо прописать дополнительное разрешение:

Практика: ошибки и особенности эксплуатации

Разберём ошибки, которые совершают новички при настройке приложения и в коде.

  • После установки или force stop приложение ни разу не запускалось.
  • Приложение установлено не на внутренней памяти, или пользователь вручную перенес его на внешнюю память.
  • У некоторых разработчиков приём начинал работать, когда они указывали относительное имя класса приёмника.
  • Также некоторые разработчики в Logcat не видели своих сообщений из ресивера. Используйте Toast для отладки:
  • Опечатки или несуществующие сообщения внутри тега ресивера:
  • Неправильное положение элементов в манифесте приложения:
    «uses-permission» должен быть указан только как прямой потомок элемента «manifest», не нужно его указывать/дублировать в теге «receiver»;
    тег «receiver» должен быть указан только как прямой потомок элемента «application».
  • Различные диспетчеры задач, оптимизаторы, приложения безопасности, Startup-менеджеры и т.п. могут отслеживать регистрацию приложения для приема ACTION_BOOT_COMPLETED и запрещать/разрешать его получение при загрузке. Удалите эти приложения или добавьте в исключение вашу программу в их настройках.
  • Как было указано выше, некоторые устройства используют режим Fast boot. Можно попробовать в настройках телефона отключить этот режим.
  • В приложении нет ни одной активности, поэтому после установки у пользователя нет возможности хотя бы один раз запустить ваше приложение. Из-за этого сообщение ACTION_BOOT_COMPLETED не будет отправлено в ваше приложение.
  • Нет ошибки, но всё же: указаны лишние, не обязательные атрибуты в теге «receiver», например («uses-permission», «enabled», «exported») (Примечание от меня: сомнительный совет, у меня работало):

Отладка ресивера в эмуляторе и на реальных устройствах

В терминале выполните:

Далее, чтобы отправить ACTION_BOOT_COMPLETED всем приложениям, наберите в терминале:

Или для отправки ACTION_BOOT_COMPLETED конкретному приложению наберите в терминале:

В эмуляторе: установите ваше ПО, запустив его из студии. При этом студия соберет ваш проект, установит приложение и запустит его. После этого закройте эмулятор (это аналогично выключению на реальном устройстве). Чтобы получить сообщение ACTION_BOOT_COMPLETED, запустите эмулятор из AVD-менеджера, а не с помощью кнопки «Run app» в студии.

После запуска эмулятора во вкладке Android Monitor укажите запущенный эмулятор и ваше приложение, чтобы просмотреть логи logcat.

Итоги

Чтобы ваше приложение запускалось при загрузке на всех устройствах, манифест как минимум должен выглядеть так:

Источник

Boot completed permission android

В этом уроке мы научимся запускать свое приложение вместе с загрузкой системы. То есть, когда вы перезапустите устройство, то наше приложение автоматически запуститься. Это может пригодиться в том случае, если вы создали что то типа антивируса, лаунчера или еще что то такое, что должно запускаться при запуске системы Android на устройстве.

Реализация этой возможности довольно проста. В своем приложении мы должны прослушивать действие BOOT_COMPLETED и настраивать реакцию приложения в случае выполнения этого действия. Прослушивать это действие можно, используя BroadcastReceiver, который и будет запускать activity нашего приложения после того, как получит сигнал о свершении действия BOOT_COMPLETED.

Создадим простое приложение, состоящее из всего одного текстового объекта TextView и будем запускать его при загрузке Android системы на устройстве.

Создаем новый проект, открываем файл activity_main.xml и добавляем туда элемент TextView:

Файл MainActivity.java в этот раз выглядит предельно просто:

Теперь беремся за создание того самого класса BroadcastReceiver. Он также будет предельно прост и состоит по сути всего из одного действия — запуска основной activity приложения с помощью намерения Intent. Создаем новый класс под названием AutoStart.java, который расширяется от BroadcastReceiver и добавляем в него следующее:

Все что осталось сделать, это объявить о созданном классе в файле AndroidManifest.xml. Объявляем наш приемник события загрузки системы BOOT_COMPLETED, который будет получен программой с помощью intent, а также настраиваем разрешение на прослушивание действия загрузки системы RECEIVE_BOOT_COMPLETED:

Вот и все, чтобы протестировать наше чудо Android приложение, нужно установить его на устройство и перезапустить аппарат — при запуске вы увидите, что вместе с системой запустилось и наше приложение!

Источник

Android. Автозапуск приложения при загрузке: теория и практика

1. Теория

Взглянув на примеры из официального источника (например, этот и этот) и изучив рекомендации на сайте stackoverflow.com, можно выделить следующие правила:

    В манифесте в элементе «manifest» указать разрешение:

В манифесте в элементе «application» зарегистрировать ваш ресивер на прием сообщения ACTION_BOOT_COMPLETED:

Используйте правильное полное или относительное имя класса вашего broadcast-ресивера. В описании ресивера без необходимости не указывайте атрибуты «enabled», «exported» и т.д. Вполне достаточно настроек и атрибутов по умолчанию.

Код вашего broadcast-ресивера:

Если ваш ресивер используется только для сообщения ACTION_BOOT_COMPLETED, то проверка «if» не обязательна. Однако иногда разработчики используют один и тот же ресивер для разных сообщений. В этом случае фильтруйте сообщения, проверяя их внутри метода onReceive.

Приложение должно быть установлено на внутреннюю память. ОС Android устроена таким образом, что сообщение ACTION_BOOT_COMPLETED отправляется приложениям перед монтированием внешний памяти. Поэтому приложения, установленные на внешней памяти, никогда не получат это сообщение. Чтобы указать системе не устанавливать приложение на внешнюю память, в манифесте НЕ нужно прописывать для атрибута «@android:installLocation» значения «auto» или «preferExternal». По умолчанию, т.е. если этот атрибут не указан, ОС установит ваше приложение только на внутреннюю память. Однако согласно официальной документации лучше явно указать значение «internalOnly», чтобы у вас и других разработчиков не возникло искушение в будущем указать иное значение.

После установки или принудительной остановки (force stop) приложение должно быть запущено хотя бы один раз, чтобы система «запомнила» это приложение для отправки ему сообщения ACTION_BOOT_COMPLETED. Такое поведение было реализовано в версии Android 3.1 в целях безопасности. В чем суть? Все только что установленные приложения находятся в состоянии «stopped» (не путать с активити, т.к. ОС управляет этим состоянием у приложений и активити по-разному). В это же состояние приложение «уходит», когда пользователь в настройках телефона принудительно его останавливает. Пока приложение находится в таком состоянии, оно не будет запущено системой ни по какой причине (например, через ACTION_BOOT_COMPLETED), исключая, конечно же, запуск самим пользователем. Благодаря такому нововведению немалая часть«вирусни и троянцев» перестала работать, т.к. уже нет возможности запуститься автоматом после установки.

Исключение составляют системные приложения: см. замечание пользователя kolipass.

Особенности режима Fast boot в HTC-устройствах. Известно, что HTC-устройства не перезагружаются в классическом смысле, а используют так наз. режим Fast boot (это одна из форм гибернации), сохраняя состояние ОС на диск. Поэтому сообщение ACTION_BOOT_COMPLETED не отправляется системой, т.к. в действительности перезагрузка не происходит (см. здесь). Вместо ACTION_BOOT_COMPLETED система может отправить следующие сообщения:

В вашем приложении укажите в теге «receiver» кроме ACTION_BOOT_COMPLETED также вышеуказанные сообщения. Кроме этого необходимо прописать разрешение в дополнение к п.1:

2. Практика: ошибки и особенности эксплуатации

Разберем ошибки, которые совершают новички при настройке приложения и в коде.

    После установки или force stop приложение ни разу не запускалось (см. п.1.5).

Приложение установлено не на внутренней памяти, или пользователь вручную перенес его на внешнюю память (см. п. 1.4).

У некоторых разработчиков прием начинал работать, когда они указывали относительное имя класса ресивера.

Также некоторые разработчики, отлаживая приложение, в logcat не видели своих сообщений из ресивера. Используйте Toast для отладки:

Опечатки или несуществующие сообщения внутри тега ресивера:

Неправильное положение элементов в манифесте приложения:

  • «uses-permission» должен быть указан только как прямой потомок элемента «manifest», не нужно его указывать/дублировать в теге «receiver»;
  • тег «receiver» должен быть указан только как прямой потомок элемента «application».

  • Различные диспетчеры задач, оптимизаторы, приложения безопасности, Startup-менеджеры и т.п. могут отслеживать регистрацию приложения для приема ACTION_BOOT_COMPLETED и запрещать/разрешать его получение при загрузке. Удалите эти приложения или добавьте в исключение вашу программу в их настройках.

    Как было указано выше, некоторые устройства используют режим Fast boot. Можно попробовать в настройках телефона отключить этот режим или учесть п. 1.6.

    В приложении нет ни одной активити, поэтому после установки у пользователя нет возможности хотя бы 1 раз запустить ваше приложение. Из-за этого сообщение ACTION_BOOT_COMPLETED не будет отправлено в ваше приложение.

    Не ошибки, но все же: указаны лишние, не обязательные атрибуты в теге «receiver», например («uses-permission», «enabled», «exported»):

    3. Отладка ресивера в эмуляторе и на реальных устройствах.

      В терминале выполните:

    Далее, чтобы отправить ACTION_BOOT_COMPLETED всем приложениям, наберите в терминале:

    Или для отправки ACTION_BOOT_COMPLETED конкретному приложению наберите в терминале:

    В эмуляторе: установите ваше ПО, запустив его из студии. При этом студия соберет ваш проект, установит приложение и запустит его. После этого закройте эмулятор (это аналогично выключению на реальном устройстве). Чтобы получить сообщение ACTION_BOOT_COMPLETED, запустите эмулятор из AVD-менеджера, а не с помощью кнопки «Run app» в тулбаре студии.

    После запуска эмулятора во вкладке Android Monitor укажите запущенный эмулятор и ваше приложение, чтобы просмотреть логи logcat.

    Итоги

    Чтобы ваше приложение запускалось при загрузке на всех устройствах, манифест как минимум должен выглядеть так:

    Код ресивера, как правило, будет таким:

    Надеюсь, эта статья поможет новичкам побороть «коварного врага» под названием «ACTION_BOOT_COMPLETED».

    Источник

    Android permissions for system developers

    This document targets system developers. App developers should refer to the public documentation.

    Definitions

    Each app (often called package) has a unique name called package name. Each package has a manifest file describing properties of the package. The android system server is in a special package named “android”.

    When a package gets installed the package is (usually) assigned a unique identifier called uid . This is the same as a uid in Linux, but this often leads to confusion. It is easiest to see a uid as a unique identifier for a package.

    Usually an app is running in a container called a process. Each process has a unique id called pid, but unlike the uid the pid changes each time the process is restarted and app that are not currently running don’t have a pid. The process container makes sure that other apps cannot negatively interact with an app. Processes can only interact via controlled interactions called remote procedure calls (RPCs). Android’s RPC mechanism is called Binder.

    As no app code can be trusted the permission need to be checked on the receiving side of the Binder call.

    For more details please take a look at Android’s security model.

    Permissions for regular apps

    Install time permissions

    The purpose of install time permissions is to control access to APIs where it does not makes sense to involve the user. This can be either because the API is not sensitive, or because additional checks exist.

    Another benefit of install time permissions is that is becomes very easy to monitor which apps can access certain APIs. E.g. by checking which apps have the android.permission.INTERNET permission you can list all apps that are allowed to use APIs that can send data to the internet.

    Defining a permission

    Any package can define a permission. For that it simply adds an entry in the manifest file

    Any package can do this, including the system package. When talking about permissions for system apps we will see that it is important which package defines a permission.

    It is common good practice to prefix the permission name with the package name to avoid collisions.

    Requesting a permission

    Any app can request any permission via adding an entry in the manifest file like

    A requested permission does not necessarily mean that the permission is granted. When and how a permission is granted depends on the protection level of the permission. If no protection level is set, the permission will always be granted. Such “normal” permissions can still be useful as it will be easy to find apps using a certain functionality on app stores and by checking dumpsys package .

    Checking a permission

    Context.checkPermission(permission, pid, uid) returns if the pid/uid has the permission. By far the most common case is to check the permission on the receiving end of a binder call. In this case the pid can be read as Binder.callingPid() and the uid as Binder.callingUid() . The uid is a mandatory argument as permissions are maintained per uid. The pid can be set to -1 if not pid is available. The context class contains handy wrappers for checkPermission , such as enforeCallingPermission which calls checkPermission with Binder.callingPid / Binder.callingUid and throws a SecurityException when the permission is not granted.

    Verifying an app has an install time permission

    In dumpsys package my.package.name there are two sections. In requested permissions all permissions of the uses-permission tags are listed. In install permission the permissions with their grant state are listed. If an install time permission is not listed here, it is not granted.

    End-to-end: Protecting an RPC call via a permission

    Service Manifest
    Service code
    Caller Manifest

    Runtime permissions

    Runtime permission must be granted by the user during runtime. This is needed if the API protects data or functionality that is sensitive for the user. E.g. the users current location is protected by a runtime permission.

    Users want a system that is secure and privacy focused by default. User can also often not make a good choice when asked at the wrong time without enough context. Hence in general runtime permissions should be avoided and the API should be built in a way where no private data needs to be leaked.

    Defining a runtime permission

    Runtime permissions are defined in the same way as install time permissions. To tag them as runtime permissions the protectionLevel needs to be set to dangerous. Dangerous is a synonym for runtime permissions in the Android platform.

    Requesting a runtime permission

    Similar to install time permissions any app can request a runtime permission by adding the to the manifest.

    By default runtime permissions are not granted. The app needs to call Activity.requestPermissions during runtime to ask the user for the permission. The user might then grant or deny and once the decision is made the activity is called by via Activity.onPermissionGranted .

    During development and testing a runtime permission can be granted via the pm shell command or by using the UiAutomator.grantRuntimePermission API call. Please note that this does not grant the app-op synchronously. Unless the app needs to test the actual permission grant flow it is recommended to grant the runtime permissions during install using adb install -g /my/package.apk .

    Checking a runtime permission

    For runtime permissions defined by 3rd party apps it is fine to check a runtime permission like an install time permission. For system defined permissions you need to check all runtime permissions by using the PermissionChecker utility. It is good practice to use the tool anywhere possible.

    The permission checker might return PERMISSION_DENIED_APP_OP which should lead to a silent failure. This can only happen for system defined runtime permissions.

    Runtime permissions and app-ops

    The PermissionChecker code fundamentally looks like this:

    For each platform defined runtime permission there is a matching app-op. When calling AppOpsManager.noteOp this returns either MODE_ALLOWED or MODE_IGNORED .

    This value is then used to decide between PERMISSION_DENIED_APP_OP and PERMISSION_GRANTED .

    The primary purpose of the special PERMISSION_DENIED_APP_OP state was to support apps targeting an SDK lower than 23. These apps do not understand the concept of denied runtime permissions. Hence they would crash when getting a SecurityException . To protect the users’ privacy while still not crashing the app the special PERMISSION_DENIED_APP_OP mandates that the API should somehow silently fail.

    A secondary use case of the AppOpsManager.noteOp calls is to track which apps perform what runtime protected actions.

    Verifying an app has a runtime time permission

    In dumpsys package my.package.name the runtime permissions are listed per uid. I.e. different users might have different runtime permission grants and shared uids share a grant-set. If a runtime permission is listed as requested but not in the runtime permission section it is in its initial state, i.e. not granted.

    End-to-end: Protecting an RPC call via a runtime permission

    Service Manifest
    Service code
    Caller Manifest
    Caller code

    Restricted permissions

    Some runtime permissions are restricted. They are annotated in the platforms AndroidManifest.xml as hardRestricted or softRestricted .

    Restricted permissions behave uncommon when not whitelisted. When whitelisted the permissions behave normally. What uncommon means depends on the whether they are hard or soft restricted.

    They can either be whitelisted during upgrade P->Q by the system or need to be whitelisted by the installer via PackageInstaller.SessionParams.setWhitelistedRestrictedPermissions . If this method is not used all permissions will be whitelisted.

    Afterwards the app that originally installed the app can change the whitelisting state via PackageManager.addWhitelistedRestrictedPermission and PackageManager.removeWhitelistedRestrictedPermission .

    The system tracks the source of the whitelisting by having three different flags RESTRICTION_SYSTEM_EXEMPT , RESTRICTION_UPGRADE_EXEMPT , and RESTRICTION_INSTALLER_EXEMPT ,

    The flags can be checked in dumpsys package my.package.name

    Hard restricted

    Hard restricted permissions need to be whitelisted to be grant-able.

    Soft restricted

    The behavior of non-whitelisted soft restricted permissions is not uniform. The behavior is defined in the SoftRestrictedPermissionPolicy .

    System fixed permission

    Some runtime permissions are required for normal operation of the device. In this case the system can grant the permission as SYSTEM_FIXED . In this case the permission can be seen in the permission management settings but cannot be revoked by the user.

    The flag can be checked in dumpsys package my.package.name

    Background access

    Whether the app is currently visible to the user is reflected in the ActivityManager ‘s proc state. There is a lot of granularity to this, but runtime permissions are using the app-ops services’ definition of foreground and background.

    Most runtime permissions are not affected by foreground/background-ness. Microphone and Camera are foreground-only while Location is usually foreground-only, but background access can be added by granting the ACCESS_BACKGROUND_LOCATION modifier runtime permission.

    Microphone and Camera

    Currently these only allow access while the app is in foreground. There is a manual whitelist for e.g. the voice interaction service.

    This is currently (Mar 2020) reworked and will behave like location soon.

    Location

    As described above the app-op mode for granted permissions is MODE_ALLOWED to allow access or MODE_IGNORED to suppress access.

    The important case is the case where the permission is granted and the app-op is MODE_IGNORED . In the case of location this state causes the LocationManagerService to stop delivering locations to the app. This is not a breaking behavior as the same scenario happens if e.g. no satellites could be found.

    This behavior is used to implement the foregound/background behavior for location. If the app is in the foreground the app-op mode is MODE_ALLOWED and works normally. If the app goes into background the app-op mode changes to MODE_IGNORED . This means that locations are delivered while the app is in foreground and while the app is background, the app won’t get any locations.

    The automatic switching between MODE_ALLOWED and MODE_IGNORED is done inside of AppOpsManager .

    Background access can be enabled by also granting the ACCESS_BACKGROUND_LOCATION to the app. In this case the app-op mode will always be MODE_ALLOWED .

    Granting

    An app following the best practices does not ask for any runtime permissions until absolutely needed. Once needed the request should be made in context. I.e. the user should understand from the current state of the app and the user’s action why the request is made. E.g. if the user presses a “show me the next ATM”-button the user is most likely expecting a request for the location permission.

    This is central premise to the runtime permission UI. It is the app’s responsibility to avoid showing permission requests dialogs to the user which might get denied. These dialogs are not meant to be user-choices, they are meant to be user-confirmations.

    Hence any denied permission dialog is probably due to the app asking for permissions the user does not expect. If too many permission requests get denied the app is apparently trying to get more than the user wants to give to the app. In this case the permission gets permanently denied and all future requests will be denied automatically without showing a UI.

    Context.requestPermission calls for more than one permission are allowed and might result in multiple dialogs in sequence. This might make sense for e.g. getting microphone and camera permission when starting a video call.

    Each time the the user makes a choice (either to grant or the deny) a permission request the permission is marked as USER_SET . If a permission gets permanently denied the permission is marked as USER_FIXED .

    This can be found in dumpsys package my.package.name

    Settings

    By far most interactions with the permission system are via the permission grant flow. The main purpose of the permission settings is to show the user the previous choices and allow the user to revisit previous choices. In reality few users do that.

    Grouping

    There are too many runtime permissions for the user to individually manage. Hence the UI bundles the permissions into groups. Apps should never assume the grouping. The grouping might change with SDK updates, but also at any other time. Certain form factors or locales might use other permission models and sometimes some of the permissions of a group cannot be granted for various reasons. The grouping is defined inside the permission controller app.

    If two permissions belong to a group and the first permission is already granted the second one will be granted on request of the app without user interaction. For that reason a permission group with at least one individual permission granted will show up as granted in the UI.

    Alternate permission management

    It is not allowed to build alternate permission management UIs. While restricting innovation is not a good choice this is a required one to enforce a consistent, predictable, but flexible permission model for users and app developers.

    Further some data needed for permission management (e.g. the grouping) is not available outside the permission controller app.

    Hence all permission management UI needs to be integrated with AOSP.

    Pre granting

    Runtime permissions protect user private data. It is a violation of user trust to give the data to an app without explicit user consent (i.e. the user granting the permission). Still the user expects certain functionality (e.g. receiving a phone call) to work out of the box.

    Hence the DefaultPermissionGrantPolicy and roles allow to grant permission without the user . The default permission grant policy grants permissions for three categories of apps

    • Apps running in well defined uids as they are considered as part of the platform
    • Apps that are in certain predefined categories, e.g. the browser and the SMS app. This is meant for the most basic phone functionality, not for all pre-installed apps.
    • Apps that are explicitly mentioned as pre-grant-exceptions. This is meant to be used for setup and other highly critical use cases, not to improve the user experience. The exceptions are listed in xml files in etc/ and follow the following syntax

    Pre-granted runtime permissions can still be revoked by the user in settings unless they are granted as SYSTEM_FIXED .

    Whether a permission was granted by the default can be checked in the permission flags of dumpsys package my.package.name

    Permission restricted components

    As publicly documented it is possible to restrict starting an activity/binding to a service by using permission.

    It is a common pattern to

    • define a permission in the platform as signature
    • protect a service in an app by this permission using the android:permission attribute of the tag

    Then it is guaranteed that only the system can bind to such service. This is used for services that provide extensions to platform functionality, such as auto-fill services, print services, and accessibility services.

    This does not work for app-op or runtime permissions as the way to check these permissions is more complex than install time permissions.

    End-to-end A service only the system can bind to

    Make sure to set the android:permission flag for this service. As developers can forget this it is a good habit to check this before binding to the service. This makes sure that the services are implemented correctly and no random app can bind to the service.

    The result is that the permission is granted only to the system. It is not granted to the service’s package, but this has no negative side-effects.

    Permission definition
    Service definition

    Manifest of the service providing the functionality:

    System server code binding to service

    Permissions for system apps

    System apps need to integrate deeper with the system than regular apps. Hence they need to be able to call APIs not available to other apps. This is implemented by granting permissions to these system apps and then enforcing the permissions in the API similar to other install time permissions.

    System apps are not different from regular apps, but the protection levels (e.g. privileged, preinstalled) mentioned in this section are more commonly used by system apps.

    Multiple permission levels

    It is possible to assign multiple protection levels to a permission. Very common combinations are for example adding signature to all permissions to make sure the platform signed apps can be granted the permission, e.g. privileged|signature .

    The permission will be granted if the app qualifies for any of the permission levels.

    App-op permissions

    App-op permissions are user-switchable permissions that are not runtime permissions. This should be used for permissions that are really only meant to be ever granted to a very small amount of apps. Traditionally granting these permissions is intentionally very heavy weight so that the user really needs to understand the use case. For example one use case is the INTERACT_ACROSS_PROFILES permission that allows apps of different users within the same profile group to interact. Of course this is breaking a very basic security container and hence should only ever be granted with a lot of care.

    Warning: Most app-op permissions follow this logic, but most of them also have exceptions and special behavior. Hence this section is a guideline, not a rule.

    Defining an app-op permission

    Only the platform can reasonably define an app-op permission. The permission is defined in the platforms manifest using the appop protection level

    Almost always the protection level is app-op | something else, like signature (in the case above) or privileged.

    Checking an app-op permission

    The PermissionChecker utility can check app-op permissions with the same syntax as runtime permissions.

    The permission checker internally follows this flow

    Granting an app-op permission

    The permission‘s grant state is only considered if the app-op’s mode is MODE_DEFAULT . This allows to have default grants while still being overridden by the app-op.

    The permission is then granted by setting the app-op mode. This is usually done via dedicated APIs for each use case. Similarly whether and how an app can request the permission is different for each app-op permission.

    When implementing a new app-op permission, make sure to set the app-op mode using AppOpsManager.setUidMode to make sure the permission is granted on the uid as this is the security domain.

    During development app-ops can be grated to app via the appops set shell command. E.g.

    sets the INTERACT_ACROSS_PROFILES app-op for uid 10187 to allow thereby granting apps in this uid the ability to interact across profiles.

    Most UIs for app-op permissions are in the “Special app access” section of the settings app.

    In most cases the permission should only be granted with the user’s explicit agreement, usually by allowing the app to directly open the “Special app access” page for this permission and app.

    To repeat: this is a guideline for app-op permissions and there are many exceptions.

    Signature permissions

    Only apps signed with the defining app’s certificate will be granted the permission. This is used to restrict APIs to apps of the same developer.

    This is frequently used to restrict permissions defined by the platform to apps also signed with the platform’s certificate. As this is a very tight restriction this is recommended for permissions that are only used by apps built out of AOSP which are signed with the platform certificate.

    Please note that OEMs sign their platform themselves. I.e. OEMs can implement new apps using these permissions. It is unlikely that 3rd party apps will be able to use APIs protected by signature permissions as they are usually not signed with the platform certificate.

    If possible, role protected permissions should also be considered as an alternative to better restrict which apps may get the permission.

    Such permissions are defined and checked like an install time permission.

    Preinstalled permissions

    This means that the app has to be pre-installed. There is no restriction what apps are pre-installed on a particular device install there. Hence it can be really any app including 3rd party apps.

    Hence this permission level is discouraged unless there are further restrictions.

    If possible, role protected permissions should also be considered as an alternative to better restrict which apps may get the permission.

    Such permissions are defined and checked like an install time permission.

    Privileged permissions

    This means that the app has to be pre-installed and in the system/priv directory in the filesystem. There is no restriction what apps are in this directory on a particular device. Hence it can be really any app including 3rd party apps.

    An app is only ever granted privileged permissions requested by the pre-installed apk. I.e. privileged permissions added in updates will never be granted.

    Hence this permission level is discouraged unless there are further restrictions.

    If possible, role protected permissions should also be considered as an alternative to better restrict which apps may get the permission.

    Such permissions are defined and checked like an install time permission.

    Restricted by tests

    As all apps that might get preinstalled or privilidged permissions need to be pre-installed and new images need to pass compliance tests it is possible to use a test to whitelist the apps that can request the permission.

    Example of such a test:

    Whitelist

    As mentioned above it is not suggested, but still common practice to install 3rd party apps as privileged. To verify and restrict which privileged permissions those apps get granted all privileged permissions need to be explicitly whitelisted in a file /etc .

    If the pre-installed apk of an app requests a privileged permission that is not mentioned in any whitelist or that is not denied the system will refuse to boot. As mentioned above privileged permissions added in updates to the pre-installed app will never be granted.

    Limited permissions

    E.g. installer, wellbeing, documenter, etc. This allows the system to restrict the permission to a well defined app or set of apps. It is possible to add new types in PackageManagerService .

    Which apps qualify for such a permission level is flexible and custom for each such level. Usually they refer to a single or small set of apps, usually — but not always — apps defined in AOSP.

    This type of permission is deprecated in favor of role protected permissions.

    These permissions are defined and checked like an install time permission.

    Role protected permissions

    Development permissions

    By adding the development protection level to any permissions the permission can be granted via the pm grant shell command. This appears to be useful for development and testing, but it is very highly discouraged. Any user can grant them permanently via adb, hence adding this tag removes all guarantees the permission might otherwise provide.

    Other protection levels

    There are other levels (such as runtime ) but they are for special purposes on should not be used by platform developers.

    Источник

    Читайте также:  Темы доты для андроидов
  • Оцените статью