在 Ubuntu 24.04.1 LTS (WSL) 中使用 openssl 生成 keybox.xml

news/2024/12/18 13:51:34/

看到“生成 keybox.xml”,大概率都会联想到 PIF 和 Tricky Store。这里就不多解释它们的用途了。最近在网上看到生成非 AOSP keybox 的教程,在这里做一些补充,并将代码打包成一个 Python 脚本。

参考自:

  1. Idea 提供者:https://xdaforums.com/t/tee-hacking.4662185/page-21#post-89847987(如果打不开或者被重定向去另一个网页可能要刷新几遍才能正确打开这个网页) ,该原始 Idea 需要借助一个密码学工具网站;
  2. RSA 私钥转换:https://stackoverflow.com/questions/17733536/how-to-convert-a-private-key-to-an-rsa-private-key。

做出以下调整:

  1. 直接使用一站式脚本执行,自动利用 openssl 生成三个 PEM 文件,如果用于预检测的 openssl version 命令执行失败,自动尝试通过 sudo apt-get install libssl-dev 进行安装;
  2. 实现对新版 openssl 生成的 RSA 私钥进行识别,并从 PKCS8 转换为 PKCS1。

直接上 Python 代码,记得以 LF 形式保存换行符,并在 Ubuntu 24.04.1 LTS 中运行。

import os
try:os.chdir(os.path.abspath(os.path.dirname(__file__)))
except:pass
EXIT_SUCCESS = 0
EXIT_FAILURE = 1
EOF = (-1)
keyboxFormatter = """<?xml version="1.0"?>
<AndroidAttestation>
<NumberOfKeyboxes>1</NumberOfKeyboxes>
<Keybox DeviceID="YourDeviceID">
<Key algorithm="ecdsa">
<PrivateKey format="pem">
{0}</PrivateKey>
<CertificateChain>
<NumberOfCertificates>1</NumberOfCertificates>
<Certificate format="pem">
{1}</Certificate>
</CertificateChain>
</Key>
<Key algorithm="rsa">
<PrivateKey format="pem">
{2}</PrivateKey>
</Key>
</Keybox>
</AndroidAttestation>"""def execute(commandline:str) -> int|None:if isinstance(commandline, str):print("$ " + commandline)return os.system(commandline)else:return Nonedef handleOpenSSL(flag:bool = True) -> bool|None:if isinstance(flag, bool):errorLevel = execute("openssl version")if EXIT_SUCCESS == errorLevel:return Trueelif flag: # can try againexecute("sudo apt-get install openssl libssl-dev")return handleOpenSSL(False)else:return Falseelse:return Nonedef pressTheEnterKeyToExit(errorLevel:int|None = None):try:print("Please press the enter key to exit ({0}). ".format(errorLevel) if isinstance(errorLevel, int) else "Please press the enter key to exit. ")input()except:passdef main() -> int:# Parameters #failureCount = 0ecPrivateKeyFilePath = "ecPrivateKey.pem"certificateFilePath = "certificate.pem"rsaPrivateKeyFilePath = "rsaPrivateKey.pem"oldRsaPrivateKeyFilePath = "oldRsaPrivateKey.pem"keyboxFilePath = "keybox.xml"# First-phase Generation #failureCount += execute("openssl ecparam -name prime256v1 -genkey -noout -out \"{0}\"".format(ecPrivateKeyFilePath)) != 0failureCount += execute("openssl req -new -x509 -key \"{0}\" -out {1} -days 3650 -subj \"/CN=Keybox\"".format(ecPrivateKeyFilePath, certificateFilePath)) != 0failureCount += execute("openssl genrsa -out \"{0}\" 2048".format(rsaPrivateKeyFilePath)) != 0if failureCount > 0:print("Cannot generate a sample ``keybox.xml`` file since {0} PEM file{1} not generated successfully. ".format(failureCount, ("s were" if failureCount > 1 else " was")))pressTheEnterKeyToExit(EOF)return EOF# First-phase Reading #try:with open(ecPrivateKeyFilePath, "r", encoding = "utf-8") as f:ecPrivateKey = f.read()with open(certificateFilePath, "r", encoding = "utf-8") as f:certificate = f.read()with open(rsaPrivateKeyFilePath, "r", encoding = "utf-8") as f:rsaPrivateKey = f.read()except BaseException as e:print("Failed to read one or more of the PEM files. Details are as follows. \n{0}".format(e))pressTheEnterKeyToExit(EOF)return EOF# Second-phase Generation #if rsaPrivateKey.startswith("-----BEGIN PRIVATE KEY-----"):print("A newer openssl version is used. The RSA private key in the PKCS8 format will be converted to that in the PKCS1 format soon. ")failureCount += execute("openssl rsa -in \"{0}\" -out \"{1}\" -traditional".format(rsaPrivateKeyFilePath, oldRsaPrivateKeyFilePath))if failureCount > 0:print("Cannot convert the RSA private key in the PKCS8 format to that in the PKCS1 format. ")pressTheEnterKeyToExit(EOF)return EOFelse:print("Finished converting the RSA private key in the PKCS8 format to that in the PKCS1 format. ")try:with open(oldRsaPrivateKeyFilePath, "r", encoding = "utf-8") as f:rsaPrivateKey = f.read()except BaseException as e:print("Failed to update the RSA private key from \"{0}\". Details are as follows. \n{1}".format(oldRsaPrivateKeyFilePath, e))pressTheEnterKeyToExit(EOF)return EOF# Keybox Generation #keybox = keyboxFormatter.format(ecPrivateKey, certificate, rsaPrivateKey)print(keybox)try:with open(keyboxFilePath, "w", encoding = "utf-8") as f:f.write(keybox)print("Successfully wrote the keybox to \"{0}\". ".format(keyboxFilePath))pressTheEnterKeyToExit(EXIT_SUCCESS)return EXIT_SUCCESSexcept BaseException as e:print("Failed to write the keybox to \"{0}\". Details are as follows. \n{1}".format(keyboxFilePath, e))pressTheEnterKeyToExit(EXIT_FAILURE)return EXIT_FAILUREif "__main__" == __name__:exit(main())

