当前位置:   article > 正文

OpenHarmon3.2 一键安装系统应用_open harmony 3.2

open harmony 3.2

OpenHarmon3.2 一键安装系统应用

在上一篇OpenHarmony3.2 安装系统应用 中介绍了如何手动安装系统应用, 过程中读取签名指纹和安装, 权限配置文件的读写比较麻烦, 所以想到使用python脚本来实现.
但涉及到签名的部分还需手动配置, 详情请参考3.2安装系统应用第一章节

1. 使用示例

打开终端, 键入

# python install_sys_hap.py {hap_path}
python install_sys_hap.py C:\target.hap
  • 1
  • 2

在这里插入图片描述

2. 下载, 配置

脚本使用python实现, 主要功能点为: 解析hap包获取包名和权限列表; hap签名指纹的获取; 更新预原装配置文件, 除了第二点获取签名指纹, 其他两个功能都是简单的io流, 主要难点在hap签名指纹的获取, 看了下系统源码, 发现安全子系统有暴露相关能力, 所以采用编写二进制程序依赖该部件实现签名指纹获取. 目前提供OpenHarmony 3.2版本 arm32和arm64位, 如其他版本可能需要自己编译, 关键代码可参考第四节编译dev_kits

(20231018更新)脚本及依赖整合, 下载即可, 章节3章节4为源码实现, 可参考

链接: https://pan.baidu.com/s/1BvB5RgX2cTJZcWsJjQtw_g 提取码: yvdt 
  • 1
│  install_sys_hap.py
└─libs
    ├─arm64-v8a
    │      dev_kits
    │
    └─default
            dev_kits
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

3. 源码

将下面代码复制下来保存为 install_sys_hap.py

#!/usr/bin/env python
import json
import os
import sys
import time
import zipfile
import subprocess
from abc import abstractmethod

HDC = "hdc"

CONFIG_FILE = "module.json"
INSTALL_LIST = "install_list.json"
INSTALL_LIST_CAPABILITY = "install_list_capability.json"
INSTALL_LIST_PERMISSIONS = "install_list_permissions.json"


class AppInfo:

    def __init__(self, path_, bundle_name, permissions, app_signature: str):
        self.path_ = path_
        self.bundle_name_ = bundle_name
        self.permissions_ = permissions
        self.app_signature_ = app_signature
        self.hap_name_ = os.path.basename(path_)

    def __str__(self):
        return f"bundleName: {self.bundle_name_} permissions: {self.permissions_}"


class ReConfig:
    install_file = 0

    def __init__(self, path_: str, re_content_):
        self.path_ = path_
        self.re_content_ = re_content_

    @abstractmethod
    def check_exist(self, src: dict, key: AppInfo):
        pass

    @abstractmethod
    def re_config(self, src: dict, key: AppInfo):
        pass

    def start(self):
        if not os.path.exists(self.path_):
            print(f"target file{self.path_} is not exist")
            return
        try:
            self.install_file = open(self.path_, "r")
            content = self.install_file.read()
            json_dict = json.loads(content)
            if not self.check_exist(json_dict, self.re_content_):
                self.re_config(json_dict, self.re_content_)
                self.install_file.close()
                self.install_file = open(self.path_, "w")
                self.install_file.write(json.dumps(json_dict, indent=2))
        finally:
            self.install_file.close()


class ReConfigInstallList(ReConfig):

    def check_exist(self, src: dict, key: AppInfo):
        find_start = len("/system/app/")
        find_str = f"{key.bundle_name_}"
        for item in src["install_list"]:
            app_dir = str(item["app_dir"])
            if app_dir.find(find_str, find_start) != -1:
                return True
        return False

    def re_config(self, src: dict, key: AppInfo):
        content: list = src["install_list"]
        item = {
            "app_dir": f"/system/app/{key.bundle_name_}",
            "removable": False
        }
        print(f"write: {self.path_} to {json.dumps(item, indent=2)}")
        content.append(item)


class ReConfigCapability(ReConfig):

    def check_exist(self, src: dict, key: AppInfo):
        return False

    def re_config(self, src: dict, key: AppInfo):
        new_content = {
            "allowAppUsePrivilegeExtension": True,
            "app_signature": [
                f"{key.app_signature_}"
            ],
            "bundleName": f"{key.bundle_name_}",
            "keepAlive": False
        }

        content: list = src["install_list"]
        old_index: int = -1
        for index in range(len(content)):
            bdn: str = content.__getitem__(index)["bundleName"]
            if bdn == key.bundle_name_:
                old_index = index
                break
        if old_index != -1:
            print(f"remove old data {old_index}")
            del content[old_index]
        print(f"write: {self.path_} to {json.dumps(new_content, indent=2)}")
        content.append(new_content)


class ReConfigPermissions(ReConfigCapability):

    def re_config(self, content: list, key: AppInfo):
        if key.permissions_ is None or len(key.permissions_) == 0:
            return
        new_content = {
            "bundleName": f"{key.bundle_name_}",
            "app_signature": [
                f"{key.app_signature_}"
            ],
            "permissions": key.permissions_
        }
        old_index: int = -1
        for index in range(len(content)):
            bdn: str = content.__getitem__(index)["bundleName"]
            if bdn == key.bundle_name_:
                old_index = index
                break
        if old_index != -1:
            print(f"remove old data {old_index}")
            del content[old_index]
        print(f"write: {self.path_} to {json.dumps(new_content, indent=2)}")
        content.append(new_content)


