3.1、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.
应用程序沙箱不依赖于用于构建应用程序的技术。尤其是 Dalvik 虚拟机不是一个安全边界,任何应用程序可以运行本地代码(请参阅 Android NDK )。所有类型的应用程序 —— Java ,本地和混合类型的 —— 被沙箱以同样的方式以及彼此具有相同安全性保护着。
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 ( .apk 文件)必须使用由他们的开发者持有的证书的私钥签署。此证书用于标识应用程序的作者。该证书并不 需要由证书颁发机构签署 ; 这是完全允许的,典型情况下, Android 应用程序使用自签名证书。 Android 证书的目的是区分应用程序的作者。这允许系统来允许或拒绝应用程序访问签名级别的权限 ,并授予或拒绝另一个应用程序申请的请求给予相同的 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 用户 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
标识 来 允许任何其它的 包去读写这个文件。 当设置这些标志的时候,这些文件仍然是由你的应用程序拥有的,但是它的全局读取和/或写入权限被设置为全局,所以任何其他应用程序可以看到它。
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 应用程序没有与之关联的缺省权限,意味着它不能干任何影响用户体验或对设备上的任何数据造成不利影响事情。为了使用被设备保护的功能,您必须在您的 AndroidManifest.xml 中包含一个或多个你的应用需要的 <uses-permission> 标签。
For example, an application that needs to monitor incoming SMS messages would specify:
比如说,一个应用程序需要监听接收到的短消息,可以像下面这样做:
<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.
很多时候,请求权限失败将导致 SecurityException 被抛出到应用程序。但是,这不能保证一定会发生。例如, sendBroadcast(Intent) 作为数据被传递到每个 Receiver ,该方法调用之后返回,所以如果有权限失败你将不会收到一个异常。但是,在几乎所有情况下,一个失败的权限将被打印到系统日志。
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.
然而,在一个普通的用户情况下 ( 比如当应用从 Google Play 商店上安装 ) ,如果用户没有赋予应用所请求的权限,一个应用不能被安装。所以你一般不需要担心造成丢失权限导致的运行失败,因为该应用程序被安装意味着你的应用程序已经获得其所需的权限。
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:
你的程序的运行过程中在一些地方特定的权限可能被强制执行:
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 。因为现有的应用程序假定访问这些 API 是免费提供的, Android 的可能应用这些新的权限请求到应用程序的清单,以避免破坏新平台版本的应用程序。 Android 根据 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 级别 4 加入限制访问共享存储空间。如果您 targetSdkVersion 为 3 或更低,此权限在新版本的 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.
要注意的是,如果发生这种情况,您的应用程序, Google Play 上您的应用程序列表将显示这些所需的权限,即使您的应用程序可能无法真正需要他们。
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 文档看到每个版本添加的哪些权限 。
To enforce your own permissions, you must first declare them in your AndroidManifest.xml using one or more <permission> tags.
要执行你自己的权限,必须首先在你的 AndroidManifest.xml 中 使用一个或多个 <permission> 标签声明它们。
For example, an application that wants to control who can start one of its activities could declare a permission for this operation as follows:
例如,要控制谁可以启动它的 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.
<protectionLevel> 属性是必需的,告诉系统用户是如何被告知应用程序需要的权限,或者谁被允许持有该权限,链接的文档中有详细的说明
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.
<permissionGroup> 属性是可选的,并且只用于帮助系统显示权限给用户。你通常会希望将其设置为一个标准的系统组(列表在 android.Manifest.permission_group )或更罕见的情况下给一个自己定义的。优先使用现有的组,因为这简化了显示给用户的使用权限的用户界面。
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 是 permission 应该提供的。它们的字符串资源能够在它们显示 permission 列表的时候 ( android:label ) 或者显示一个 permission 的详情的时候 ( android:description ) 显示给用户。标签应尽量短,用几句话描述 permission 所保护的关键部分。描述应该是一两句描述了允许权限持有人能做什么。我们的描述约定是两句话,第一描述权限,第二个警告用户:如果这个权限被授予一个应用程序被会发生什么样不好的事情。
Here is an example of a label and description for the CALL_PHONE permission:
下面是 CALL_PHONE 权限的一个 label 和 description 的例子:
<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:
你可以从设置中或者使用 shell 命令的 adb shell pm list permissions 查看 应用程序所具有的权限 。如果要从设置中查看:进入设置 > 应用程序,选择一个应用程序,然后向下滚动以查看该应用程序使用的权限。对于开发人员, adb "-S" 选项 显示权限形式类似于下面这样 :
$ adb shell pm list permissions -sAll
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...
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() and 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() and 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> 标签 ) 将限制谁能够发送广播到相关的 receiver 。这个权限检查将在 Context.sendBroadcast() 方法返回之后进行 , 随 后 系统试图将提交的广播 发送到给定的Receiver。 其结果是,一个权限异常不会被抛回给调用者 ; 它只是无法发送 Intent 。以同样的方式,使用权限可以传递给 Context.registerReceiver() 方法来控制谁谁能够广播以编程方式注册的 Receiver 。另外一种方式,权限可以在当做参数传递给 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 中的数据。 (Content provider 有一个非常重要的额外的安全技巧称为 URI 的权限。这将在后面介绍 ) 不像其他的组件一样,有两个不同的属性可以设置: android:readPermission 限制谁能从 Provider 中读取数据; android:writePermission 限制谁能往 Provider 中写入数据;请注意,如果一个 Provider 同时具有读和写权限的保护,只拿着写权限并不意味着你可以从 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.
除了 执行谁可以发送 Intent 到注册的 BroadcastReceiver (如上所述)之外,您也可以发送广播时指定必需的权限。通过调用 Context.sendBroadcast() 与 permission 字符串,为了接受你的广播,程序必须具有相应的权限才可以。
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.
注意, Receiver 和 Broadcast 必须具有相同的权限。 当这一切发生的时候,这两个权限检查必须通过意图传递给相关的目标。
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.
任意细粒度的权限可以在调用任何一个服务执行。这是 Context.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) 来找出特定的包是否已授予特定权限。
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 可能希望保护自己的读取和写入权限,而其直接的用户还需要手工指定 URI 到对他们进行操作的其他应用程序。一个典型的例子是邮件应用程序的附件。访问邮件应该得到权限的保护,因为这是敏感的用户数据。但是,如果 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.
解决这个问题是的方案是每个 URI 权限:启动一个 Activity 或返回一个结果到一个 Activity 的时候,调用者可以设置 Intent.FLAG_GRANT_READ_URI_PERMISSION 和 / 或 Intent.FLAG_GRANT_WRITE_URI_PERMISSION 。这将授予接收 Activity 权限访问特定数据的 URI 的意图,不管它是否有访问 ContentProvider 中对应的 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.
确实授予细粒度的 URI 的权限,但是,需要和 Content Provide 合作拿到这些 URI 。强烈建议 Content Provider 实现这种方案,并通过支持它的 android : grantUriPermissions 属性或 <grant-uri-permissions> 标签定义出来。
More information can be found in the Context.grantUriPermission() , Context.revokeUriPermission() , and Context.checkUriPermission() methods.
更多信息可以在 Context.grantUriPermission() , Context.revokeUriPermission() 和 Context.checkUriPermission() 方法找到。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步