1<!-- 2 Copyright (C) 2020 The Android Open Source Project 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License 15 --> 16 17# Android permissions for system developers 18 19This document targets system developers. App developers should refer to the [public 20 documentation](https://developer.android.com/guide/topics/permissions/overview). 21 22## Definitions 23 24Each app (often called package) has a unique name called package name. Each package has a manifest 25file describing properties of the package. The android system server is in a special package named 26"android". 27 28When a package gets installed the package is (usually) assigned a unique identifier called [uid 29](../os/Users.md#int-uid). 30This is the same as a uid in Linux, but this often leads to confusion. It is easiest to see a uid 31as a unique identifier for a package. 32 33Usually an app is running in a container called a process. Each process has a unique id called 34pid, but unlike the uid the pid changes each time the process is restarted and app that are not 35currently running don't have a pid. The process container makes sure that other apps cannot 36negatively interact with an app. Processes can only interact via controlled interactions called 37remote procedure calls (RPCs). Android’s RPC mechanism is called _Binder_. 38 39As no app code can be trusted the permission need to be checked on the receiving side of the 40Binder call. 41 42For more details please take a look at [Android's security model](../os/Users.md#security-model). 43 44## Permissions for regular apps 45 46### Install time permissions 47 48The purpose of install time permissions is to control access to APIs where it does not makes sense 49to involve the user. This can be either because the API is not sensitive, or because additional 50checks exist. 51 52Another benefit of install time permissions is that is becomes very easy to monitor which apps can 53access certain APIs. E.g. by checking which apps have the `android.permission.INTERNET` permission 54you can list all apps that are allowed to use APIs that can send data to the internet. 55 56#### Defining a permission 57 58Any package can define a permission. For that it simply adds an entry in the manifest file 59`<permission android:name="com.example.myapp.myfirstpermission" />` 60 61Any package can do this, including the system package. When talking about [permissions for system 62 apps](#permissions-for-system-apps) we will see that it is important which package defines a 63permission. 64 65It is common good practice to prefix the permission name with the package name to avoid collisions. 66 67#### Requesting a permission 68 69Any app can request any permission via adding an entry in the manifest file like 70`<uses-permission android:name="com.example.myapp.myfirstpermission" />` 71 72A requested permission does not necessarily mean that the permission is granted. When and how a 73permission is granted depends on the protection level of the permission. If no protection level is 74set, the permission will always be granted. Such "normal" permissions can still be useful as it 75will be easy to find apps using a certain functionality on app stores and by checking `dumpsys 76package`. 77 78#### Checking a permission 79 80`Context.checkPermission(permission, pid, uid)` returns if the pid/uid has the permission. By far 81the most common case is to check the permission on the receiving end of a binder call. In this case 82the pid can be read as `Binder.callingPid()` and the uid as `Binder.callingUid()`. The uid is a 83mandatory argument as permissions are maintained per uid. The pid can be set to -1 84if not pid is available. The context class contains handy wrappers for `checkPermission`, such as 85`enforeCallingPermission` which calls checkPermission with `Binder.callingPid`/`Binder.callingUid` 86and throws a SecurityException when the permission is not granted. 87 88#### Verifying an app has an install time permission 89 90In `dumpsys package my.package.name` there are two sections. In requested permissions all 91permissions of the `uses-permission` tags are listed. In install permission the permissions with 92their grant state are listed. If an install time permission is not listed here, it is not granted. 93 94``` 95Packages: 96 Package [com.android.packageinstaller] (2eb7062): 97 userId=10071 98 [...] 99 requested permissions: 100 android.permission.MANAGE_USERS 101 android.permission.INSTALL_PACKAGES 102 android.permission.DELETE_PACKAGES 103 android.permission.READ_INSTALL_SESSIONS 104 android.permission.RECEIVE_BOOT_COMPLETED 105 android.permission.HIDE_NON_SYSTEM_OVERLAY_WINDOWS 106 android.permission.USE_RESERVED_DISK 107 android.permission.UPDATE_APP_OPS_STATS 108 android.permission.MANAGE_APP_OPS_MODES 109 android.permission.INTERACT_ACROSS_USERS_FULL 110 android.permission.SUBSTITUTE_NOTIFICATION_APP_NAME 111 android.permission.PACKAGE_USAGE_STATS 112 install permissions: 113 android.permission.USE_RESERVED_DISK: granted=true 114 android.permission.INSTALL_PACKAGES: granted=true 115 android.permission.RECEIVE_BOOT_COMPLETED: granted=true 116 android.permission.INTERACT_ACROSS_USERS_FULL: granted=true 117 android.permission.PACKAGE_USAGE_STATS: granted=true 118 android.permission.SUBSTITUTE_NOTIFICATION_APP_NAME: granted=true 119 android.permission.READ_INSTALL_SESSIONS: granted=true 120 android.permission.MANAGE_USERS: granted=true 121 android.permission.HIDE_NON_SYSTEM_OVERLAY_WINDOWS: granted=true 122 android.permission.MANAGE_APP_OPS_MODES: granted=true 123 android.permission.UPDATE_APP_OPS_STATS: granted=true 124 android.permission.DELETE_PACKAGES: granted=true 125``` 126 127#### End-to-end: Protecting an RPC call via a permission 128 129##### Service Manifest 130 131```xml 132<manifest xmlns:android="http://schemas.android.com/apk/res/android" 133 package="com.android.example.myservice"> 134 <!-- Define a permission --> 135 <permission android:name="com.android.example.myservice.MY_PERMISSION" /> 136 <application> 137 <service android:name=".MyService" android:exported="true" /> 138 </application> 139</manifest> 140``` 141 142##### Service code 143 144```kotlin 145class MyService : Service() { 146 override fun onBind(intent: Intent?): IBinder? { 147 return object : IMyService.Stub() { 148 override fun doSomething() { 149 // Verify that calling UID has the permission 150 enforceCallingPermission( 151 "com.android.example.myservice.MY_PERMISSION", 152 "Need to hold permission" 153 ) 154 // do something 155 } 156 }.asBinder() 157 } 158} 159``` 160 161##### Caller Manifest 162 163```xml 164<manifest xmlns:android="http://schemas.android.com/apk/res/android" 165 package="com.android.example.myapp"> 166 <!-- request a permission --> 167 <uses-permission android:name="com.android.example.myservice.MY_PERMISSION" /> 168 <application /> 169</manifest> 170``` 171 172### Runtime permissions 173 174Runtime permission must be granted by the user during runtime. This is needed if the API protects 175data or functionality that is sensitive for the user. E.g. the users current location is protected 176by a runtime permission. 177 178Users want a system that is secure and privacy focused by default. User can also often not make a 179good choice when asked at the wrong time without enough context. Hence in general runtime 180permissions should be avoided and the API should be built in a way where no private data needs to be 181leaked. 182 183#### Defining a runtime permission 184 185Runtime permissions are defined in the same way as install time permissions. To tag them as runtime 186permissions the `protectionLevel` needs to be set to dangerous. Dangerous is a synonym for 187runtime permissions in the Android platform. 188 189```xml 190<uses-permission android:name="com.example.myapp.myfirstruntimepermission" 191 android:protectionLevel="dangerous" /> 192``` 193 194#### Requesting a runtime permission 195 196Similar to install time permissions any app can request a runtime permission by adding the 197`<uses-permission android:name="com.example.myapp.myfirstruntimepermission" />` 198to the manifest. 199 200By default runtime permissions are not granted. The app needs to call `Activity.requestPermissions` 201during runtime to ask the user for the permission. The user might then grant or deny and once the 202decision is made the activity is called by via `Activity.onPermissionGranted`. 203 204During development and testing a runtime permission can be granted via the `pm` shell command or by 205using the `UiAutomator.grantRuntimePermission` API call. Please note that this does _not_ grant the 206[app-op](#runtime-permissions-and-app-ops) synchronously. Unless the app needs to test the actual 207permission grant flow it is recommended to grant the runtime permissions during install using 208`adb install -g /my/package.apk`. 209 210#### Checking a runtime permission 211 212For runtime permissions defined by a 3rd party apps it is fine to check a runtime 213permission like an install time permission. For system defined permissions you need to check all 214runtime permissions by using the `PermissionChecker` utility. It is good practice to use the tool 215anywhere possible. 216 217The permission checker might return `PERMISSION_DENIED_APP_OP` which should lead to a silent 218failure. This can only happen for system defined runtime permissions. 219 220##### Runtime permissions and app-ops 221 222> See [App-ops](../app/AppOps.md). 223 224The PermissionChecker code fundamentally looks like this: 225 226```kotlin 227class PermissionChecker { 228 fun checkCallingPermission(context: Context, permission: String) { 229 if (isRuntimePermission(permission)) { 230 if (context.checkPermission(uid, permission) == DENIED) { 231 return PERMISSION_DENIED 232 } 233 234 val appOpOfPermission = AppOpsManager.permissionToOp(permission) 235 if (appOpOfPermission == null) { 236 // not platform defined 237 return PERMISSION_GRANTED 238 } 239 240 val appOpMode = appOpsManager.noteOp(appOpOfPermission) 241 if (appOpMode == AppOpsManager.MODE_ALLOWED) { 242 return PERMISSION_GRANTED 243 } else { 244 return PERMISSION_DENIED_APP_OP 245 } 246 } else { 247 return PERMISSION_DENIED 248 } 249 } 250} 251``` 252 253For each platform defined runtime permission there is a matching app-op. When calling 254`AppOpsManager.noteOp` this returns either `MODE_ALLOWED` or `MODE_IGNORED`. 255 256This value is then used to decide between `PERMISSION_DENIED_APP_OP` and `PERMISSION_GRANTED`. 257 258The primary purpose of the special `PERMISSION_DENIED_APP_OP` state was to support apps targeting an 259SDK lower than 23. These apps do not understand the concept of denied runtime permissions. Hence 260they would crash when getting a `SecurityException`. To protect the users' privacy while still not 261crashing the app the special `PERMISSION_DENIED_APP_OP` mandates that the API should somehow 262silently fail. 263 264A secondary use case of the `AppOpsManager.noteOp` calls is to 265[track](../app/AppOps.md#Appops-for-tracking) which apps perform what runtime protected actions. 266 267#### Verifying an app has a runtime time permission 268 269In `dumpsys package my.package.name` the runtime permissions are listed per uid. I.e. different 270users might have different runtime permission grants and shared uids share a grant-set. If a runtime 271permission is listed as requested but not in the runtime permission section it is in it’s initial 272state, i.e. not granted. 273 274``` 275Packages: 276 Package [com.google.android.GoogleCamera] (ccb6af): 277 userId=10181 278 [...] 279 requested permissions: 280 android.permission.ACCESS_COARSE_LOCATION 281 android.permission.ACCESS_FINE_LOCATION 282 android.permission.ACCESS_NETWORK_STATE 283 android.permission.ACCESS_NOTIFICATION_POLICY 284 android.permission.ACCESS_WIFI_STATE 285 android.permission.BIND_WALLPAPER 286 android.permission.CAMERA 287 android.permission.CHANGE_WIFI_STATE 288 android.permission.INTERNET 289 android.permission.GET_PACKAGE_SIZE 290 android.permission.NFC 291 android.permission.READ_SYNC_SETTINGS 292 android.permission.RECEIVE_BOOT_COMPLETED 293 android.permission.RECORD_AUDIO 294 android.permission.SET_WALLPAPER 295 android.permission.USE_CREDENTIALS 296 android.permission.VIBRATE 297 android.permission.WAKE_LOCK 298 android.permission.WRITE_EXTERNAL_STORAGE [ ... ] 299 android.permission.WRITE_SETTINGS 300 android.permission.WRITE_SYNC_SETTINGS 301 com.google.android.elmyra.permission.CONFIGURE_ASSIST_GESTURE 302 com.google.android.providers.gsf.permission.READ_GSERVICES 303 android.permission.FOREGROUND_SERVICE 304 com.google.android.googlequicksearchbox.permission.LENSVIEW_BROADCAST 305 android.permission.READ_EXTERNAL_STORAGE [ ... ] 306 [...] 307 User 0: [ ... ] 308 overlay paths: 309 runtime permissions: 310 android.permission.ACCESS_FINE_LOCATION: granted=false [ ... ] 311 android.permission.READ_EXTERNAL_STORAGE: granted=true [ ... ] 312 android.permission.ACCESS_COARSE_LOCATION: granted=false [ ... ] 313 android.permission.CAMERA: granted=true [ ... ] 314 android.permission.WRITE_EXTERNAL_STORAGE: granted=true [ ... ] 315 android.permission.RECORD_AUDIO: granted=true[ ... ] 316``` 317 318#### End-to-end: Protecting an RPC call via a runtime permission 319 320##### Service Manifest 321 322```xml 323<manifest xmlns:android="http://schemas.android.com/apk/res/android" 324 package="com.android.example.myservice"> 325 <!-- Define a runtime permission --> 326 <permission android:name="com.android.example.myservice.MY_RUNTIME_PERMISSION" 327 android:protectionLevel="dangerous" /> 328 <application> 329 <service android:name=".MyService" android:exported="true" /> 330 </application> 331</manifest> 332``` 333 334##### Service code 335 336```kotlin 337class MyService : Service() { 338 override fun onBind(intent: Intent?): IBinder? { 339 return object : IMyService.Stub() { 340 override fun doSomething(callingPackage: String?, callingFeatureId: String?) { 341 Objects.requireNonNull(callingPackageName) 342 343 // Verify that calling UID has the permission 344 when (run { 345 PermissionChecker.checkCallingPermission( 346 this@MyService, 347 "com.android.example.myservice.MY_RUNTIME_PERMISSION", 348 callingPackageName, 349 callingFeatureId, 350 "Did something" 351 ) 352 }) { 353 PERMISSION_GRANTED -> /* do something */ 354 PERMISSION_DENIED_APP_OP -> /* silent failure, do nothing */ 355 else -> throw SecurityException( 356 "Cannot do something as caller is missing " 357 + "com.android.example.myservice.MY_RUNTIME_PERMISSION" 358 ) 359 } 360 } 361 }.asBinder() 362 } 363} 364``` 365 366##### Caller Manifest 367 368```xml 369<manifest xmlns:android="http://schemas.android.com/apk/res/android" 370 package="com.android.example.myapp"> 371 <!-- request a permission --> 372 <uses-permission android:name="com.android.example.myservice.MY_RUNTIME_PERMISSION" /> 373 <application /> 374</manifest> 375``` 376 377##### Caller code 378 379```kotlin 380class MyActivity : Activity { 381 fun callDoSomething() { 382 if (checkSelfPermission("com.android.example.myservice.MY_RUNTIME_PERMISSION") == PERMISSION_DENIED) { 383 // Interrupt operation and request permission 384 requestPermissions(arrayOf("com.android.example.myservice.MY_RUNTIME_PERMISSION"), 23) 385 } else { 386 myService.doSomething(this@MyActivity.opPackageName, this@MyActivity.featureId) 387 } 388 } 389 390 override fun onRequestPermissionsResult( 391 requestCode: Int, 392 permissions: Array<String>, 393 grantResults: IntArray 394 ) { 395 if (requestCode == 23 && grantResults[0] == PERMISSION_GRANTED) { 396 // Finish operation 397 callDoSomething() 398 } 399 } 400} 401``` 402 403#### Restricted permissions 404 405Some runtime permissions are restricted. They are annotated in the platforms `AndroidManifest.xml` 406has `hardRestricted` or `softRestricted`. 407 408Restricted permissions behave uncommon when not whitelisted. When whitelisted the permissions 409behave normally. What uncommon means depends on the whether they are hard or soft restricted. 410 411They can either be whitelisted during upgrade P->Q, but the system or need to be whitelisted by the 412installer via `PackageInstaller.SessionParams.setWhitelistedRestrictedPermissions`. If this method 413is not used all permissions will be whitelisted. 414 415Afterwards the app that originally installed the app can change the whitelisting state via 416`PackageManager.addWhitelistedRestrictedPermission` and 417`PackageManager.removeWhitelistedRestrictedPermission`. 418 419The system tracks the source of the whitelisting by having three different flags 420 `RESTRICTION_SYSTEM_EXEMPT`, `RESTRICTION_UPGRADE_EXEMPT`, and `RESTRICTION_INSTALLER_EXEMPT`, 421 422The flags can be checked in `dumpsys package my.package.name` 423 424``` 425User 0: 426 [...] 427 runtime permissions: 428 android.permission.READ_EXTERNAL_STORAGE: granted=false, flags=[ RESTRICTION_UPGRADE_EXEMPT ] 429 android.permission.ACCESS_FINE_LOCATION: granted=true, flags=[ RESTRICTION_SYSTEM_EXEMPT|RESTRICTION_UPGRADE_EXEMPT ] 430``` 431 432##### Hard restricted 433 434Hard restricted permissions need to be whitelisted to be grant-able. 435 436##### Soft restricted 437 438The behavior of non-whitelisted soft restricted permissions is not uniform. The behavior is 439defined in the `SoftRestrictedPermissionPolicy`. 440 441#### System fixed permission 442 443Some runtime permissions are required for normal operation of the device. In this case the system 444can grant the permission as `SYSTEM_FIXED`. In this case the permission can be seen in the 445[permission management settings](#settings) but cannot be revoked by the user. 446 447The flag can be checked in `dumpsys package my.package.name` 448``` 449User 0: 450 [...] 451 runtime permissions: 452 android.permission.READ_EXTERNAL_STORAGE: granted=true, flags=[ SYSTEM_FIXED|GRANTED_BY_DEFAULT ] 453``` 454 455#### Background access 456 457Whether the app is currently visible to the user is reflected in the `ActivityManager`'s proc state. 458There is a lot of granularity to this, but runtime permissions are using the [app-ops services' 459](../app/AppOps.md) definition of foreground and background. 460 461Most runtime permissions are not affected by foreground/background-ness. Microphone and Camera are 462foreground-only while Location is usually foreground-only, but background access can be added by 463granting the `ACCESS_BACKGROUND_LOCATION` modifier runtime permission. 464 465##### Microphone and Camera 466 467Currently these only allow access while in the app is in foreground. There is a manual whitelist 468for e.g. the voice interaction service. 469 470This is currently (Mar 2020) reworked and will behave like [location](#location) soon. 471 472##### Location 473 474As described [above](#runtime-permissions-and-app-ops) the app-op mode for granted permissions is 475`MODE_ALLOWED` to allow access or `MODE_IGNORED` to suppress access. 476 477The important case is the case where the permission is granted and the app-op is `MODE_IGNORED`. In 478the case of location this state causes the `LocationManagerService` to stop delivering locations to 479the app. This is not a breaking behavior as the same scenarios happens if e.g. no satellites 480could be found. 481 482This behavior is used to implement the foregound/background behavior for location. If the app is 483in the foreground the app-op mode is `MODE_ALLOWED` and works normally. If the app goes into 484background the app-op mode changes to `MODE_IGNORED`. This means that locations are delivered while 485the app is in foreground and while the app is background, the app won't get any locations. 486 487The automatic switching between `MODE_ALLOWED` and `MODE_IGNORED` is done inside of 488 [`AppOpsManager`](../app/AppOps.md#foreground). 489 490Background access can be enabled by also granting the `ACCESS_BACKGROUND_LOCATION` to the app. In 491this case the app-op mode will always be `MODE_ALLOWED`. 492 493#### UI 494 495##### Granting 496 497An app following the best practices does not ask for any runtime permissions until absolutely 498needed. Once needed the request should be made in context. I.e. the user should understand from the 499current state of the app and the user's action why the request is made. E.g. if the user presses 500a "show me the next ATM"-button the user is most likely expecting a request for the location 501permission. 502 503This is central premise to the runtime permission UI. It is the app's responsibility to avoid 504showing permission requests dialogs to the user which might get denied. These dialogs are not 505meant to be user-choices, they are meant to be user-confirmations. 506 507Hence any denied permission dialog is probably due to the app asking for permissions the user 508does not expect. If too many permission requests get denied the app is apparently trying to get 509more than the user wants to give to the app. In this case the permission gets permanently denied 510and all future requests will be denied automatically without showing a UI. 511 512`Context.requestPermission` calls for more than one permission are allowed and might result in 513multiple dialogs in sequence. This might make sense for e.g. getting microphone and camera 514permission when starting a video call. 515 516Each time the the user makes a choice (either to grant or the deny) a permission request the 517permission is marked as `USER_SET`. If a permission gets permanently denied the permission is marked 518as `USER_FIXED`. 519 520This can be found in `dumpsys package my.package.name` 521``` 522User 0: 523 [...] 524 runtime permissions: 525 android.permission.READ_EXTERNAL_STORAGE: granted=false, flags=[ USER_SET|USER_FIXED ] 526 android.permission.ACCESS_FINE_LOCATION: granted=true, flags=[ USER_SET ] 527``` 528 529##### Settings 530 531By far most interactions with the permission system are via the [permission grant flow](#granting). 532The main purpose of the permission settings is to show the user the previous choices and allow 533the user to revisit previous choices. In reality few users do that. 534 535##### Grouping 536 537There are too many runtime permissions for the user to individually manage. Hence the UI bundles the 538permissions into groups. **Apps should never assume the grouping**. The grouping might change 539with SDK updates, but also at any other time. Certain form factors or locales might use other 540permission models and sometimes some of the permissions of a group cannot be granted for various 541reasons. The grouping is defined inside the permission controller app. 542 543If two permissions belong to a group and the first permission is already granted the second one 544will be granted on request of the app without user interaction. For that reason a permission 545group with at least one individual permission granted will show up as granted in the UI. 546 547##### Alternate permission management 548 549It is not allowed to build alternate permission management UIs. While restricting innovation is not 550a good choice this is a required one to enforce a consistent, predictable, but flexible permission 551model for users and app developers. 552 553Further some data needed for permission management (e.g. the grouping) is not available outside 554the permission controller app. 555 556Hence all permission management UI needs to be integrated with AOSP. 557 558#### Pre granting 559 560Runtime permissions protect user private data. It is a violation of user trust to give the data 561to an app without explicit user consent (i.e. the user [granting](#granting) the permission 562). Still the user expects certain functionality (e.g. receiving a phone call) to work out of the 563box. 564 565Hence the `DefaultPermissionGrantPolicy` and roles allow to grant permission without the user 566. The default permission grant policy grants permissions for three categories of apps 567- Apps running in well defined [uids](../os/Users.md#int-uid) as they are considered as part of 568 the platform 569- Apps that are in certain predefined categories, e.g. the browser and the SMS app. This is 570 meant for the most basic phone functionality, not for all pre-installed apps. 571- Apps that are explicitly mentioned as a pre-grant-exceptions. This is meant to be used for setup 572 and other highly critical use cases, not to improve the user experience. The exceptions are listed 573 in xml files in `etc/` and follow the following syntax 574```xml 575<exceptions> 576 <exception package="my.package.name"> 577 <permission name="android.permission.ACCESS_FINE_LOCATION" fixed="false"/> 578 </exception> 579</exceptions> 580``` 581 582Pre-granted runtime permissions can still be revoked by the user in [settings](#settings) unless 583they are granted as `SYSTEM_FIXED`. 584 585Whether a permission was granted by the default can be checked in the permission flags of 586`dumpsys package my.package.name` 587 588``` 589User 0: 590 [...] 591 runtime permissions: 592 android.permission.ACCESS_FINE_LOCATION: granted=true, flags=[ GRANTED_BY_DEFAULT ] 593``` 594 595### Permission restricted components 596 597As [publicly documented](https://developer.android.com/guide/topics/permissions/overview#permission_enforcement) 598it is possible to restrict starting an activity/binding to a service by using permission. 599 600It is a common pattern to 601 602- define a permission in the platform as `signature` 603- protect a service in an app by this permission using the `android:permission` attribute of the 604 `<service>` tag 605 606Then it is guaranteed that only the system can bind to such service. This is used for services 607that provide extensions to platform functionality, such as auto-fill services, print services, and 608accessibility services. 609 610This does not work for app-op or runtime permissions as the way to check these permissions is 611more complex than install time permissions. 612 613#### End-to-end A service only the system can bind to 614 615Make sure to set the `android:permission` flag for this service. As developers can forget this it is 616a good habit to check this before binding to the service. This makes sure that the services are 617implemented correctly and no random app can bind to the service. 618 619The result is that the permission is granted only to the system. It is not granted to the service's 620package, but this has no negative side-effects. 621 622##### Permission definition 623 624frameworks/base/core/res/AndroidManifest.xml: 625 626```xml 627<manifest> 628[...] 629 <permission android:name="android.permission.BIND_MY_SERVICE" 630 android:label="@string/permlab_bindMyService" 631 android:description="@string/permdesc_bindMyService" 632 android:protectionLevel="signature" /> 633[...] 634</manifest> 635``` 636 637##### Service definition 638 639Manifest of the service providing the functionality: 640 641```xml 642<manifest> 643 <service android:name="com.my.ServiceImpl" 644 android:permission="android.permission.BIND_MY_SERVICE"> 645 <!-- add an intent filter so that the system can find this package --> 646 <intent-filter> 647 <action android:name="android.my.Service" /> 648 </intent-filter> 649 </service> 650</manifest> 651``` 652 653##### System server code binding to service 654 655```kotlin 656val serviceConnections = mutableListOf<ServiceConnection>() 657 658val potentialServices = context.packageManager.queryIntentServicesAsUser( 659 Intent("android.my.Service"), GET_SERVICES or GET_META_DATA, userId) 660 661for (val ri in potentialServices) { 662 val serviceComponent = ComponentName(ri.serviceInfo.packageName, ri.serviceInfo.name) 663 664 if (android.Manifest.permission.BIND_MY_SERVICE != ri.serviceInfo.permission) { 665 Slog.w(TAG, "$serviceComponent is not protected by " + 666 "${android.Manifest.permission.BIND_MY_SERVICE}") 667 continue 668 } 669 670 val newConnection = object : ServiceConnection { 671 ... 672 } 673 674 val wasBound = context.bindServiceAsUser(Intent().setComponent(serviceComponent), 675 serviceConnection, BIND_AUTO_CREATE, UserHandle.of(userId)) 676 if (wasBound) { 677 serviceConnections.add(newConnection) 678 } 679} 680``` 681 682## Permissions for system apps 683 684System apps need to integrate deeper with the system than regular apps. Hence they need to be 685able to call APIs not available to other apps. This is implemented by granting permissions to 686these system apps and then enforcing the permissions in the API similar to other [install time 687permissions](#checking-a-permission). 688 689System apps are not different from regular apps, but the protection levels (e.g. 690[privileged](#privileged-permissions), [preinstalled](#preinstalled-permissions)) mentioned in this 691section are more commonly used by system apps. 692 693### Multiple permission levels 694 695It is possible to assign multiple protection levels to a permission. Very common combinations are 696for example adding `signature` to all permissions to make sure the platform signed apps can be 697granted the permission, e.g. `privileged|signature`. 698 699The permission will be granted if the app qualifies for _any_ of the permission levels. 700 701### App-op permissions 702 703> See [App-ops](../app/AppOps.md). 704 705App-op permissions are user-switchable permissions that are not runtime permissions. This should 706be used for permissions that are really only meant to be ever granted to a very small amount of 707apps. Traditionally granting these permissions is intentionally very heavy weight so that the 708user really needs to understand the use case. For example one use case is the 709`INTERACT_ACROSS_PROFILES` permission that allows apps of different users within the same 710[profile group](../os/Users.md#profile-group) to interact. Of course this is breaking a very basic 711security container and hence should only ever be granted with a lot of care. 712 713**Warning:** Most app-op permissions follow this logic, but most of them also have exceptions 714and special behavior. Hence this section is a guideline, not a rule. 715 716#### Defining an app-op permission 717 718Only the platform can reasonably define an app-op permission. The permission is defined in the 719platforms manifest using the `appop` protection level 720 721```xml 722<manifest package="android"> 723 <permission android:name="android.permission.MY_APPOP_PERMISSION" 724 android:protectionLevel="appop|signature" /> 725</manifest> 726``` 727 728Almost always the protection level is app-op | something else, like 729[signature](#signature-permissions) (in the case above) or [privileged](#privileged-permissions). 730 731#### Checking an app-op permission 732 733The `PermissionChecker` utility can check app-op permissions with the [same syntax as runtime 734permissions](#checking-a-runtime-permission). 735 736The permission checker internally follows this flow 737 738```kotlin 739class PermissionChecker { 740 fun checkCallingPermission(context: Context, permission: String) { 741 if (isAppOpPermission(permission)) { 742 val appopOfPermission = AppOpsManager.permissionToOp(permission) 743 if (appopOfPermission == null) { 744 // not platform defined 745 return PERMISSION_DENIED 746 } 747 748 val appopMode = appOpsManager.noteOp(appopOfPermission) 749 when (appopMode) { 750 AppOpsManager.MODE_ALLOWED -> return PERMISSION_GRANTED 751 AppOpsManager.MODE_IGNORED -> return PERMISSION_DENIED 752 AppOpsManager.MODE_DEFAULT -> { 753 if (context.checkPermission(uid, permission) == GRANTED) { 754 return PERMISSION_GRANTED 755 } else { 756 return PERMISSION_DENIED 757 } 758 } 759 } 760 } else { 761 return PERMISSION_DENIED 762 } 763 } 764} 765``` 766 767#### Granting an app-op permission 768 769The permission's grant state is only considered if the app-op's mode is `MODE_DEFAULT`. This 770allows to have default grants while still being overridden by the app-op. 771 772The permission is then granted by setting the app-op mode. This is usually done via dedicated APIs 773for each use cases. Similarly whether and how an app can request the permission is different for 774each app-op permission. 775 776When implementing a new app-op permission, make sure to set the app-op mode using `AppOpsManager 777.setUidMode` to make sure the permission is granted on the uid as this is the security domain. 778 779During development app-ops can be grated to app via the `appops set` shell command. E.g. 780 781``` 782adb shell appops set 10187 INTERACT_ACROSS_PROFILES allow 783``` 784 785sets the `INTERACT_ACROSS_PROFILES` app-op for uid 10187 to allow thereby granting apps in this 786uid the ability to interact across profiles. 787 788##### UI 789 790Most UIs for app-op permissions are in the "Special app access" section of the settings app. 791 792In most cases the permission should only be granted with the user's explicit agreement, usually by 793allowing the app to directly open the "Special app access" page for this permission and app. 794 795To repeat: this is a guideline for app-op permissions and there are many exceptions. 796 797### Signature permissions 798 799Only apps signed with the defining app's certificate will be granted the permission. This is 800used to restrict APIs to apps of the same developer. 801 802This is frequently used to restrict permissions defined by the platform to apps also signed with 803the platform's certificate. As this is a very tight restriction this is recommended for 804permissions that are only used by apps built out of AOSP which are signed with the platform 805certificate. 806 807Please note that OEMs sign their platform them self. I.e. OEMs can implement new apps using these 808permissions. It is unlikely that 3rd party apps will be able to use APIs protected by signature 809permissions as they are usually not signed with the platform certificate. 810 811Such permissions are defined and checked like an install time permission. 812 813### Preinstalled permissions 814 815This means that the app has to be pre-installed. There is no restriction what apps are pre-installed 816on a particular device install there. Hence it can be really any app including 3rd party apps. 817 818Hence this permission level is discouraged unless there are 819[further restrictions](#restricted-by-tests). 820 821Such permissions are defined and checked like an install time permission. 822 823### Privileged permissions 824 825This means that the app has to be pre-installed and in the `system/priv` directory in the 826filesystem. There is no restriction what apps are in this directory on a particular device 827install there. Hence it can be really any app including 3rd party apps. 828 829An app is only ever granted privileged permissions requested by the pre-installed apk. I.e. 830privileged permissions added in updates will never be granted. 831 832Hence this permission level is discouraged unless there are 833[further restrictions](#restricted-by-tests). 834 835Such permissions are defined and checked like an install time permission. 836 837#### Restricted by tests 838 839As all apps that might get preinstalled or privilidged permissions need to be pre-installed and new 840images need to pass compliance tests it is possible to use a test to whitelist the apps that can 841request the permission. 842 843Example of such a test: 844```kotlin 845/* Add new whitelisted packages to this list */ 846private val whitelistedPkgs = listOf("my.whitelisted.package") 847 848@Test 849fun onlySomeAppsAreAllowedToHavePermissionGranted() { 850 assertThat(whitelistedPkgs).containsAllIn( 851 context.packageManager.getInstalledPackages(MATCH_ALL) 852 .filter { pkg -> 853 context.checkPermission(android.Manifest.permission.MY_PRIVILEGED_PERMISSION, -1, 854 pkg.applicationInfo.uid) == PERMISSION_GRANTED 855 /* The permission is defined by the system and hence granted to it */ 856 }.filter { pkg -> pkg.applicationInfo.uid != SYSTEM_UID } 857 .map { it.packageName } 858 ) 859} 860``` 861 862#### Whitelist 863 864As mentioned above it is not suggested, but still common practice to install 3rd party apps as 865privilidged. To verify and restrict which privilidged permissions those apps get granted all 866privilidged permissions need to be explicitly whitelisted in a file `/etc`. 867 868```xml 869<permissions> 870 <privapp-permissions package="my.privileged.package"> 871 <!-- allow the app to request a permission --> 872 <permission name="android.permission.MY_PRIVILEGED_PERMISSION"/> 873 874 <!-- Even though the app requests the permission, do not grant it --> 875 <deny-permission name="android.permission.MY_OTHER_PRIVILEGED_PERMISSION"/> 876 </privapp-permissions> 877</permissions> 878``` 879 880If the pre-installed apk of app requests a privileged permission that is not mentioned in any 881whitelist or that is not denied the system will refuse to boot. As mentioned above privileged 882permissions added in updates to the pre-installed app will never be granted. 883 884### Limited permissions 885 886E.g. installer, wellbeing, documenter, etc... This allows the system to restrict the permission to a 887well defined app or set of apps. It is possible to add new types in `PackageManagerService`. 888 889Which apps qualify for such a permission level is flexible and custom for each such level. Usually 890they refer to a single or small set of apps, usually - but not always - apps defined in AOSP. 891 892These permissions are defined and checked like an install time permission. 893 894### Development permissions 895 896> Not recommended 897 898By adding the `development` protection level to any permissions the permission can be granted via 899the `pm grant` shell command. This appears to be useful for development and testing, but it is very 900highly discouraged. Any user can grant them permanently via adb, hence adding this tag removes 901all guarantees the permission might otherwise provide. 902 903### Other protection levels 904 905There are other levels (such as `runtime`) but they are for special purposes on should not be 906used by platform developers. 907