Android Google官方文档解析之——System Permissions

时间:2022-06-30 04:17:12

  Android is a privilege-separated operating system, in which each application runs with a distinct system identity (Linux user ID and group ID). 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 operations that a particular process can perform, and per-URI permissions for granting ad hoc access to specific pieces of data.
  This document describes how application developers can use the security features provided by Android. A more general Android Security Overview is provided in the Android Open Source Project.
  Android是一个分隔权限的操作系统,每一个应用程序在一个独特的系统标识(Linux 用户ID和群组ID)下运行。系统的部分也也被分隔成明显的身份。Linux因此将应用程序彼此和系统相互孤立开来。

  Android细粒度的安全特性通过"许可"机制提供,强制限制某一个进程可以执行的特殊操作,每一个URI权限授予给特别的数据片。

  这个文档描述了应用程序开发者如何使用Android提供的安全特性。更一般的Android安全综述在Android开源项目中提供。

Security Architecture安全架构
  A central design point of the Android security architecture is that no application, by default, has permission to perform any operations that would adversely impact other applications, the operating system, or the user. This includes reading or writing the user's private data (such as contacts or emails), reading or writing another application's files, performing network access, keeping the device awake, and so on.
  Android安全架构有一个中心的设计要点就是一般来说没有应用程序有权限来执行任何对其他应用程序、操作系统或是用户的不利操作。这包括读或写用户的*数据(例如联系人或邮件),读或写其他应用程序的文件,执行网络访问,保持设备在唤起状态,等等。
  Because each Android application operates in a process sandbox, applications must explicitly share resources and data. They do this by declaring the permissions they need for additional capabilities not provided by the basic sandbox. Applications statically declare the permissions they require, and the Android system prompts the user for consent at the time the application is installed. Android has no mechanism for granting permissions dynamically (at run-time) because it complicates the user experience to the detriment of security.
  因为每一个Android应用程序操作在一个进程砂箱中,应用程序必须明确的分享资源和数据。他们通过定义运行程序的基础砂箱并没有提供的额外能力的许可来做到。应用程序静态的定义了他们需要的许可,并且Android系统在安装的时候会提示用户这些权限信息。
  The application sandbox does not depend on the technology used to build an application. In particular the Dalvik VM is not a security boundary, and any app can run native code (see the Android NDK). All types of applications — Java, native, and hybrid — are sandboxed in the same way and have the same degree of security from each other.
  应用程序砂箱并不依赖于用于构造一个 应用程序的技术。尤其是Dalik虚拟机不是一个安全边界,任何应用都可以运行本地代码(请查看Andorid NDK).所有应用程序的类型-Java型,本地型,混合型-同样的都是砂箱的,彼此之间都有相同的安全程度。

Application Signing应用程序签名

  All APKs (.apk files) must be signed with a certificate whose private key is held by their developer. This certificate identifies the author of the application. The certificate does not need to be signed by a certificate authority; it is perfectly allowable, and typical, for Android applications to use self-signed certificates. The purpose of certificates in Android is to distinguish application authors. This allows the system to grant or deny applications access to signature-level permissions and to grant or deny an application's request to be given the same Linux identity as another application.
  所有的APKs(.apk文件)必须用一个由开发者私有的秘钥所对应的证书所签名。这个证书定义了应用程序的作者。证书并不需要被认证授权中心签名;它是为Android应用程序完美典型的自签名授权。在Android中证书的作用是区分应用程序作者。这允许系统授予或拒绝应用程序访问签名等级许可还有授予或取消一个应用程序的请求被作为其他应用程序赋予相同的Linux身份。