替换 /data/adb/tricky_store/keybox.xml 之前,记得先将原来的 keybox.xml(刷入 tricky_store 时自带的那个基于 AOSP 的 keybox.xml)备份为 keybox.xml.bak
截图
12月14日凌晨做了一些更新:

  1. 支持粗略检查三个子密钥文件内容,支持 OpenSSL 私钥转 RSA 私钥;
  2. 如果文件存在,程序会提示是否覆盖;
  3. 设备ID随机生成。
import os
from random import randint, choice
from base64 import b64decode
try:os.chdir(os.path.abspath(os.path.dirname(__file__)))
except:pass
EXIT_SUCCESS = 0
EXIT_FAILURE = 1
EOF = (-1)
LB = 2 # the lower bound of the length of the device ID
UB = 12 # the upper bound of the length of the device ID
CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
keyboxFormatter = """<?xml version="1.0"?>
<AndroidAttestation>
<NumberOfKeyboxes>1</NumberOfKeyboxes>
<Keybox DeviceID="{0}">
<Key algorithm="ecdsa">
<PrivateKey format="pem">
{1}</PrivateKey>
<CertificateChain>
<NumberOfCertificates>1</NumberOfCertificates>
<Certificate format="pem">
{2}</Certificate>
</CertificateChain>
</Key>
<Key algorithm="rsa">
<PrivateKey format="pem">
{3}</PrivateKey>
</Key>
</Keybox>
</AndroidAttestation>
"""def canOverwrite(flags:list, idx:int, prompts:str|tuple|list|set) -> bool:if isinstance(flags, list) and isinstance(idx, int) and -len(flags) <= idx < len(flags) and isinstance(prompts, (str, tuple, list, set)):try:if isinstance(prompts, str):print("\"{0}\"".format(prompts))choice = input("The file mentioned above exists. Overwrite or not [aYn]? ")else:print(prompts)choice = input("At least one of the files mentioned above exists. Overwrite or not [aYn]? ")if choice.upper() == "A":for i in range((idx if idx >= 0 else len(flags) + idx), len(flags)): # overwirte the current file and all the following necessary files no matter whether they existflags[i] = Truereturn Trueelif choice.upper() == "N":return Falseelse:flags[idx] = Truereturn Trueexcept BaseException as e:print(e)return Falseelse:input("#")return Falsedef execute(commandline:str) -> int|None:if isinstance(commandline, str):print("$ " + commandline)return os.system(commandline)else:return Nonedef handleOpenSSL(flag:bool = True) -> bool|None:if isinstance(flag, bool):errorLevel = execute("openssl version")if EXIT_SUCCESS == errorLevel:return Trueelif flag: # can try againexecute("sudo apt-get install openssl libssl-dev")return handleOpenSSL(False)else:return Falseelse:return Nonedef pressTheEnterKeyToExit(errorLevel:int|None = None):try:print("Please press the enter key to exit ({0}). ".format(errorLevel) if isinstance(errorLevel, int) else "Please press the enter key to exit. ")input()except:passdef main() -> int:# Parameters #failureCount = 0deviceID = "".join([choice(CHARSET) for _ in range(randint(LB, UB))]) # or specify the device ID manually like "YourDeviceID"ecPrivateKeyFilePath = "ecPrivateKey.pem"certificateFilePath = "certificate.pem"rsaPrivateKeyFilePath = "rsaPrivateKey.pem"keyboxFilePath = "keybox.xml" # None for no files writtenflags = [not (os.path.isfile(ecPrivateKeyFilePath) or os.path.isfile(certificateFilePath)), not os.path.isfile(rsaPrivateKeyFilePath), not os.path.isfile(keyboxFilePath)]# First-phase Generation #if flags[0] or canOverwrite(flags, 0, (ecPrivateKeyFilePath, certificateFilePath)):failureCount += execute("openssl ecparam -name prime256v1 -genkey -noout -out \"{0}\"".format(ecPrivateKeyFilePath)) != 0if flags[0] or not os.path.isfile(certificateFilePath):failureCount += execute("openssl req -new -x509 -key \"{0}\" -out {1} -days 3650 -subj \"/CN=Keybox\"".format(ecPrivateKeyFilePath, certificateFilePath)) != 0if flags[1] or canOverwrite(flags, 1, rsaPrivateKeyFilePath):failureCount += execute("openssl genrsa -out \"{0}\" 2048".format(rsaPrivateKeyFilePath)) != 0if failureCount > 0:print("Cannot generate a sample ``keybox.xml`` file since {0} PEM file{1} not generated successfully. ".format(failureCount, ("s were" if failureCount > 1 else " was")))pressTheEnterKeyToExit(11)return 11# First-phase Reading #try:with open(ecPrivateKeyFilePath, "r", encoding = "utf-8") as f:ecPrivateKey = f.read()with open(certificateFilePath, "r", encoding = "utf-8") as f:certificate = f.read()with open(rsaPrivateKeyFilePath, "r", encoding = "utf-8") as f:rsaPrivateKey = f.read()except BaseException as e:print("Failed to read one or more of the PEM files. Details are as follows. \n{0}".format(e))pressTheEnterKeyToExit(12)return 12# Second-phase Generation #if flags[1]: # only updates the key content when the original key is newly generated or updating is allowedif rsaPrivateKey.startswith("-----BEGIN PRIVATE KEY-----") and rsaPrivateKey.rstrip().endswith("-----END PRIVATE KEY-----"):print("A newer openssl version is used. The RSA private key in the PKCS8 format will be converted to that in the PKCS1 format soon. ")failureCount += execute("openssl rsa -in \"{0}\" -out \"{0}\" -traditional".format(rsaPrivateKeyFilePath))if failureCount > 0:print("Cannot convert the RSA private key in the PKCS8 format to that in the PKCS1 format. ")pressTheEnterKeyToExit(13)return 13else:print("Finished converting the RSA private key in the PKCS8 format to that in the PKCS1 format. ")try:with open(rsaPrivateKeyFilePath, "r", encoding = "utf-8") as f:rsaPrivateKey = f.read()except BaseException as e:print("Failed to update the RSA private key from \"{0}\". Details are as follows. \n{1}".format(rsaPrivateKeyFilePath, e))pressTheEnterKeyToExit(14)return 14elif rsaPrivateKey.startswith("-----BEGIN OPENSSH PRIVATE KEY-----") and rsaPrivateKey.rstrip().endswith("-----END OPENSSH PRIVATE KEY-----"):print("An OpenSSL private key is detected, which will be converted to the RSA private key soon. ")failureCount += execute("ssh-keygen -p -m PEM -f \"{0}\" -N \"\"".format(rsaPrivateKeyFilePath))if failureCount > 0:print("Cannot convert the OpenSSL private key to the RSA private key. ")pressTheEnterKeyToExit(15)return 15else:print("Finished converting the OpenSSL private key to the RSA private key. ")try:with open(rsaPrivateKeyFilePath, "r", encoding = "utf-8") as f: # the ``ssh-keygen`` overwrites the file though no obvious output filepaths specifiedrsaPrivateKey = f.read()except BaseException as e:print("Failed to update the RSA private key from \"{0}\". Details are as follows. \n{1}".format(rsaPrivateKeyFilePath, e))pressTheEnterKeyToExit(16)return 16# Brief Checks #if not (ecPrivateKey.startswith("-----BEGIN EC PRIVATE KEY-----") and ecPrivateKey.rstrip().endswith("-----END EC PRIVATE KEY-----")):print("An invalid EC private key is detected. Please try to use the latest key generation tools to solve this issue. ")pressTheEnterKeyToExit(17)return 17if not (certificate.startswith("-----BEGIN CERTIFICATE-----") and certificate.rstrip().endswith("-----END CERTIFICATE-----")):print("An invalid certificate is detected. Please try to use the latest key generation tools to solve this issue. ")pressTheEnterKeyToExit(18)return 18if not (rsaPrivateKey.startswith("-----BEGIN RSA PRIVATE KEY-----") and rsaPrivateKey.rstrip().endswith("-----END RSA PRIVATE KEY-----")):print("An invalid final RSA private key is detected. Please try to use the latest key generation tools to solve this issue. ")pressTheEnterKeyToExit(19)return 19# Keybox Generation #keybox = keyboxFormatter.format(deviceID, ecPrivateKey, certificate, rsaPrivateKey)print("Generated keybox with a length of {0}: ".format(len(keybox)))print(keybox)if keyboxFilePath is not None and (flags[2] or canOverwrite(flags, 2, keyboxFilePath)):try:with open(keyboxFilePath, "w", encoding = "utf-8") as f:f.write(keybox)print("Successfully wrote the keybox to \"{0}\". ".format(keyboxFilePath))pressTheEnterKeyToExit(EXIT_SUCCESS)return EXIT_SUCCESSexcept BaseException as e:print("Failed to write the keybox to \"{0}\". Details are as follows. \n{1}".format(keyboxFilePath, e))pressTheEnterKeyToExit(20)return 20else:print("The keybox has not been written to any files. Please refer to the text above. ")pressTheEnterKeyToExit(EXIT_FAILURE)return EXIT_FAILUREif "__main__" == __name__:exit(main())

