The current repo belongs to Closed status, and some functions are restricted. For details, please refer to the description of repo status
4 Star 0 Fork 1

OpenHarmony / security_permission
Closed

Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
Clone or Download
contribute
Sync branch
Cancel
Notice: Creating folder will generate an empty file .keep, because not support in Git
Loading...
README
Apache-2.0

security_permission

Introduction

In OpenHarmony, apps and system services run in independent sandboxes. Both processes and data are isolated from each other to protect the security of app data. However, services or apps running in the sandboxes provide some APIs to implement specific functionalities. To access these APIs across processes, apps in other sandboxes need the required permissions, which are granted and managed based on a permission management mechanism.

  • App permission management provides a mechanism for defining permissions, allowing system services and apps to define new permissions for their sensitive APIs. To access these APIs, other apps need the required permissions.

  • App permission management also allows apps to request permissions that are defined by the system or other apps. Upon obtaining the permissions, apps can access the sensitive APIs provided by the system or other apps.

  • In addition, app permission management allows users to view and manage the permission granting status.

Figure 1 App permission management architecture

App permission management provides permission management for the application framework subsystem and provides APIs for apps to request permissions and query the permission granting status. Currently, app permission management is available for mini, small and standard systems.

  • Mini system: refers to the system running on the devices whose memory is greater than or equal to 128 KiB and that are equipped with MCU processors such as ARM Cortex-M and 32-bit RISC-V. This system provides multiple lightweight network protocols and graphics frameworks, and a wide range of read/write components for the IoT bus. Typical products include connection modules, sensors, and wearables for smart home.
  • Small system: refers to the system running on the devices whose memory is greater than or equal to 1 MiB and that are equipped with app processors such as ARM Cortex-A. This system provides higher security capabilities, standard graphics frameworks, and video encoding and decoding capabilities. Typical products include smart home IP cameras, electronic cat eyes, and routers, and event data recorders (EDRs) for smart travel.
  • Standard system: refers to the system running on the devices whose memory is greater than or equal to 128 MiB and that are equipped with app processors such as ARM Cortex-A. This system provides a complete application framework supporting the enhanced interaction, 3D GPU, hardware composer, diverse components, and rich animations. This system applies to high-end refrigerator displays.

Directory Structure

/base/security/permission_lite
├── frameworks                         # Frameworks
│   └── permission_standard            # Permission management framework for the standard system
├── interfaces                         # APIs
│   ├── innerkits                      # Internal APIs
│   │   ├── permission_lite            # Internal permission management APIs for the mini and small systems
│   │   └── permission_standard        # Internal permission management APIs for the standard system
│   └── kits                           # External APIs
│       ├── permission_lite            # External permission management APIs for the mini and small systems
│       └── permission_standard        # External permission management APIs for the standard system
└── services                           # Services
    ├── permission_lite                # Permission management services for the mini and small systems
    └── permission_standard            # Permission management services for the standard system

Constraints

  • Currently, C++ APIs are available only for local permission management in the standard system. Distributed permission management APIs are not provided yet.

Usage

Available APIs

App permission management for a standard system: provides basic permission management and verification capabilities for the application framework subsystem of a standard system and is unavailable for third-party apps. The following table describes the available APIs.

API

Description

int VerifyPermission(const string& bundleName, const string& permissionName, int userId)

Checks whether a specified app has been granted the given permission.

bool CanRequestPermission(const string& bundleName, const string& permissionName, int userId)

Checks whether a specified app can request the given permission through a pop-up window.

int GrantUserGrantedPermission(const string& bundleName, const string& permissionName, int userId)

Grants a specified user_grant permission to the given app.

int GrantSystemGrantedPermission(const string& bundleName, const string& permissionName)

Grants a specified system_grant permission to the given app.

int RevokeUserGrantedPermission(const string& bundleName, const string& permissionName, int userId)

Revokes a specified user_grant permission from the given app.

int RevokeSystemGrantedPermission(const string& bundleName, const string& permissionName)

Revokes a specified system_grant permission from the given app.

int AddUserGrantedReqPermissions(const string& bundleName, const std::vector<string>& permList, int userId)

Adds user_grant permissions requested by a specified app.

int AddSystemGrantedReqPermissions(const string& bundleName, const std::vector<string>& permList)