User IDs and File Access用户ID和文件访问

  At install time, Android gives each package a distinct Linux user ID. The identity remains constant for the duration of the package's life on that device. 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.
  在安装的时候,Android给每一个一个安装包一个明确的Linux用户ID。在设备上这个标识在整个包生命周期内保持不变。在不同的设备上,同一个包也许有不同的UID;要紧的是每一个包在一个给定的设备上都有一个明确的UID。
  Because security enforcement happens at the process level, the code of any two packages cannot normally run in the same process, since they need to run as different Linux users. You can use the sharedUserId attribute in the AndroidManifest.xml's manifest tag of each package to have them assigned the same user ID. By doing this, for purposes of security the two packages are then treated as being the same application, with the same user ID and file permissions. Note that in order to retain security, only two applications signed with the same signature (and requesting the same sharedUserId) will be given the same user ID.
  因为安全实施发生在进程级别上,任意两个包的代码需要作为不同的Linux用户运行,所以他们不能正常的在同一个进程中运行。你可以在每个包的AndroidManifest.xml的“manifest”标签中使用“sharedUserId”属性来给他们分配相同的用户ID。通过这样做,出于安全目的这两个包将被当做是拥有相同的用户ID和文件许可的同一个应用。既然为了保留安全性,只有两个应用被签有相同的签名(并且请求相同的sharedUserId)才能被赋予相同的用户ID。
  Any data stored by an application will be assigned that application's user ID, and not normally accessible to other packages. When creating a new file with getSharedPreferences(String, int), openFileOutput(String, int), or openOrCreateDatabase(String, int, SQLiteDatabase.CursorFactory), you can use the MODE_WORLD_READABLE and/or MODE_WORLD_WRITEABLE flags to allow any other package to read/write the file. When setting these flags, the file is still owned by your application, but its global read and/or write permissions have been set appropriately so any other application can see it.
  任何被应用程序存储的数据将会被应用程序的用户ID签名,并且通常说来不会被其他包所得的。当创建了一个新文件通过 getSharedPreferences(String, int), openFileOutput(String, int), 或者openOrCreateDatabase(String, int, SQLiteDatabase.CursorFactory)方法,你可以使用”MODE_WORLD_READABLE“或者“MODE_WORLD_WRITEABLE”标签来运行任何其他包来读写这个文件。当设置那些标签的时候,文件仍然被你的应用程序拥有,但是他的全局读写权限已经被设置成全局适用的,所以对其他应用程序来说都是可见的。

Using Permissions

  A basic Android application has no permissions associated with it by default, meaning it cannot do anything that would adversely impact the user experience or 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 would specify:
  一个基础Android应用程序没有默认的关联权限,意图是不能做任何对用户体验或是设备上的数据产生不利的影响的事。利用设备的受保护的特性,你必须在你的AndroidManifest.xml文件中包含一个或更多的<uses-permission>标签来定义你的应用程序需要的权限。
  例如,一个应用程序需要管理收到的短消息应当指定:

<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 are granted to it by the package installer, based on checks against the signatures of the applications declaring those permissions and/or interaction with the user. No checks with the user are done while an application is running; the app is either granted a particular permission when installed, and can use that feature as desired, or the permission is not granted and any attempt to use the feature fails without 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 is being delivered to each receiver, after the method call has returned, so you will not receive an exception if there are permission failures. In almost all cases, however, a permission failure will be printed to the system log.
  终于一个许可失败将会导致一个”SecurityExcepton“异常被返回给应用程序。然而,这也不能被保证在每一处都会发生。例如”sendBroadcast(Intent)“方法检查权限因为数据将被分发到每一个接收者,在方法调用返回后,如果权限请求失败你将不会接收到一个异常信息。然而,在大部分情况下一个请求权限失败的信息将会在系统日志中打印出来。
  However, in a normal user situation (such as when the app is installed from Google Play Store), an app cannot be installed if the user does not grant the app each of the requested permissions. So you generally don't need to worry about runtime failures caused by missing permissions because the mere fact that the app is installed at all means that your app has been granted its desired permissions.

  然而,在一个正常的用户情况下(比如说当app是从Google Play Store中安装的),一个app如何用户没有授予这个app的每一项请求的权限将不能被安装。所以你一般来说不必要担心由缺少权限引起的运行时失败因为单纯的事实是如果你的应用被安装成功那么意味着你的app已经被授予了它需要的权限。
  The permissions provided by the Android system can be found at Manifest.permission. Any application may also define and enforce its own permissions, so this is not a comprehensive list of all possible permissions.
  权限被Android系统提供,它能在”Manifest.permission“中找到。任意的应用程序也能定义然后强制它自己的权限,所以这里没有一个综合性所有可能的权限列表。

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

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