http://www.ppmy.cn/news/1556136.html

相关文章

【2025最新计算机毕业设计】基于Java的爱心社会公益平台【提供源码+答辩PPT+文档+项目部署】

作者简介&#xff1a;✌CSDN新星计划导师、Java领域优质创作者、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和学生毕业项目实战,高校老师/讲师/同行前辈交流。✌ 主要内容&#xff1a;&#x1f31f;Java项目、Python项目、前端项目、PHP、ASP.NET、人工智能…

虚拟机VirtualBox安装最新版本Oracle数据库

https://www.oracle.com/database/technologies/databaseappdev-vm.html 如上所示&#xff0c;从Oracle官方网站上下载最新版本的VirtualBox虚拟机对应的Oracle数据库安装源文件。 如上所示&#xff0c;在VirtualBox中导入下载的Oracle安装源文件。 如上所示&#xff0c;导入…

UIP协议栈 TCP通信客户端 服务端,UDP单播 广播通信 example

文章目录 1. TCP通信 客户端&#xff08;关键配置&#xff09;2. TCP 服务端配置3. UDP 点播通信4. UDP 广播通信5. UIP_UDP_APPCALL 里边的处理example6. TCP数据处理 &#xff0c;UIP_APPCALL调用的函数 UIP_APPCALL TCP的数据都在这个宏定义的函数里进行数据处理的 UDP 数据…