Adds system_grant permissions requested by a specified app.

int RemoveUserGrantedReqPermissions(const string& bundleName, int userId)

Removes all the user_grant permissions requested by a specified app.

int RemoveSystemGrantedReqPermissions(const string& bundleName)

Removes all the system_grant permissions requested by a specified app.

int AddDefPermissions(const std::vector<PermissionDef>& permList)

Adds the permissions defined by the app.

int GetDefPermission(const string& permissionName, PermissionDef& permissionDefResult)

Obtains the definition of the permission with a specified name.

App permission management for a mini or small system: The following table lists the available APIs, which can be called only by system apps and services.

API

Description

int CheckPermission(int uid, const char *permissionName)

Checks whether the app with a specified UID has the permission to access system service APIs.

int CheckSelfPermission(const char *permissionName)

Checks whether the caller has the permission to access system service APIs.

int QueryPermission(const char *identifier, PermissionSaved **permissions, int *permNum)

Queries all permissions requested by the app and checks whether the requested permissions have been granted.

int GrantPermission(const char *identifier, const char *permName)

Grants a specified permission to the app.

int RevokePermission(const char *identifier, const char *permName)

Revokes a specified permission from the app.

int GrantRuntimePermission(int uid, const char *permissionName)

Grants a specified runtime permission to the app.

int RevokeRuntimePermission(int uid, const char *permissionName)

Revokes a specified runtime permission from the app.

int UpdatePermissionFlags(const char *identifier, const char *permissionName, const int flags)

Updates the flags for the specified permission to the app.

IPC authentication for a mini or small system

API

Description

int GetCommunicationStrategy(RegParams params, PolicyTrans **policies, unsigned int *policyNum)

Obtains the access policies of a service API.

int IsCommunicationAllowed(AuthParams params)

Checks whether a process has the permission to access an API of another process.

Usage Guidelines

App permission management for a standard system

The APIs provided are for internal use and unavailable to developers. During the authentication, you only need to call VerifyPermission.

  1. Determine the app UID and the name of the permission to verify.
  2. Obtain the app bundle name based on the app UID.
  3. Obtain the user ID of the app based on the UID.
  4. Pass the permission name, bundle name, and user ID to VerifyPermission(string permissionName, string bundleName, int userId).
  5. Obtain the verification result.

App permission management for a mini or small system