特定的权限可以被执行在你的程序操作的任何一个地方:

  • 在调用进系统的时候,阻止应用程序执行某些功能。
  • 当启动一个Activity的时候,阻止应用程序启动其他程序的Activity。
  • 发送和接收广播通知的时候,控制谁能接收到你的广播或是谁能给你发送广播。
  • 当访问和操作某个content provider的时候
  • 绑定或是开启一个service的时候

  Caution: Over time, new restrictions may be added to the platform such that, in order to use certain APIs, your app must request a permission that it previously did not need. Because existing apps assume access to those APIs is freely available, Android may apply the new permission request to the app's manifest to avoid breaking the app on the new platform version. Android makes the decision as to whether an app might need the permission based on the value provided for the targetSdkVersion attribute. If the value is lower than the version in which the permission was added, then Android adds the permission.
  警告:超时,新的限制条件可能要被添加到平台中这样,为了用确定的APIs,你的app必须请求一个之前并没有的权限。因为目前app假定访问那些APIs是*可用的,Android或许会为了避免破坏新平台版本的app,给app的清单申请新的权限请求。Android做出决定一个app是否需要权限,基于提供targetSdkVersion属性值的权限。如果版本值低于权限被添加的版本那么Android会添加这个权限。
  For example, the WRITE_EXTERNAL_STORAGE permission was added in API level 4 to restrict access to the shared storage space. If your targetSdkVersion is 3 or lower, this permission is added to your app on newer versions of Android.
  例如,“WRITE_EXTERNAL_STORAGE”权限是在API level 4的时候限制访问共享存储空间。如果你的targetSdkVersion是3或是更低,这个权限在较新的Android版本中会被添加进你的app中。
  Beware that if this happens to your app, your app listing on Google Play will show these required permissions even though your app might not actually require them.
  注意如果这发生在你的app上,你在Google Play中的app列表将会显示那些所需要的权限,即便你的应用也许实际上没有需要。
  To avoid this and remove the default permissions you don't need, always update your targetSdkVersion to be as high as possible. You can see which permissions were added with each release in the Build.VERSION_CODES documentation.
  为避免这些发生,删掉默认你不需要的权限,总是尽可能更新你的targetSdkVersion为最新的版本.你可以在Build.VERSION_CODES文档中查看每次发布的时候有哪些权限被添加。

Declaring and Enforcing Permissions声明和施行权限

  To enforce your own permissions, you must first declare them in your AndroidManifest.xml using one or more <permission> tags.
For example, an application that wants to control who can start one of its activities could declare a permission for this operation as follows:
  为了施行你自己的权限,你必须一开始就在你的AndroidManifest.xml文件中用一个或多个<permission>标签来声明。
例如,一个应用程序想要控制谁能启动它的Activity可以为这个操作像下面一样声明一个权限:

<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 the user is to be informed of applications requiring the permission, or who is allowed to hold that permission, as described in the linked documentation.
The <permissionGroup> attribute is optional, and only used to help the system display permissions to the user. You will usually want to set this to either a standard system group (listed in android.Manifest.permission_group) or in more rare cases to one defined by yourself. It is preferred to use an existing group, as this simplifies the permission UI shown to the user.

  <protectionLevel>属性是必须的,它告诉系统用户如何知道需要这个权限,或者谁被允许拥有这个权限,就像这个链接文档中说的一样。
<permissionGroup>属性是可选的,只用于帮助系统给用户展示权限信息。你将通常把这个这只成一个标准的系统群组组(在android.Manifest.permission_group中列出的)或是少见的一个你自己定义的群组。更宁愿使用一个已经存在的群组,作为给用户展示的权限UI的简化。
  Note that both a label and description should be supplied for the permission. These are string resources that can be displayed to the user when they are viewing a list of permissions (android:label) or details on a single permission ( android:description). The label should be short, a few words describing the key piece of functionality the permission is protecting. The description should be a couple sentences describing what the permission allows a holder to do. Our convention for the description is two sentences, the first describing the permission, the second warning the user of what bad things can happen if an application is granted the permission.
  Here is an example of a label and description for the CALL_PHONE permission:
  既然一个标签和描述应该提供给权限。当被以列表形式展示时,权限信息(android:label)或是一个简单权限的详细信息(android:description)会有字符串资源展示给用户。标签应该很短只有很少的描述字,几句话就描述了功能,权限是受保护的。描述应该是一段话描述了权限允许持有者能做什么。我们的对描述的约定是两句话,第一句描述权限,第二句警示使用者如果应用程序被授予了该权限会有声明不好的事情发生。
  这里有一个CALL_PHONE权限的标签和描述的例子:

