Security and Permissions

In this document

  1. Security Architecture
  2. Application Signing
  3. User IDs and File Access
  4. Using Permissions
  5. Declaring and Enforcing Permissions
    1. ...in AndroidManifest.xml
    2. ...when Sending Broadcasts
    3. Other Permission Enforcement
  6. URI Permissions

Android is a privilege-separated operating system, in which eachapplication runs with a distinct system identity (Linux user ID and groupID). Parts of the system are also separated into distinct identities.Linux thereby isolates applications from each other and from the system.

Additional finer-grained security features are provided through a"permission" mechanism that enforces restrictions on the specific operationsthat a particular process can perform, and per-URI permissions for grantingad-hoc access to specific pieces of data.

Security Architecture

A central design point of the Android security architecture is that noapplication, by default, has permission to perform any operations that wouldadversely impact other applications, the operating system, or the user. Thisincludes reading or writing the user's private data (such as contacts ore-mails), reading or writing another application's files, performingnetwork access, keeping the device awake, etc.

Because the kernel sandboxes applications from each other, applicationsmust explicitly share resources and data. They do this by declaring thepermissions they need for additional capabilities not provided bythe basic sandbox. Applications statically declare the permissions theyrequire, and the Android system prompts the user for consent at the time theapplication is installed. Android has no mechanism for granting permissionsdynamically (at run-time) because it complicates the user experience to thedetriment of security.

The kernel is solely responsible for sandboxing applications from eachother. In particular the Dalvik VM is not a security boundary, and any appcan run native code (see the Android NDK).All types of applications — Java, native, and hybrid — aresandboxed in the same way and have the same degree of security from eachother.

Application Signing

All Android applications (.apk files) must be signed with a certificatewhose private key is held by their developer. This certificate identifiesthe author of the application. The certificate does not need to besigned by a certificate authority: it is perfectly allowable, and typical,for Android applications to use self-signed certificates. The purpose ofcertificates in Android is to distinguish application authors. This allowsthe system to grant or deny applications access to signature-levelpermissions and to grant or deny an application's request to be giventhe same Linux identity as another application.

User IDs and File Access

At install time, Android gives each package a distinct Linux user ID. Theidentity remains constant for the duration of the package's life on thatdevice. On a different device, the same package may have a different UID;what matters is that each package has a distinct UID on a given device.

Because security enforcement happens at theprocess level, the code of any two packages can not normallyrun in the same process, since they need to run as different Linux users.You can use the sharedUserId attribute in theAndroidManifest.xml'smanifest tag of each package tohave them assigned the same user ID. By doing this, for purposes of securitythe two packages are then treated as being the same application, with the sameuser ID and file permissions. Note that in order to retain security, only two applicationssigned with the same signature (and requesting the same sharedUserId) willbe given the same user ID.

Any data stored by an application will be assigned that application's userID, and not normally accessible to other packages. When creating a new filewith getSharedPreferences(String, int),openFileOutput(String, int), oropenOrCreateDatabase(String, int, SQLiteDatabase.CursorFactory),you can use theMODE_WORLD_READABLE and/orMODE_WORLD_WRITEABLE flags to allow any otherpackage to read/write the file. When setting these flags, the file is stillowned by your application, but its global read and/or write permissions havebeen set appropriately so any other application can see it.

Using Permissions

A basic Android application has no permissions associated with it,meaning it can not do anything that would adversely impact the user experienceor any data on the device. To make use of protected features of the device,you must include in your AndroidManifest.xml one or more<uses-permission>tags declaring the permissions that your application needs.

For example, an application that needs to monitor incoming SMS messages wouldspecify:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"  package="com.android.app.myapp" >  <uses-permission android:name="android.permission.RECEIVE_SMS" />  ...</manifest>

At application install time, permissions requested by the application aregranted to it by the package installer, based on checks against thesignatures of the applications declaring those permissions and/or interactionwith the user. No checks with the userare done while an application is running: it either was granted a particularpermission when installed, and can use that feature as desired, or thepermission was not granted and any attempt to use the feature will failwithout prompting the user.

