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.
Android是一个特权分隔的操作系统，每个app都会带着系统唯一标识(Linux UID和GID)来运行. 系统的某些部分也被分隔成唯一的标识. 从而Linux系统可以把每个app与其他app隔离开来.
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.
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.
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 app的操作都在进程沙盒里进行，app必须显式的去共享资源和数据. 通过声明在它们需要的并且在基本沙盒里没有提供的额外的权限. app需要静态的声明它们需要的权限，并且Android系统会在app安装时给用户提示来取得用户的同意. 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.
app沙盒并不依赖于构建一个app的技术. 在指定的DVM中并没有安全边界，任何app都可以运行本地代码. 所有类型的app如：纯Java的、纯native的，或者混合的，互相都会以同样的方式、统一的安全制度存在于沙盒中.
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.
所有的apk文件都必须要用开发者的私有证书来签名. 这个证书都唯一标识着此app的开发者. 证书不需要再用开发者的证书进行再度签名；它已经被完全的许可了，Android app使用证书自己签名的证书. 而此证书的目的就是来区别app的开发者. 这样允许系统授权或拒绝某一app可以访问签名级别的权限，还可以授权或拒绝app请求被赋予linux唯一标识的权限
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 UID. 这个设备上的软件包的标识会在其生命周期中保持不变. 而在另一个不同的设备，同一个软件包会有不同的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用户身份来运行(不同的UID). 你可以通过在每个软件包里的AndroidManifest.xml 文件中设置sharedUserId 标签的属性值来请求系统赋予相同的UID. 如果这样做，安全机制会把这样两个app会被当做是同一个app，拥有相同的UID和文件权限. 请注意为了保持(记住)它们的安全权限，这两个app必须是使用相同的签名才能这么做
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 theMODE_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.
任何被app保存的数据都被赋予该app的UID，不能够正常地访问其他的软件包. 当使用以下方法创建了一个新文件时：getSharedPreferences(String, int), openFileOutput(String, int), or openOrCreateDatabase(String, int, SQLiteDatabase.CursorFactory)，你可以使用MODE_WORLD_READABLE 或者和 MODE_WORLD_WRITEABLE标志来允许其他软件包读或写这个文件. 当设置了这些标志时，文件仍然是属于你的app，但被适当的设置了全局读或写的权限就可以让其他app看见了.
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.
一个基本你的Android app默认情况下是不跟任何权限关联的，这样就意味着它不能做任何事情而严重的影响了用户体验和不能读或写设备上的任何数据了. 为了利用设备的保护功能，你必须要在 AndroidManifest.xml 文件中包含一个到多个的<uses-permission> 标签来声明你app中需要的权限.
For example, an application that needs to monitor incoming SMS messages would specify:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
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.
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.
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.
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.
当访问或操作一个 content provider 时
· Binding to or starting a 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.
注意：未来的时间里，新的限制条件可能会被加入到平台之中，例如，为了能够使用将来的API，你的app必须要申请一些之前版本不需要的权限. 因为现在存在的app被假定可以大胆的访问那些API，Android在未来可能会引用到一些新的权限到app的menifest文件中，来避免打断一些app在新版本的平台上运行. Android可以根据targetSdkVersion 的属性值来决定一个app是否需要这些权限. 如果此属性值比平台版本低且加入了某些权限，那么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.
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.
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_CODESdocumentation.
为了避免这个问题，一处你不需要的默认权限，总是将你的targetSdkVersion 尽可能的更新到最高. 并且你可以在一些release版本的文档中看到被新添加的权限.
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:
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 inandroid.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.
<permissionGroup> 属性是可选的，仅用来帮助系统来向用户展示权限. 通常情况你可以将这个值设置为标准的系统组或者更稀有的情况下可以使用自定义组. 如果只是简单的向用户展示一些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.
注意label和description两个属性标签在权限声明当中应该要提供的. 有一些string资源可以当用户在视察权限列表时来向用户展示，或者展示单个权限的详细形式时. Label属性应该要短一些，只需要该权限功能的几个关键词来描述即可. description 属性应该用成对的语句出现来描述该权限允许持有者做的工作. 我们的会约定description 属性会用两句话描述出来：第一句描述权限，第二句来警告用户如果授予了该权限会发生什么坏的事情.
Here is an example of a label and description for the CALL_PHONE permission:
<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:
$ adb shell pm list permissions -s
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
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.
高级的权限会限制app或者系统的整个组件的访问，这可以在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.
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.
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).
使用<receiver>标签来定义BroadcastReceiver 权限可以限谁能发送广播到接收者. 权限检查阶段是在调用 Context.sendBroadcast() 函数返回时；如果系统尝试发出一个广播到指定的接收者. 结果是系统不会再权限申请失败的情况下导致抛回异常到调用者；而是只是提交到intent. 在一些相同的情况下， 一些权限可以通过 Context.registerReceiver() 方法的调用来控制谁能接受此广播. 而另一种情况是：通过调用Context.sendBroadcast() 方法来限制允许哪些BroadcastReceiver对象可以接受一个广播.
ContentProvider permissions (applied to the <provider> tag) restrict who can access the data in aContentProvider. (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, andandroid: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. UsingContentResolver.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.
使用<provider>标签可以限制谁能访问ContentProvider的数据. (Content providers拥有一个很重要的附加权限限制机制，就是URI权限机制). 与其他组件不同的是，他分别拥有两个权限来限制读和写. 注意如果一个provider同时被读和写权限来限制就会被保护起来. 权限将在第一次获得 provider 的时候来检查(如果你也没有权限，那么SecurityException异常会抛出)，使用ContentResolver.query()来申请持有读权限，使用 ContentResolver.insert(),ContentResolver.update(), ContentResolver.delete()来申请持有写权限. 在这所有的情况中，如果没有权限的话会导致SecurityException异常会跑回到调用者
In addition to the permission enforcing who can send Intents to a registered BroadcastReceiver (as described above), you can also specify a required permission when sending a broadcast. By calling Context.sendBroadcast() with a permission string, you require that a receiver's application must hold that permission in order to receive your broadcast.
Note that both a receiver and a broadcaster can require a permission. When this happens, both permission checks must pass for the Intent to be delivered to the associated target.
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.
在任何调用到service时，任意一些有意的权限都可以被实施. 通过调用Context.checkCallingPermission()方法来完成. 被一个有期望权限的字符串调用，可以返回一个整型来致命是否权限被当前的进程被授予了. 注意当你从另一个进程执行的时候会被调用到，通常通过一个service的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.
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 providers是远远不够的. 一个content providers可能想要保护自己的读写权限，当它的客户端也需要指定一些URIs来让其他程序来操作. 一个典型的例子是邮件app 里的附件. 访问到邮件里是有一些权限来保护的， 因为这是用户的敏感数据. 但是， 如果一个图片附件的URI被给了image viewer，那image viewer将会得不到权限来打来图片附件，因为他并未持有访问邮件的权限.
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.
为了解决这个每个URI权限的问题： 当启动一个activity时来返回一个结果给一个activity， 调用者可以设置Intent.FLAG_GRANT_READ_URI_PERMISSION and/or Intent.FLAG_GRANT_WRITE_URI_PERMISSION.权限.这样就授予了接收activity的权限来访问指定uri携带的数据. 而无视是否有任何权限来访问 content provider相应的权限了.
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.
这种机制允许在与用户交互的地方使用一个通用的风格属性模型 (打开一个附件，从联系人列表中选择一个联系人等) 来驱动点对点的细粒度授权. 这就可以成为减少那些只与app行为有直接相关的一些权限的关键.
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.