def parse_hap(hap_path: str):
    print(f"parse_hap {hap_path}")
    if not os.path.exists(hap_path):
        print(f"hap file is not exists")
        return
    hap_zip = zipfile.ZipFile(hap_path, "r")
    hap_zip.namelist().index(CONFIG_FILE)
    config = hap_zip.open(CONFIG_FILE, mode="r")
    content = config.read()
    config.close()
    strc = content.decode("utf-8")
    cfg = json.loads(strc)
    bundle_name = cfg["app"]["bundleName"]
    permissions = cfg["module"].get("requestPermissions")
    return AppInfo(hap_path, bundle_name, permissions, "")


def pull_config_files():
    work_dir = fr"{os.getcwd()}\.install_list_{int(time.time())}"
    if not os.path.exists(work_dir):
        os.mkdir(work_dir)
    if not os.path.exists(work_dir):
        print("failed create work dir, task be stop")
        return None
    os.system(fr"{HDC} shell mount -o remount,rw /")
    os.system(fr"{HDC} file recv system/etc/app/install_list.json {work_dir}")
    os.system(fr"{HDC} file recv system/etc/app/install_list_capability.json {work_dir}")
    os.system(fr"{HDC} file recv system/etc/app/install_list_permissions.json {work_dir}")
    return work_dir


def merge_to_config_file(target_path: str, apps: AppInfo):
    ReConfigInstallList(fr"{target_path}/{INSTALL_LIST}", apps).start()
    ReConfigCapability(fr"{target_path}/{INSTALL_LIST_CAPABILITY}", apps).start()
    ReConfigPermissions(fr"{target_path}/{INSTALL_LIST_PERMISSIONS}", apps).start()


def push_to_device(target_path, app: AppInfo):
    os.system(fr"{HDC} shell mount -o remount,rw /")
    os.system(fr"{HDC} file file send {target_path}\{INSTALL_LIST} system/etc/app/")
    os.system(fr"{HDC} file file send {target_path}\{INSTALL_LIST_CAPABILITY} system/etc/app/")
    os.system(fr"{HDC} file file send {target_path}\{INSTALL_LIST_PERMISSIONS} system/etc/app/")
    os.system(fr"{HDC} shell rm -rf system/app/{app.bundle_name_}/*")
    os.system(fr"{HDC} shell mkdir system/app/{app.bundle_name_}")
    os.system(fr"{HDC} file send {app.path_} system/app/{app.bundle_name_}")
    os.system(fr"{HDC} shell rm -rf data/*")
    os.system(fr"{HDC} shell reboot")


def measure_hap_finger(app: AppInfo):
    cpu = subprocess.run(f"{HDC} shell param get const.product.cpu.abilist", shell=True, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE, text=True).stdout.strip()
    os.system(f"{HDC} shell mount -o remount,rw /")
    send_path = fr"{os.getcwd()}\libs\{cpu}\dev_kits"
    os.system(fr"{HDC} file send {send_path} bin/")
    os.system(f"{HDC} shell chmod a+x bin/dev_kits")
    os.system(fr"{HDC} shell mkdir system/app/{app.bundle_name_}")
    os.system(fr"{HDC} file send {app.path_} system/app/{app.bundle_name_}")
    result = subprocess.run(f"{HDC} shell dev_kits --fingerprint system/app/{app.bundle_name_}/{app.hap_name_}",
                            shell=True, stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE, text=True).stdout.strip()
    app.app_signature_ = result
    return app.app_signature_ is not None and len(app.app_signature_) != 0


def clear_cache(target_path):
    os.system(f"del /s /q {target_path}")


def start(target_hap: str):
    app = parse_hap(target_hap)
    if app is None:
        return
    measure_hap_finger(app)
    if len(app.app_signature_) == 0:
        app.app_signature_ = input("failed to measure hap finger, please input hap finger:")
    target_path = pull_config_files()
    if target_path is None:
        return
    merge_to_config_file(target_path, app)
    push_to_device(target_path, app)
    # clear(target_path)


if __name__ == '__main__':
    print(f"{sys.argv}")
    if len(sys.argv) < 2:
        print("miss params hapPath, call example: python install_sys_hap.py C:/app/default-signed.hap")
    start(sys.argv[1])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226

4. 手动编译dev_kits

dev_kits是个人为OH的开发工具, 此处只介绍hap指纹获取的关键部分, hap指纹功能依赖安全子系统appverify组件提供app验证暴露能力实现

  1. 链接security/appverify, 引入头文件
ohos_executable("dev_kits") {
    sources = ["dev_kits.cpp" ]
    include_dirs = [ "//base/security/appverify/interfaces/innerkits/appverify/include" ]
    deps = [ "//base/security/appverify/interfaces/innerkits/appverify:libhapverify" ]
    subsystem_name = "{subsystem_name}"
    part_name = "{part_name}"
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  1. cpp
#include <cstdint>
#include <cstdio>
#include "interfaces/hap_verify_result.h"
#include "interfaces/hap_verify.h"

int HapFingerExecute(int len, char **args, std::string &result)
{
    if (len <= 1) {
        result = "miss param hap_path";
        return -1;
    }
    OHOS::Security::Verify::HapVerifyResult verifyResult;
    const std::string hapPath = args[2];
    int32_t ret = OHOS::Security::Verify::HapVerify(hapPath, verifyResult);
    if (ret == 0) {
        result = verifyResult.GetProvisionInfo().fingerprint.c_str();
    } else {
        result = std::to_string(ret);
    }
    return ret;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/338168
推荐阅读
相关标签
  

闽ICP备14008679号