<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 the Settings app and the shell command adb shell pm list permissions. To use the Settings app, go to Settings > Applications. Pick an app and scroll down to see the permissions that the app uses. For developers, the adb '-s' option displays the permissions in a form similar to how the user will see them:
  你可以通过你的app设置还有adb shell命令行的pm命令列出权限列表的方式来查看当前系统定义的权限。使用app设置,进入Setting->Application。选择一个应用向下滑来查看这个应用使用的权限。对于开发者来说,adb”-s“选项展示权限在一种用户将看到的这种方式来展示权限:

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

Enforcing Permissions in AndroidManifest.xml在AndroidManifest.xml中施行权限

  High-level permissions restricting access to entire components of the system or application can be applied through your AndroidManifest.xml. All that this requires is including an android:permission attribute on the desired component, naming the permission that will be used to control access to it.
  高等级的权限约束进入系统的全部组件或是可以通过AndroidManifest.xml文件实施的应用程序。这所需要的是在所需要的组件上包含一个”android:permission“属性,给权限命名将被用于控制对其组件的访问。
  Activity permissions (applied to the <activity> tag) restrict who can start the associated activity. The permission is checked during Context.startActivity() and Activity.startActivityForResult(); if the caller does not have the required permission then SecurityException is thrown from the call.
  Activity权限(适用于<activity>标签)限制了谁能启动所关联的Activity。这个权限在”Context.startActivity()“还有”Activity.startActivityForResult()“期间检查;如果调用者没有需要的权限那么SecurityException异常将从调用者返回。
  Service permissions (applied to the <service> tag) restrict who can start or bind to the associated service. The permission is checked during Context.startService(), Context.stopService() and Context.bindService(); if the caller does not have the required permission then SecurityException is thrown from the call.
  Service权限(适用于<service>标签)限制了谁能启动或是绑定到所关联的service上。这个权限将会在Context.startService(),Context.stopService()还有Context.bindService()期间被检查;如果调用者没有需要的权限那么SecurityException异常将从调用者返回。
  BroadcastReceiver permissions (applied to the <receiver> tag) restrict who can send broadcasts to the associated receiver. The permission is checked after Context.sendBroadcast() returns, as the system tries to deliver the submitted broadcast to the given receiver. As a result, a permission failure will not result in an exception being thrown back to the caller; it will just not deliver the intent. In the same way, a permission can be supplied to Context.registerReceiver() to control who can broadcast to a programmatically registered receiver. Going the other way, a permission can be supplied when calling Context.sendBroadcast() to restrict which BroadcastReceiver objects are allowed to receive the broadcast (see below).
  BroadcastReceiver权限(适用于<receiver>标签)限制了谁能发送广播到所关联的接收者。这个权限将会在Conext.sendBroadcast()方法返回之后检查,随着系统尝试分发提交的广播给给定的接收者。结果,权限失败将不会作为一个异常结果返回给调用者;它将不仅分发intent。同样的,一个权限能被提供给Context.registerReceiver来控制谁能给以程序方式注册的接受者发送广播。另一方面来说,一个权限能被提供,当调用Context.sendBroadcast()方法来限制哪一个BroadcastReceiver对象允许接收广播(见下文)。
  ContentProvider permissions (applied to the <provider> tag) restrict who can access the data in a ContentProvider. (Content providers have an important additional security facility available to them called URI permissions which is described later.) Unlike the other components, there are two separate permission attributes you can set: android:readPermission restricts who can read from the provider, and android:writePermission restricts who can write to it. Note that if a provider is protected with both a read and write permission, holding only the write permission does not mean you can read from a provider. The permissions are checked when you first retrieve a provider (if you don't have either permission, a SecurityException will be thrown), and as you perform operations on the provider. Using ContentResolver.query() requires holding the read permission; using ContentResolver.insert(), ContentResolver.update(), ContentResolver.delete() requires the write permission. In all of these cases, not holding the required permission results in a SecurityException being thrown from the call.
  ContentProvider权限(适用于<provider>标签)限制了谁能在ContentProvider中使用数据。(Conent providers 有一个很重要的额外安全设施,他们在URI Permission中可用将在后面提到。)不像其他组件,有两个你可以设置的分隔开的组件属性:”android:readPermission“限制谁可用从provider中读数据,还有”android:writePermission“限制谁可用往provide中写数据。既然如果一个provider提供读和写的权限保护,只有些权限并不意味着你可以从provider中读取数据。当你第一次检索一个provider(如果你没有其中任何一个权限,SecurityException异常将会被抛出)这个权限将会被检查,随着你在该provider中执行操作。使用ConentResolver.query()方法需要持有读权限;使用ContentResolver.insert(),ConentResolver.update(),ConentResolver.delete()需要写权限。在所有那些情况下,没有持有所需的权限调用者都会收到一个SecurityException异常。

Other Permission Enforcement 其他的权限实施

  Arbitrarily(武断的,专横的,反复无常的) fine-grained permissions can be enforced at any call into a service. This is accomplished with the Context.checkCallingPermission() method. Call with a desired permission string and it will return an integer indicating whether that permission has been granted to the current calling process. Note that this can only 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 way given to another process.
  杂乱的细粒度权限可以被执行在任意进入服务的调用。使用Conext.checkCallingPermission()方法是完美的。调用一个需要的权限字符串然后它会返回一个表明是否这个权限已经被当前调用进程过的整型值。注意这只能当你在执行一个从其他进程进入的调用时被使用,通常通过设备发布的IDL接口或是在给其他进程的其他方法。
  There are a number of other useful ways to check permissions. If you have the 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 another application, you can use the direct PackageManager method PackageManager.checkPermission(String, String) to find out whether that particular package has been granted a specific permission.
  还有一些有用的方法来检查权限。如果你有其他进程的pid,你可以用Context的这个方法Context.checkPermission(String,int,int)来检查那个进程的pid的权限。如果你有其他应用程序的包名,你可以直接用PackageManager的方法PackageManager.checkPermission(String,String)方法来找到是否独特的包已经被授予了特定的权限。

URI Permissions URI权限

  The standard permission system described so far is often not sufficient(足够的) when used with content providers. A content provider may want to protect itself with read and write permissions, while its direct clients also 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 mail should 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 viewer will not have permission to open the attachment since it has no reason to hold a permission to access all e-mail.
  到目前为止系统描述的标准权限是经常不足的,当以content provider的方式使用的时候。content provider想要保护他自己通过读写权限,然而它的直接客户也需要为他们传递特殊的URIs到其他的应用来操作。一个典型的例子是一个邮件应用程序中的附件。进入邮件应该被权限保护,因为有用户的敏感数据。然后如果一个指向一个图形附件的URI被给到一个图片查看器,那么图片查看器将没有权限来打开附件,因为它没有理由持有访问所有邮件的权限。
  The solution to this problem is per-URI permissions: when starting an activity or returning a result to an activity, the caller can set Intent.FLAG_GRANT_READ_URI_PERMISSION and/or Intent.FLAG_GRANT_WRITE_URI_PERMISSION. This grants the receiving activity permission access the specific data URI in the Intent, regardless of whether it has any permission to access data in the content provider corresponding to the Intent.
  解决这个问题的办法是per-URI权限:当启动一个Activity或是给一个Activity返回一个结果的时候,调用者可以设置intent.FLAG_GRANT_READ_URI_PERMISSION或是Intent.FLAG_GRANT_WRITE_URI_PERMISSION。这授予接受Activity访问intent中的特定数据URI的权限,不管是否有访问content provider相对应的Intent的权限。

  This mechanism(机制,原理,途径) allows a common capability-style model where user interaction (opening an attachment, selecting a contact from a list, etc) drives ad-hoc(专门) granting of fine-grained permission. This can be a key facility for reducing the permissions needed by applications to only those directly related to their behavior.
  这种机制允许一个通用的用户交互(打开一个附件,从列表中查询联系,等等)的能力模型驱使专门的细粒度权限授予。这也能是一种关键设施为减少应用所需要的权限到仅仅直接关联到他们行为的权限。
  The granting of fine-grained URI permissions does, however, require some cooperation with the content provider holding those URIs. It is strongly recommended that content providers implement this facility, and declare that they support it through the android:grantUriPermissions attribute or <grant-uri-permissions> tag.

  More information can be found in the Context.grantUriPermission(), Context.revokeUriPermission(), and Context.checkUriPermission() methods.
  细粒度的URI权限授予需要content provider持有那些URIs来的协作。强烈推荐content provider实现这些设施,然后通过"android:grantUriPermissions"标签或是"<grant-uri-permission>"标签定义他们他们支持它。
  更多信息可以查看Context.grantUriPermission(), Context.revokeUriPermission(), 还有 Context.checkUriPermission()方法。