This section uses the bundle manager as an example to describe the app permission development. Before starting development, you need to declare the required sensitive permissions in the config.json file. During app installation, the BMS calls APIs of the app permission management component to check whether the required permissions have been granted. If yes, the installation proceeds; if not, the installation fails.

  1. Declare the required permission (ohos.permission.INSTALL_BUNDLE) in the config.json file.

    {
      ...
      "module": {
          "package": "ohos.demo.kitframework",
          "deviceType": [
              "phone", "tv","tablet", "car","smartWatch","sportsWatch","smartCamera", "smartVision"
          ],
          "reqPermissions": [{
            // Declare the ohos.permission.INSTALL_BUNDLE permission required for installing the app.
            "name": "ohos.permission.INSTALL_BUNDLE",
            "reason": "install bundle",
            "usedScene": {
              "ability": [
                "KitFramework"
                ],
              "when": "always"
            }
          },
          {
            "name": "ohos.permission.LISTEN_BUNDLE_CHANGE",
            "reason": "install bundle",
            "usedScene": {
              "ability": [
                "KitFramework"
                ],
              "when": "always"
            }
          },
          {
            "name": "ohos.permission.GET_BUNDLE_INFO",
            "reason": "install bundle",
            "usedScene": {
              "ability": [
                "KitFramework"
                ],
              "when": "always"
            }
          }
          ],
        ...
    }
  2. The BMS calls the corresponding API of the app permission management component (for example, the CheckPermission function with ohos.permission.INSTALL_BUNDLE as an input parameter) to check whether the BMS has the permission to install the app. If yes, the installation proceeds; if not, the installation fails.

    constexpr static char PERMISSION_INSTALL_BUNDLE[] = "ohos.permission.INSTALL_BUNDLE";
    
    bool Install(const char *hapPath, const InstallParam *installParam, InstallerCallback installerCallback)
    {
        if ((hapPath == nullptr) || (installerCallback == nullptr) || (installParam == nullptr)) {
            HILOG_ERROR(HILOG_MODULE_APP, "BundleManager install failed due to nullptr parameters");
            return false;
        }
        // Check whether the ohos.permission.INSTALL_BUNDLE permission has been granted.
        if (CheckPermission(0, static_cast<const char *>(PERMISSION_INSTALL_BUNDLE)) != GRANTED) {
            HILOG_ERROR(HILOG_MODULE_APP, "BundleManager install failed due to permission denied");
            return false;  // App installation fails.
        }
        // App installation process
        ...
    }

IPC authentication for a mini or small system

This section uses the bundle manager as an example to describe how to configure access policies for APIs provided by the IPC authentication component. In this example, the service registered by BMS with Samgr is bundlems, and the feature registered for open APIs is BmsFeature.

  1. Configure access policies in the base/security/permission_lite/services/ipc_auth/include/policy_preset.h file. Access policies are classified into the following three types:

    1. RANGE: Processes with a specified range of UIDs can access BMS APIs. uidMin and uidMax must be specified.

    2. FIXED: Processes with specified UIDs can access BMS APIs. fixedUid must be specified, and a maximum of eight UIDs are allowed.

    3. BUNDLENAME: An app with a specified bundleName can access BMS APIs.

    FeaturePolicy bmsFeature[] = {
        {
            "BmsFeature",
            {
                {
                    .type=FIXED,    // Processes with specified UIDs can access BMS APIs.
                    .fixedUid={2, 3, 8}
                },
                {
                    .type=RANGE,    // Processes with a specified range of UIDs can access BMS APIs.
                    .uidMin=100,
                    .uidMax=__INT_MAX__,
                },
            }
        },
        {
            "BmsInnerFeature",
            {
                {
                    .type=FIXED,     // Processes with specified UIDs can access BMS APIs.
                    .fixedUid={2, 3, 8}
                },
                {
                    .type=RANGE,
                    .uidMin=100,
                    .uidMax=999,
                },
            }
        },
    };
  2. Add the policies configured for the features in Step 1 to the global policy settings. You need to set the number of features.

    static PolicySetting g_presetPolicies[] = {
        {"permissionms", pmsFeature, 1},
        {"abilityms", amsFeature, 2},
        {"bundlems", bmsFeature, 2},  // Add the policies configured for the two features in [Step 1](#li15901515152517) to the global policy settings.
        {"dtbschedsrv", dmsFeature, 1},
        {"samgr", samgrFeature, 1},
        {"appspawn", appspawnFeature, 1},
        {"WMS", wmsFeature, 1},
        {"bundle_daemon", bdsFeature, 1},
    };
  3. Register the BmsFeature defined in Step 1 with Samgr.

    const char BMS_SERVICE[] = "bundlems";
    const char BMS_FEATURE[] = "BmsFeature";
    static void Init()
    {
        SamgrLite *sm = SAMGR_GetInstance();
        if (sm == nullptr) {
            return;
        }
        // Register the BmsFeature with Samgr.
        sm->RegisterFeature(BMS_SERVICE, reinterpret_cast<Feature *>(BundleMsFeature::GetInstance()));
        sm->RegisterFeatureApi(BMS_SERVICE, BMS_FEATURE,
            GetBmsFeatureApi(reinterpret_cast<Feature *>(BundleMsFeature::GetInstance())));
        HILOG_DEBUG(HILOG_MODULE_APP, "BundleMS feature start success");
    }
    APP_FEATURE_INIT(Init);

When you register a service with Samgr, Samgr calls the GetCommunicationStrategy function of the IPC authentication component to obtain access policies of the service. When other services or apps access this service through IPC, Samgr calls the IsCommunicationAllowed function of the IPC authentication component to check whether the services or apps have the access permission.

Repositories Involved

security security_permission

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS

About

Application permission management and IPC authentication | 提供应用权限管理及IPC通信鉴权能力 expand collapse
C and 2 more languages
Apache-2.0
Cancel

Releases

No release

Contributors

All

Activities

Load More
can not load any more
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/openharmony/security_permission.git
git@gitee.com:openharmony/security_permission.git
openharmony
security_permission
security_permission
master

Search

344bd9b3 5694891 D2dac590 5694891