华为HarmonyOS实现跨多个子系统融合的场景化服务 -- 2 选择头像Button

场景介绍 本章节将向您介绍如何使用选择头像Button功能&#xff0c;开发者可调用对应Button组件快速拉起头像选择页面&#xff0c;供用户完成华为账号头像或其他头像的选择与展示。 前提条件 参见开发前提。 效果图展示 单击头像按钮拉起半模态选择头像页面来设置头像。 开…

Linux 更改目录命令 cd 详细介绍

Linux 和其他类 Unix 操作系统中的 cd&#xff08;change directory&#xff09;命令是最常用的命令之一&#xff0c;用于更改当前工作目录。 文章目录 01、更改到指定目录02、回到上一级目录03、回到用户的主目录04、相对路径05、绝对路径06、带空格的目录名07、带特殊字符的目…

洛谷P5076 【深基16.例7】普通二叉树(简化版)c嘎嘎

题目链接&#xff1a;P5076 【深基16.例7】普通二叉树&#xff08;简化版&#xff09; - 洛谷 | 计算机科学教育新生态 题目难度&#xff1a;普及/提高 解题思路&#xff1a;本题运用了STL中的multiset&#xff0c;它可以看成一个序列&#xff0c;插入一个数&#xff0c;删除一…

CVE-2024-32709 WordPress —— Recall 插件存在 SQL 注入漏洞

漏洞描述 WordPress 是一款免费开源的内容管理系统,适用于各类网站,包括个人博客、电子商务系统、企业网站。其插件 WP-Recall 的 account 存在 SQL 注入漏洞,攻击者可以通过该漏洞获取数据库敏感信息。 WP-Recall 版本 <= 16.26.5 漏洞复现 搭建环境、安装插件、完成…

跟着问题学19——BERT详解(2)

预训练策略 BERT模型的预训练基于两个任务&#xff1a; 屏蔽语言建模 下一句预测 在深入屏蔽语言建模之间&#xff0c;我们先来理解一下语言建模任务的原理。 语言建模 在语言建模任务中&#xff0c;我们训练模型给定一系列单词来预测下一个单词。可以把语言建模分为两类&…