Often times a permission failure will result in a SecurityException being thrown back to the application. However,this is not guaranteed to occur everywhere. For example, the sendBroadcast(Intent) method checks permissions as data isbeing delivered to each receiver, after the method call has returned, so youwill not receive an exception if there are permission failures. In almost allcases, however, a permission failure will be printed to the system log.

The permissions provided by the Android system can be found at Manifest.permission. Any application may also define and enforce itsown permissions, so this is not a comprehensive list of all possiblepermissions.

A particular permission may be enforced at a number of places during yourprogram's operation:

  • At the time of a call into the system, to prevent an application fromexecuting certain functions.
  • When starting an activity, to prevent applications from launchingactivities of other applications.
  • Both sending and receiving broadcasts, to control who can receiveyour broadcast or who can send a broadcast to you.
  • When accessing and operating on a content provider.
  • Binding to or starting a service.

Declaring and Enforcing Permissions

To enforce your own permissions, you must first declare them in yourAndroidManifest.xml using one or more<permission>tags.

For example, an application that wants to control who can start oneof its activities could declare a permission for this operation as follows:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"  package="com.me.app.myapp" >  <permission android:name="com.me.app.myapp.permission.DEADLY_ACTIVITY"    android:label="@string/permlab_deadlyActivity"    android:description="@string/permdesc_deadlyActivity"    android:permissionGroup="android.permission-group.COST_MONEY"    android:protectionLevel="dangerous" />  ...</manifest>

The <protectionLevel> attribute is required, telling the system how theuser is to be informed of applications requiring the permission, or who isallowed to hold that permission, as described in the linked documentation.

The <permissionGroup> attribute is optional, and only used to help the system displaypermissions to the user. You will usually want to set this to either a standardsystem group (listed in android.Manifest.permission_group) or in more rare cases to one defined byyourself. It is preferred to use an existing group, as this simplifies thepermission UI shown to the user.

Note that both a label and description should be supplied for thepermission. These are string resources that can be displayed to the user whenthey are viewing a list of permissions(android:label)or details on a single permission (android:description).The label should be short, a few wordsdescribing the key piece of functionality the permission is protecting. Thedescription should be a couple sentences describing what the permission allowsa holder to do. Our convention for the description is two sentences, the firstdescribing the permission, the second warning the user of what bad thingscan happen if an application is granted the permission.

Here is an example of a label and description for the CALL_PHONEpermission:

  <string name="permlab_callPhone">directly call phone numbers</string>  <string name="permdesc_callPhone">Allows the application to call    phone numbers without your intervention. Malicious applications may    cause unexpected calls on your phone bill. Note that this does not    allow the application to call emergency numbers.</string>

You can look at the permissions currently defined in the system with theshell command adb shell pm list permissions. In particular,the '-s' option displays the permissions in a form roughly similar to how theuser will see them:

$ adb shell pm list permissions -s   All Permissions:Network communication: view Wi-Fi state, create Bluetooth connections, fullInternet access, view network stateYour location: access extra location provider commands, fine (GPS) location,mock location sources for testing, coarse (network-based) locationServices that cost you money: send SMS messages, directly call phone numbers...

Enforcing Permissions in AndroidManifest.xml

High-level permissions restricting access to entire components of thesystem or application can be applied through yourAndroidManifest.xml. All that this requires is including an android:permission attribute on the desiredcomponent, naming the permission that will be used to control access toit.

Activity permissions(applied to the<activity> tag)restrict who can start the associatedactivity. The permission is checked duringContext.startActivity() andActivity.startActivityForResult();if the caller does not havethe required permission then SecurityException is thrownfrom the call.

Service permissions(applied to the<service> tag)restrict who can start or bind to theassociated service. The permission is checked duringContext.startService(),Context.stopService() andContext.bindService();if the caller does not havethe required permission then SecurityException is thrownfrom the call.

BroadcastReceiver permissions(applied to the<receiver> tag)restrict who can send broadcasts to the associated receiver.The permission is checked afterContext.sendBroadcast() returns,as the system triesto deliver the submitted broadcast to the given receiver. As a result, apermission failure will not result in an exception being thrown back to thecaller; it will just not deliver the intent. In the same way, a permissioncan be supplied toContext.registerReceiver()to control who can broadcast to a programmatically registered receiver.Going the other way, a permission can be supplied when callingContext.sendBroadcast()to restrict which BroadcastReceiver objects are allowed to receive the broadcast (seebelow).

