System Permissions

Android is aprivilege-separatedoperating 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. Linuxtherebyisolates applications from each other and from the system.

Android是一个特权分隔的操作系统,每个app都会带着系统唯一标识(Linux UIDGID)来运行.系统的某些部分也被分隔成唯一的标识.从而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 grantingad hocaccess to specific pieces of data.

额外的会提供一个指纹验证的安全功能的权限机制,可以强制的限制在特殊的进程中进行特殊的操作,并且使用URI前缀权限机制可以对点对点进行授权访问一些特定的数据.

This document describes how application developers can use the security features provided by Android. A more generalAndroid Security Overviewis provided in the Android Open Source Project.

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安全架构设计的一个中心点是:默认情况下,任何app都不能拥有对其他app、操作系统,或者用户做任何操作的权限.包括读或写用户的私有数据(例如联系人或者邮件),读写其他app的文件,访问网络,保持设备唤醒等.

Because each Android application operates in a process sandbox, applications must explicitly share resources and data. They do this by declaring thepermissionsthey need for additional capabilities not provided by the basic sandbox. Applications statically declare the permissions they require, and the Android systempromptsthe user forconsentat 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 (seethe 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的,或者混合的,互相都会以同样的方式、统一的安全制度存在于沙盒中.

Application Signing

All APKs (.apkfiles) must be signed with a certificate whose private key is held by their developer. This certificate identifies the author of the application. The certificate doesnotneed 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 tosignature-level permissionsand to grant or deny an application'srequest to be given the same Linux identityas another application.

所有的apk文件都必须要用开发者的私有证书来签名.这个证书都唯一标识着此app的开发者.证书不需要再用开发者的证书进行再度签名;它已经被完全的许可了,Android app使用证书自己签名的证书.而此证书的目的就是来区别app的开发者.这样允许系统授权或拒绝某一app可以访问签名级别的权限,还可以授权或拒绝app请求被赋予linux唯一标识的权限

User IDs and File Access

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 theprocess 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 thesharedUserIdattribute in theAndroidManifest.xml'smanifesttag 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 withgetSharedPreferences(String, int),openFileOutput(String, int), oropenOrCreateDatabase(String, int, SQLiteDatabase.CursorFactory), you can use theMODE_WORLD_READABLEand/orMODE_WORLD_WRITEABLEflags 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保存的数据都被赋予该appUID,不能够正常地访问其他的软件包.当使用以下方法创建了一个新文件时:getSharedPreferences(String, int),openFileOutput(String, int), oropenOrCreateDatabase(String, int, SQLiteDatabase.CursorFactory)你可以使用MODE_WORLD_READABLE或者和MODE_WORLD_WRITEABLE标志来允许其他软件包读或写这个文件.当设置了这些标志时,文件仍然是属于你的app,但被适当的设置了全局读或写的权限就可以让其他app看见了.

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 yourAndroidManifest.xmlone 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:

<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.app.myapp">
<uses-permissionandroid: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.Nochecks 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.

app安装期间,app请求的权限会被软件包安装器来授予,它可以检查app的签名以及授予app所声明的想要和用户交互的一些权限.app运行期间则不会检查;app会在安装完成的时候被授予一些指定的权限,就能够按照期望的使用那些功能了,如果权限没有被授予而app试图获得那些功能就会失败.

Often times a permission failure will result in aSecurityExceptionbeing thrown backto the application. However, this is not guaranteed to occur everywhere. For example, thesendBroadcast(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.

通常几次的权限申请失败会导致SecurityException异常被抛回app.但是,会确保不会在任何地方发生,sendBroadcast(Intent)方法在数据被提交到每一个receiver时会检查其权限,当方法返回时,如果权限失败你将不会接到一个异常.几乎全部的情况都是这样,但是这样的权限失败信息会被打印到系统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.

然而,在用户正常使用的情况下,一个app是不会在被用户给每一个权限授权的情况下被安装到你的设备之中的.所以你可以不必担心因为失去某些权限而在运行时的产生的错误,因为实际上当你的app被安装在设备上的时候就意味着你的app已经被授予了它期望的权限了.

The permissions provided by the Android system can be found atManifest.permission.Any application may also define and enforce its own permissions, so this is not a comprehensive list of all possible permissions.

一些其他的app可能会定义一些自己的权限,所以这不是一个很完全的权限列表

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

一些特殊的权限可能在你程序操作期间会在一下几个地方被授予.

&middot;At the time of a call into the system, to prevent an application from executing certain functions.

在系统调用之时,来防止一个app执行某些确定的函数.

&middot;When starting an activity, to prevent applications from launching activities of other applications.

在启动一个activity之时,来防止app启动到其他appacitivity

&middot;Both sending and receiving broadcasts, to control who can receive your broadcast or who can send a broadcast to you.

在发送和接受广播之时,来控制广播的接收或者发送者

&middot;When accessing and operating on a content provider.

当访问或操作一个content provider

&middot;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 thetargetSdkVersionattribute. If the value is lower than the version in which the permission was added, then Android adds the permission.

注意:未来的时间里,新的限制条件可能会被加入到平台之中,例如,为了能够使用将来的API,你的app必须要申请一些之前版本不需要的权限.因为现在存在的app被假定可以大胆的访问那些APIAndroid在未来可能会引用到一些新的权限到appmenifest文件中,来避免打断一些app在新版本的平台上运行. Android可以根据targetSdkVersion的属性值来决定一个app是否需要这些权限.如果此属性值比平台版本低且加入了某些权限,那么Android会为了添加那些权限的.

For example, theWRITE_EXTERNAL_STORAGEpermission was added in API level 4 to restrict access to the shared storage space. If yourtargetSdkVersionis 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.

例如WRITE_EXTERNAL_STORAGE权限是在API等级为4的时候加入的,用来限制访问共享存储空间的权限.如果你的targetSdkVersion属性值为3或者更低,而这个权限是在一个较新的版本中被添加的.请注意这样的情况,你的app会在Google Play上列出一些请求的权限和一些甚至是你不需要的权限.

To avoid this and remove the default permissions you don't need, always update yourtargetSdkVersionto be as high as possible. You can see which permissions were added with each release in theBuild.VERSION_CODESdocumentation.

为了避免这个问题,一处你不需要的默认权限,总是将你的targetSdkVersion尽可能的更新到最高.并且你可以在一些release版本的文档中看到被新添加的权限.

Declaring and Enforcing Permissions

To enforceyour own permissions(自定义权限), you must first declare them in yourAndroidManifest.xmlusing one or more<permission>tags.

For example, an application that wants tocontrol who can start one of itsactivitiescould declare a permission for this operation as follows:

<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.me.app.myapp">
<permissionandroid: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.

<protectionLevel>属性是必要的,来告知系统用户应该怎样接到app请求权限的通知,或者谁将会持有那个权限

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 morerarecases 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.

注意labeldescription两个属性标签在权限声明当中应该要提供的.有一些string资源可以当用户在视察权限列表时来向用户展示,或者展示单个权限的详细形式时. Label属性应该要短一些,只需要该权限功能的几个关键词来描述即可. description属性应该用成对的语句出现来描述该权限允许持有者做的工作.我们的会约定description属性会用两句话描述出来:第一句描述权限,第二句来警告用户如果授予了该权限会发生什么坏的事情.

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

<stringname="permlab_callPhone">directly call phone numbers</string>
<stringname="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 commandadb 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, theadb '-s'option displays the permissionsin a form similar to how the user will see them:

$ adb shell pm list permissions-s
AllPermissions:

Networkcommunication:viewWi-Fistate,createBluetoothconnections,full
Internetaccess,view network state

Yourlocation:access extra location provider commands,fine(GPS)location,
mock location sources
fortesting,coarse(network-based)location

Servicesthat cost you money:send SMS messages,directly call phone numbers

...

Enforcing Permissions in AndroidManifest.xml

High-level permissions restricting access to entire components of the system or application can be applied through yourAndroidManifest.xml. All that this requires is including anandroid:permissionattribute on the desired component, naming the permission that will be used to control access to it.

高级的权限会限制app或者系统的整个组件的访问,这可以在AndroidManifest.xml件中提供.只需在需要的组件上包含android:permission属性,然后声明要使用访问控制权限的名称即可.

Activitypermissions (applied to the<activity>tag) restrict who can start the associated activity. The permission is checked duringContext.startActivity()andActivity.startActivityForResult(); if the caller does not have the required permission thenSecurityExceptionis thrown from the call.

使用<activity>标签来定义activity权限可以限制谁能启动它.权限检查阶段是在调用Context.startActivity()andActivity.startActivityForResult()函数时来检查的;如果调用者没有所需要的权限则会抛出SecurityException异常

Servicepermissions (applied to the<service>tag) restrict who can start or bind to the associated service. The permission is checked duringContext.startService(),Context.stopService()andContext.bindService(); if the caller does not have the required permission thenSecurityExceptionis thrown from the call.

使用<service>标签来定义Service权限可以限制谁能启动或者绑定它.权限检查阶段是在调用Context.startService(),Context.stopService()andContext.bindService()函数时来检查的;如果调用者没有所需要的权限则会抛出SecurityException异常

BroadcastReceiverpermissions (applied to the<receiver>tag) restrict who can send broadcasts to the associated receiver. The permission is checkedafterContext.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 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 (see below).

使用<receiver>标签来定义BroadcastReceiver权限可以限谁能发送广播到接收者.权限检查阶段是在调用Context.sendBroadcast()函数返回时;如果系统尝试发出一个广播到指定的接收者.结果是系统不会再权限申请失败的情况下导致抛回异常到调用者;而是只是提交到intent.在一些相同的情况下,一些权限可以通过Context.registerReceiver()方法的调用来控制谁能接受此广播.而另一种情况是:通过调用Context.sendBroadcast()方法来限制允许哪些BroadcastReceiver对象可以接受一个广播.

ContentProviderpermissions (applied to the<provider>tag) restrict who can access the data in aContentProvider. (Content providers have an important additional security facility available to them calledURI permissionswhich is described later.) Unlike the other components, there are two separate permission attributes you can set:android:readPermissionrestricts who can read from the provider, andandroid:writePermissionrestricts 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; usingContentResolver.insert(),ContentResolver.update(),ContentResolver.delete()requires the write permission. In all of these cases, not holding the required permission results in aSecurityExceptionbeing thrown from the call.

使用<provider>标签可以限制谁能访问ContentProvider的数据. (Content providers拥有一个很重要的附加权限限制机制,就是URI权限机制).与其他组件不同的是,他分别拥有两个权限来限制读和写.注意如果一个provider同时被读和写权限来限制就会被保护起来.权限将在第一次获得provider的时候来检查(如果你也没有权限,那么SecurityException异常会抛出),使用ContentResolver.query()来申请持有读权限,使用ContentResolver.insert(),ContentResolver.update(),ContentResolver.delete()来申请持有写权限.在这所有的情况中如果没有权限的话会导致SecurityException异常会跑回到调用者

Enforcing Permissions when Sending Broadcasts

In addition to the permission enforcing who can send Intents to a registeredBroadcastReceiver(as described above), you can also specify a required permission when sending a broadcast. By callingContext.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.

一些附加的权限可以限制谁能发送intent到已注册的BroadcastReceiver你也可以指定一个需要发送广播的权限.若你使用有权限的调用Context.sendBroadcast()方法,你需要接收者app必须得持有那个权限来接收广播

注意接收者和广播发送者都需要权限,双方的权限都必须检查通过才能提交intent到已关联的目标对象.

Other Permission Enforcement

Arbitrarily fine-grained permissions can be enforced at any call into a service. This is accomplished with theContext.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()方法来完成.被一个有期望权限的字符串调用,可以返回一个整型来致命是否权限被当前的进程被授予了.注意当你从另一个进程执行的时候会被调用到,通常通过一个serviceIDL借口来发布或者通过其他方式授予与其他的进程

There are a number of other useful ways to check permissions. If you have the pid of another process, you can use the Context methodContext.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 methodPackageManager.checkPermission(String, String)to find out whether that particular package has been granted a specific permission.

这里有几种有用的方式来检查权限.如果你有其他进程的pid,你可以使用ContextContext.checkPermission(String, int, int)方法来检查这个权限是否匹配.如果你有别的软件包的名字,你也可以用PackageManagerPackageManager.checkPermission(String, String)方法来查找指定的软件包是否被赋予了权限

URI Permissions

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 setIntent.FLAG_GRANT_READ_URI_PERMISSIONand/orIntent.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_PERMISSIONand/orIntent.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 theandroid:grantUriPermissionsattribute or<grant-uri-permissions>tag.

细粒度的URI授权模式,需要与持有在那些URIscontent provider合作,强烈建议那些content providers实现这个方案,并且使用android:grantUriPermissions属性或者<grant-uri-permissions>标签来声明.


更多相关文章

  1. ViewPager fragment android tab选项卡的使用
  2. Android官方文档翻译 三 1.1Creating an Android(安卓)Project
  3. Android使用NIO开发客户端
  4. android studio 问题整理
  5. [Android] AsyncTask的使用
  6. Android下拉列表使用方法
  7. android SpannableString使用详解
  8. ViewPager使用样例
  9. android 使用百度地图画轨迹

随机推荐

  1. Android 6.0中添加硬件访问服务
  2. Android学习-五布局之绝对布局(AbsoluteL
  3. Android帧布局实现霓虹灯的效果
  4. Android使用科大讯飞实现语音播报、语音
  5. 【Android】TextView倾斜文字
  6. android-logging-log4j - Logging with L
  7. android调用camera实现自定义照相
  8. android SD卡文件的读写(z)
  9. Android上通过gcc编译普通的C程序
  10. 分析android的usb-gadget