ContentProvider permissions(applied to the<provider> tag)restrict who can access the data ina ContentProvider. (Content providers have an importantadditional security facility available to them calledURI permissions which is described later.)Unlike the other components,there are two separate permission attributes you can set:android:readPermission restricts whocan read from the provider, andandroid:writePermission restrictswho can write to it. Note that if a provider is protected with both a readand write permission, holding only the write permission does not meanyou can read from a provider. The permissions are checked when you firstretrieve a provider (if you don't have either permission, a SecurityExceptionwill be thrown), and as you perform operations on the provider. UsingContentResolver.query() requiresholding the read permission; usingContentResolver.insert(),ContentResolver.update(),ContentResolver.delete()requires the write permission.In all of these cases, not holding the required permission results in aSecurityException being thrown from the call.

Enforcing Permissions when Sending Broadcasts

In addition to the permission enforcing who can send Intents to aregistered BroadcastReceiver (as described above), youcan also specify a required permission when sending a broadcast. By calling Context.sendBroadcast() with apermission string, you require that a receiver's application must hold thatpermission in order to receive your broadcast.

Note that both a receiver and a broadcaster can require a permission. Whenthis happens, both permission checks must pass for the Intent to be deliveredto the associated target.

Other Permission Enforcement

Arbitrarily fine-grained permissions can be enforced at any call into aservice. This is accomplished with the Context.checkCallingPermission()method. Call with a desiredpermission string and it will return an integer indicating whether thatpermission has been granted to the current calling process. Note that this canonly be used when you are executing a call coming in from another process,usually through an IDL interface published from a service or in some other waygiven to another process.

There are a number of other useful ways to check permissions. If you havethe pid of another process, you can use the Context method Context.checkPermission(String, int, int)to check a permission against that pid. If you have the package name of anotherapplication, you can use the direct PackageManager method PackageManager.checkPermission(String, String)to find out whether that particular package has been granted a specific permission.

URI Permissions

The standard permission system described so far is often not sufficientwhen used with content providers. A content provider may want toprotect itself with read and write permissions, while its direct clientsalso need to hand specific URIs to other applications for them to operate on.A typical example is attachments in a mail application. Access to the mailshould be protected by permissions, since this is sensitive user data. However,if a URI to an image attachment is given to an image viewer, that image viewerwill not have permission to open the attachment since it has no reason to holda permission to access all e-mail.

The solution to this problem is per-URI permissions: when starting anactivity or returning a result to an activity, the caller can setIntent.FLAG_GRANT_READ_URI_PERMISSION and/orIntent.FLAG_GRANT_WRITE_URI_PERMISSION. This grants the receiving activitypermission access the specific data URI in the Intent, regardless of whetherit has any permission to access data in the content provider correspondingto the Intent.

This mechanism allows a common capability-style model where user interaction(opening an attachment, selecting a contact from a list, etc) drives ad-hocgranting of fine-grained permission. This can be a key facility for reducingthe permissions needed by applications to only those directly related to theirbehavior.

The granting of fine-grained URI permissions does, however, require somecooperation with the content provider holding those URIs. It is stronglyrecommended that content providers implement this facility, and declare thatthey support it through theandroid:grantUriPermissions attribute or<grant-uri-permissions> tag.

More information can be found in theContext.grantUriPermission(),Context.revokeUriPermission(), andContext.checkUriPermission()methods.


更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. Android修改文件权限
  2. Android出现java.net.SocketException: P
  3. Android(安卓)Jetpack-Paging使用
  4. Android(安卓)HandlerThread
  5. Android: MediaScanner生成thumbnail的算
  6. android练习一之简易浏览器
  7. androdi 9.0 P版本 CTS 常见问题表格
  8. API 25 (Android(安卓)7.1.1 API) widget
  9. Android(安卓)Init Language
  10. android中的多媒体应用camera