From a7592f804ad40327a3fed569160e607d28599259 Mon Sep 17 00:00:00 2001 From: zhanzeyi Date: Mon, 15 Jul 2024 17:55:16 +0800 Subject: [PATCH 1/8] path standardization Signed-off-by: zhanzeyi --- .../api/include/localization_adapter.h | 2 +- .../api/src/localization_adapter.cpp | 2 +- .../api/src/sign_tool_service_impl.cpp | 6 +- hapsigntool_cpp/cmd/src/cmd_util.cpp | 49 +++++++++++++---- .../fsverity/include/thread_pool.h | 55 ++++++++++--------- hapsigntool_cpp/main.cpp | 2 +- .../zip/include/endof_central_directory.h | 2 + 7 files changed, 75 insertions(+), 43 deletions(-) diff --git a/hapsigntool_cpp/api/include/localization_adapter.h b/hapsigntool_cpp/api/include/localization_adapter.h index 3a969685..d878e7ff 100644 --- a/hapsigntool_cpp/api/include/localization_adapter.h +++ b/hapsigntool_cpp/api/include/localization_adapter.h @@ -55,7 +55,7 @@ public: Options* GetOptions(); EVP_PKEY* GetAliasKey(bool autoCreate); - EVP_PKEY* GetIssureKeyByAlias(); + EVP_PKEY* GetIssuerKeyByAlias(); X509* GetSubCaCertFile(); X509* GetCaCertFile(); STACK_OF(X509*) GetSignCertChain(); diff --git a/hapsigntool_cpp/api/src/localization_adapter.cpp b/hapsigntool_cpp/api/src/localization_adapter.cpp index 64f5fdeb..ebe1a6f6 100644 --- a/hapsigntool_cpp/api/src/localization_adapter.cpp +++ b/hapsigntool_cpp/api/src/localization_adapter.cpp @@ -213,7 +213,7 @@ err: return NULL; } -EVP_PKEY* LocalizationAdapter::GetIssureKeyByAlias() +EVP_PKEY* LocalizationAdapter::GetIssuerKeyByAlias() { return GetAliasKey(false); } diff --git a/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp b/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp index 4067ea69..babf298d 100644 --- a/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp +++ b/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp @@ -208,7 +208,7 @@ bool SignToolServiceImpl::GenerateCert(Options* options) goto err; } adapter->SetIssuerKeyStoreFile(true); - rootKeyPair = adapter->GetIssureKeyByAlias(); + rootKeyPair = adapter->GetIssuerKeyByAlias(); if (!rootKeyPair) { goto err; } @@ -366,7 +366,7 @@ bool SignToolServiceImpl::GenerateAppCert(Options* options) goto err; } adapter->SetIssuerKeyStoreFile(true); - if (!(issueKeyPair = adapter->GetIssureKeyByAlias())) { // get issuer keypair + if (!(issueKeyPair = adapter->GetIssuerKeyByAlias())) { // get issuer keypair goto err; } adapter->ResetPwd(); // clean pwd for safety @@ -410,7 +410,7 @@ bool SignToolServiceImpl::GenerateProfileCert(Options* options) goto err; } adapter->SetIssuerKeyStoreFile(true); - if (!(issueKeyPair = adapter->GetIssureKeyByAlias())) { // get issuer keypair + if (!(issueKeyPair = adapter->GetIssuerKeyByAlias())) { // get issuer keypair goto err; } adapter->ResetPwd(); // clean pwd for safety diff --git a/hapsigntool_cpp/cmd/src/cmd_util.cpp b/hapsigntool_cpp/cmd/src/cmd_util.cpp index 84d835cd..439463be 100644 --- a/hapsigntool_cpp/cmd/src/cmd_util.cpp +++ b/hapsigntool_cpp/cmd/src/cmd_util.cpp @@ -193,21 +193,30 @@ static bool outFilePath(Options* options) // check path directory is exists for (auto& key : outFileKeys) { if (options->count(key)) { - std::filesystem::path pat = options->GetString(key); + std::string outPath = options->GetString(key); + outPath.erase(std::remove_if(outPath.begin(), outPath.end(), ::isspace), outPath.end()); + if (outPath.empty()) { + PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "'" + key + "' output file cannot be empty"); + return false; + } + std::filesystem::path pat = outPath; if (std::filesystem::is_directory(pat)) { - PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "'" + std::string(pat.c_str()) - + "' is a directory"); + PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "'" + outPath + "' is a directory"); return false; } std::string parentPath = pat.parent_path(); - if (parentPath == "" || parentPath == "./") { - return true; + if (parentPath == "") { + parentPath = "./"; } - if (!std::filesystem::exists(parentPath)) { - PrintErrorNumberMsg("IO_ERROR", IO_ERROR, "output file parent directory'" - + std::string(parentPath.c_str()) + "' not exist"); + char path[PATH_MAX] = {0x00}; + if (parentPath.size() > PATH_MAX || realpath(parentPath.c_str(), path) == nullptr) { + PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "output file parent directory' " + + parentPath + "' not exist"); return false; } + std::string charStr(path); + std::string fileName = pat.filename(); + (*options)[key] = charStr + "/" + fileName; } } return true; @@ -224,10 +233,28 @@ static bool UpdateParamForCheckFile(ParamsSharedPtr param) Options::PROFILE_CERT_FILE, Options::APP_CERT_FILE, Options::PROFILE_FILE}; + for (auto& key : inFileKeys) { - if (options->count(key) && - !FileUtils::IsValidFile(options->GetString(key))) { - return false; + if (options->count(key)) { + char path[PATH_MAX] = {0x00}; + std::string inFilePath = options->GetString(key); + inFilePath.erase(std::remove_if(inFilePath.begin(), inFilePath.end(), ::isspace), inFilePath.end()); + if (inFilePath.empty()) { + PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "'" + key + "' input file cannot be empty"); + return false; + } + + if (inFilePath.size() > PATH_MAX || realpath(inFilePath.c_str(), path) == nullptr) { + PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "input file '" + + inFilePath + "' not exist"); + return false; + } + std::string charStr(path); + (*options)[key] = charStr; + + if (!FileUtils::IsValidFile(options->GetString(key))) { + return false; + } } } // check path exists diff --git a/hapsigntool_cpp/codesigning/fsverity/include/thread_pool.h b/hapsigntool_cpp/codesigning/fsverity/include/thread_pool.h index 9c9684a9..67f13054 100644 --- a/hapsigntool_cpp/codesigning/fsverity/include/thread_pool.h +++ b/hapsigntool_cpp/codesigning/fsverity/include/thread_pool.h @@ -32,23 +32,24 @@ namespace SignatureTools { namespace Uscript { class ThreadPool { public: - ThreadPool(size_t threads) - : stop(false) + ThreadPool(size_t threads = TASK_NUM) + : m_stop(false) { for (size_t i = 0; i < threads; ++i) - workers.emplace_back([this] { + m_workers.emplace_back([this] { std::function task; - std::unique_lock lock(queue_mutex); - while (!(stop && tasks.empty())) { - condition.wait(lock, [this] { return stop || !tasks.empty(); }); - if (stop && tasks.empty()) + std::unique_lock lock(m_queueMutex); + while (!(m_stop && m_tasks.empty())) { + m_condition.wait(lock, [this] { return m_stop || !m_tasks.empty(); }); + if (m_stop && m_tasks.empty()) { return; - task = std::move(tasks.front()); - tasks.pop(); + } + task = std::move(m_tasks.front()); + m_tasks.pop(); lock.unlock(); task(); lock.lock(); - condition_max.notify_one(); + m_conditionMax.notify_one(); } }); } @@ -63,38 +64,40 @@ public: ); std::future res = task->get_future(); { - std::unique_lock lock(queue_mutex); - while (stop == false && tasks.size() >= TASK_NUM) - condition_max.wait(lock); - tasks.emplace([task] () { (*task)(); }); - condition.notify_one(); + std::unique_lock lock(m_queueMutex); + while (m_stop == false && m_tasks.size() >= TASK_NUM) { + m_conditionMax.wait(lock); + } + m_tasks.emplace([task] () { (*task)(); }); + m_condition.notify_one(); } return res; } ~ThreadPool() { - if (stop == false) { + if (m_stop == false) { { - std::unique_lock lock(queue_mutex); - stop = true; + std::unique_lock lock(m_queueMutex); + m_stop = true; } - condition.notify_all(); - for (std::thread& worker : workers) + m_condition.notify_all(); + for (std::thread& worker : m_workers) { worker.join(); + } } } private: // need to keep track of threads so we can join them - std::vector< std::thread > workers; + std::vector m_workers; // the task queue - std::queue< std::function > tasks; + std::queue> m_tasks; // synchronization - std::mutex queue_mutex; - std::condition_variable condition; - std::condition_variable condition_max; - bool stop; + std::mutex m_queueMutex; + std::condition_variable m_condition; + std::condition_variable m_conditionMax; + bool m_stop; }; } // namespace Uscript } // namespace SignatureTools diff --git a/hapsigntool_cpp/main.cpp b/hapsigntool_cpp/main.cpp index f18964f7..167f8588 100644 --- a/hapsigntool_cpp/main.cpp +++ b/hapsigntool_cpp/main.cpp @@ -21,5 +21,5 @@ int main(int argc, char** argv) if (isSuccess) { return 0; } - return -1; + return 1; } \ No newline at end of file diff --git a/hapsigntool_cpp/zip/include/endof_central_directory.h b/hapsigntool_cpp/zip/include/endof_central_directory.h index 3647cf39..bd2f061d 100644 --- a/hapsigntool_cpp/zip/include/endof_central_directory.h +++ b/hapsigntool_cpp/zip/include/endof_central_directory.h @@ -19,6 +19,8 @@ #include #include +#include "byte_buffer.h" + namespace OHOS { namespace SignatureTools { /** -- Gitee From 6b659bd6aca2ff57b0166e90440b6e67513a094e Mon Sep 17 00:00:00 2001 From: zhanzeyi Date: Tue, 16 Jul 2024 19:32:29 +0800 Subject: [PATCH 2/8] fix code warning Signed-off-by: zhanzeyi --- .../api/src/sign_tool_service_impl.cpp | 52 ++++----- hapsigntool_cpp/cmd/include/cmd_util.h | 2 + hapsigntool_cpp/cmd/include/help.h | 10 +- hapsigntool_cpp/cmd/src/cmd_util.cpp | 104 ++++++++---------- hapsigntool_cpp/cmd/src/params_run_tool.cpp | 95 +++++++++++++++- hapsigntool_cpp/common/include/byte_buffer.h | 3 - .../common/include/digest_parameter.h | 2 +- .../common/include/pkcs7_context.h | 8 +- hapsigntool_cpp/common/src/byte_buffer.cpp | 34 ------ .../common/src/digest_parameter.cpp | 22 ++-- .../common/src/random_access_file.cpp | 4 +- .../hap/verify/include/hap_verify_result.h | 38 +++---- .../hap/verify/include/matching_result.h | 8 +- .../hap/verify/src/hap_verify_result.cpp | 50 ++++----- hapsigntool_cpp/hap/verify/src/verify_hap.cpp | 34 +++--- .../profile/include/profile_info.h | 81 +++++++------- hapsigntool_cpp/profile/src/profile_info.cpp | 52 ++++----- .../utils/include/hap_signer_block_utils.h | 14 +-- .../utils/include/key_store_helper.h | 4 +- .../utils/include/signature_tools_log.h | 24 ++-- .../utils/include/verify_cert_openssl_utils.h | 38 +++---- .../utils/src/hap_signer_block_utils.cpp | 90 +++++++-------- hapsigntool_cpp/utils/src/hash_utils.cpp | 10 +- .../utils/src/key_store_helper.cpp | 28 ++--- .../utils/src/verify_cert_openssl_utils.cpp | 46 ++++---- .../utils/src/verify_hap_openssl_utils.cpp | 26 ++--- .../zip/include/central_directory.h | 24 ++-- .../zip/src/endof_central_directory.cpp | 1 - 28 files changed, 470 insertions(+), 434 deletions(-) diff --git a/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp b/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp index babf298d..b517a36f 100644 --- a/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp +++ b/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp @@ -72,7 +72,7 @@ bool SignToolServiceImpl::GenerateRootCertToFile(Options* options, EVP_PKEY* roo std::string signAlg = options->GetString(Options::SIGN_ALG); std::string subject = options->GetString(Options::SUBJECT); std::string outFile; - X509* cert = nullptr; + X509* certPtr = nullptr; X509_REQ* csr = nullptr; bool result = false; if (rootKey == nullptr) { @@ -82,22 +82,22 @@ bool SignToolServiceImpl::GenerateRootCertToFile(Options* options, EVP_PKEY* roo if (!csr) { goto err; } - cert = CertTools::GenerateRootCertificate(rootKey, csr, options); - if (!cert) { + certPtr = CertTools::GenerateRootCertificate(rootKey, csr, options); + if (!certPtr) { goto err; } - if (!X509CertVerify(cert, rootKey)) { + if (!X509CertVerify(certPtr, rootKey)) { goto err; } - if (!OutputModeOfCert(cert, options)) { + if (!OutputModeOfCert(certPtr, options)) { goto err; } result = true; err: if (result == false) SIGNATURE_TOOLS_LOGE("generate root cert failed!"); - X509_free(cert); + X509_free(certPtr); X509_REQ_free(csr); return result; } @@ -355,44 +355,44 @@ X509_REQ* SignToolServiceImpl::GetCsr(EVP_PKEY* keyPair, std::string signAlg, st bool SignToolServiceImpl::GenerateAppCert(Options* options) { std::unique_ptr adapter = std::make_unique(options); - EVP_PKEY* keyPair = nullptr; - EVP_PKEY* issueKeyPair = nullptr; - X509_REQ* csr = nullptr; - X509* x509Certificate = nullptr; + EVP_PKEY* keyPairPtr = nullptr; + EVP_PKEY* issuerKeyPairPtr = nullptr; + X509_REQ* csrPtr = nullptr; + X509* x509CertificatePtr = nullptr; std::string signAlg = adapter->options->GetString(Options::SIGN_ALG); std::string subject = adapter->options->GetString(Options::SUBJECT); - if (!(keyPair = adapter->GetAliasKey(false))) { // get keypair + if (!(keyPairPtr = adapter->GetAliasKey(false))) { // get keypair goto err; } adapter->SetIssuerKeyStoreFile(true); - if (!(issueKeyPair = adapter->GetIssuerKeyByAlias())) { // get issuer keypair + if (!(issuerKeyPairPtr = adapter->GetIssuerKeyByAlias())) { // get issuer keypair goto err; } adapter->ResetPwd(); // clean pwd for safety - csr = GetCsr(keyPair, signAlg, subject); - if (!csr) { // get CSR request + csrPtr = GetCsr(keyPairPtr, signAlg, subject); + if (!csrPtr) { // get CSR request goto err; } - x509Certificate = CertTools::GenerateEndCert(csr, issueKeyPair, *adapter, + x509CertificatePtr = CertTools::GenerateEndCert(csrPtr, issuerKeyPairPtr, *adapter, APP_SIGNING_CAPABILITY, sizeof(APP_SIGNING_CAPABILITY)); // get app x509 cert - if (!x509Certificate) { + if (!x509CertificatePtr) { PrintErrorNumberMsg("CERTIFICATE_ERROR", CERTIFICATE_ERROR, "generate app cert failed"); goto err; } - if (!X509CertVerify(x509Certificate, issueKeyPair)) { + if (!X509CertVerify(x509CertificatePtr, issuerKeyPairPtr)) { goto err; } - if (!GetAndOutPutCert(*adapter, x509Certificate)) { + if (!GetAndOutPutCert(*adapter, x509CertificatePtr)) { goto err; } - adapter->AppAndProfileAssetsRealse({issueKeyPair, keyPair}, {csr}, {x509Certificate}); // realse heap memory + adapter->AppAndProfileAssetsRealse({issuerKeyPairPtr, keyPairPtr}, {csrPtr}, {x509CertificatePtr}); // realse heap memory return true; err: - adapter->AppAndProfileAssetsRealse({issueKeyPair, keyPair}, {csr}, {x509Certificate}); + adapter->AppAndProfileAssetsRealse({issuerKeyPairPtr, keyPairPtr}, {csrPtr}, {x509CertificatePtr}); return false; } @@ -400,7 +400,7 @@ bool SignToolServiceImpl::GenerateProfileCert(Options* options) { std::unique_ptr adapter = std::make_unique(options); EVP_PKEY* keyPair = nullptr; - EVP_PKEY* issueKeyPair = nullptr; + EVP_PKEY* issuerKeyPair = nullptr; X509_REQ* csr = nullptr; X509* x509Certificate = nullptr; std::string signAlg = adapter->options->GetString(Options::SIGN_ALG); @@ -410,7 +410,7 @@ bool SignToolServiceImpl::GenerateProfileCert(Options* options) goto err; } adapter->SetIssuerKeyStoreFile(true); - if (!(issueKeyPair = adapter->GetIssuerKeyByAlias())) { // get issuer keypair + if (!(issuerKeyPair = adapter->GetIssuerKeyByAlias())) { // get issuer keypair goto err; } adapter->ResetPwd(); // clean pwd for safety @@ -418,25 +418,25 @@ bool SignToolServiceImpl::GenerateProfileCert(Options* options) if (!csr) { // get CSR request goto err; } - x509Certificate = CertTools::GenerateEndCert(csr, issueKeyPair, *adapter, + x509Certificate = CertTools::GenerateEndCert(csr, issuerKeyPair, *adapter, PROFILE_SIGNING_CAPABILITY, sizeof(PROFILE_SIGNING_CAPABILITY)); // get profile x509 cert if (!x509Certificate) { PrintErrorNumberMsg("CERTIFICATE_ERROR", CERTIFICATE_ERROR, "generate profile cert failed"); goto err; } - if (!X509CertVerify(x509Certificate, issueKeyPair)) { + if (!X509CertVerify(x509Certificate, issuerKeyPair)) { goto err; } if (!GetAndOutPutCert(*adapter, x509Certificate)) { // output cert to file goto err; } - adapter->AppAndProfileAssetsRealse({issueKeyPair, keyPair}, {csr}, {x509Certificate}); // realse heap memory + adapter->AppAndProfileAssetsRealse({issuerKeyPair, keyPair}, {csr}, {x509Certificate}); // realse heap memory return true; err: - adapter->AppAndProfileAssetsRealse({issueKeyPair, keyPair}, {csr}, {x509Certificate}); + adapter->AppAndProfileAssetsRealse({issuerKeyPair, keyPair}, {csr}, {x509Certificate}); return false; } diff --git a/hapsigntool_cpp/cmd/include/cmd_util.h b/hapsigntool_cpp/cmd/include/cmd_util.h index 8bf22389..ac9abcab 100644 --- a/hapsigntool_cpp/cmd/include/cmd_util.h +++ b/hapsigntool_cpp/cmd/include/cmd_util.h @@ -41,6 +41,8 @@ public: static bool VerifyTypes(const std::string& inputType); static bool VerifyType(const std::string& inputtype, const std::string& supportTypes); static bool String2Bool(Options* options, const std::string& option); + static bool UpdateParamForCheckInFile(Options* options, const std::initializer_list& inFileKeys); + static bool UpdateParamForCheckOutFile(Options* options, const std::initializer_list& outFileKeys); static constexpr int ARGS_MIN_LEN = 2; private: diff --git a/hapsigntool_cpp/cmd/include/help.h b/hapsigntool_cpp/cmd/include/help.h index 43aaeee2..4f5b7b09 100644 --- a/hapsigntool_cpp/cmd/include/help.h +++ b/hapsigntool_cpp/cmd/include/help.h @@ -163,11 +163,6 @@ const std::string APP_CERT_HELP_TXT = R"( const std::string PROFILE_CERT_HELP_TXT = R"( generate-profile-cert[options]: - -keyAlias : key alias, required fields; - -keyPwd : key password, optional fields; - -issuer : issuer subject, required fields; - -issuerKeyAlias : issuer key alias, required fields; - -issuerKeyPwd : issuer key password, optional fields; -subject : certificate subject, required fields; -validity : certificate validity, optional fields, the default is 1095 days; -signAlg : signature algorithm, required fields, including SHA256withECDSA/SHA384withECDSA; @@ -175,6 +170,11 @@ const std::string PROFILE_CERT_HELP_TXT = R"( -keystorePwd : keystore password, optional fields; -outForm : the format of the output certificate file, including cert/certChain, optional fields, the default is cert; + -keyAlias : key alias, required fields; + -keyPwd : key password, optional fields; + -issuer : issuer subject, required fields; + -issuerKeyAlias : issuer key alias, required fields; + -issuerKeyPwd : issuer key password, optional fields; -rootCaCertFile : root CA certificate file, required when outForm is certChain; -subCaCertFile : secondary sub -CA certificate file, required when outForm is certChain; -outFile : output file, optional fields, if not filled, it will be directly output to the console; diff --git a/hapsigntool_cpp/cmd/src/cmd_util.cpp b/hapsigntool_cpp/cmd/src/cmd_util.cpp index 439463be..9e914bc8 100644 --- a/hapsigntool_cpp/cmd/src/cmd_util.cpp +++ b/hapsigntool_cpp/cmd/src/cmd_util.cpp @@ -32,7 +32,7 @@ bool CmdUtil::String2Bool(Options* options, const std::string& option) } else if (val == "0" || val == "false" || val == "FALSE") { (*options)[option] = false; } else { - PrintErrorNumberMsg("COMMAND_PARAM_ERROR", COMMAND_PARAM_ERROR, val + "is not valid value for "+"-" + option); + PrintErrorNumberMsg("COMMAND_PARAM_ERROR", COMMAND_PARAM_ERROR, val + "is not valid value for " + "-" + option); return false; } return true; @@ -40,7 +40,7 @@ bool CmdUtil::String2Bool(Options* options, const std::string& option) static bool UpdateParamForVariantCertInt(ParamsSharedPtr param) { - int defualtValidity = 0; + int defaultValidity = 0; Options* options = param->GetOptions(); if (options->count(Options::VALIDITY)) { int validity = 0; @@ -61,11 +61,11 @@ static bool UpdateParamForVariantCertInt(ParamsSharedPtr param) (*options)[Options::VALIDITY] = validity; } else if (param->GetMethod() == GENERATE_CA || param->GetMethod() == GENERATE_APP_CERT || param->GetMethod() == GENERATE_PROFILE_CERT) { - defualtValidity = DEFAULT_VALIDITY_DAYS * ONE_DAY_TIME; - (*options)[Options::VALIDITY] = defualtValidity; + defaultValidity = DEFAULT_VALIDITY_DAYS * ONE_DAY_TIME; + (*options)[Options::VALIDITY] = defaultValidity; } else if (param->GetMethod() == GENERATE_CERT) { - defualtValidity = DEFAULT_CUSTOM_VALIDITY_DAYS * ONE_DAY_TIME; - (*options)[Options::VALIDITY] = defualtValidity; + defaultValidity = DEFAULT_CUSTOM_VALIDITY_DAYS * ONE_DAY_TIME; + (*options)[Options::VALIDITY] = defaultValidity; } return true; } @@ -183,84 +183,71 @@ static bool UpdateParamForVariantBoolProfileSigned(ParamsSharedPtr param) return true; } -static bool outFilePath(Options* options) +bool CmdUtil::UpdateParamForCheckOutFile(Options* options, const std::initializer_list& outFileKeys) { - std::initializer_list outFileKeys = { - Options::OUT_FILE, Options::KEY_STORE_FILE, - Options::ISSUER_KEY_STORE_FILE, - Options::OUT_PROFILE, Options::OUT_CERT_CHAIN}; - - // check path directory is exists for (auto& key : outFileKeys) { if (options->count(key)) { - std::string outPath = options->GetString(key); - outPath.erase(std::remove_if(outPath.begin(), outPath.end(), ::isspace), outPath.end()); - if (outPath.empty()) { - PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "'" + key + "' output file cannot be empty"); - return false; + std::string outFilePath = options->GetString(key); + std::filesystem::path filePath = outFilePath; + std::string parentPath = filePath.parent_path(); + + //Purpose: To prevent the user output path from passing an empty string. eg " " + std::string tmpOutFilePath = outFilePath; + tmpOutFilePath.erase(std::remove_if(tmpOutFilePath.begin(), + tmpOutFilePath.end(), ::isspace), tmpOutFilePath.end()); + + if (parentPath.empty() && !tmpOutFilePath.empty()) { + parentPath = "./"; } - std::filesystem::path pat = outPath; - if (std::filesystem::is_directory(pat)) { - PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "'" + outPath + "' is a directory"); - return false; + char realFilePath[PATH_MAX + 1] = {0x00}; + if (parentPath.size() > PATH_MAX) { + PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "'" + outFilePath + "' File path longer than '" + + std::to_string(PATH_MAX) + "' characters"); } - std::string parentPath = pat.parent_path(); - if (parentPath == "") { - parentPath = "./"; + if (realpath(parentPath.c_str(), realFilePath) == nullptr) { + PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "The '" + outFilePath + + "' file does not exist or the path is invalid" + + "', parameter name '-" + key + "'"); + return false; } - char path[PATH_MAX] = {0x00}; - if (parentPath.size() > PATH_MAX || realpath(parentPath.c_str(), path) == nullptr) { - PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "output file parent directory' " - + parentPath + "' not exist"); + std::string charStr(realFilePath); + std::string fileName = filePath.filename(); + if (fileName.empty()) { + PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "The file name cannot be empty '" + + outFilePath + "', parameter name '-" + key + "'"); return false; } - std::string charStr(path); - std::string fileName = pat.filename(); (*options)[key] = charStr + "/" + fileName; } } return true; } -static bool UpdateParamForCheckFile(ParamsSharedPtr param) +bool CmdUtil::UpdateParamForCheckInFile(Options* options, const std::initializer_list& inFileKeys) { - // check file exists - Options* options = param->GetOptions(); - std::initializer_list inFileKeys = { - Options::IN_FILE, - Options::SUB_CA_CERT_FILE, - Options::CA_CERT_FILE, - Options::PROFILE_CERT_FILE, - Options::APP_CERT_FILE, - Options::PROFILE_FILE}; - for (auto& key : inFileKeys) { if (options->count(key)) { - char path[PATH_MAX] = {0x00}; std::string inFilePath = options->GetString(key); - inFilePath.erase(std::remove_if(inFilePath.begin(), inFilePath.end(), ::isspace), inFilePath.end()); - if (inFilePath.empty()) { - PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "'" + key + "' input file cannot be empty"); - return false; + char realFilePath[PATH_MAX + 1] = {0x00}; + if (inFilePath.size() > PATH_MAX) { + PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "'" + inFilePath + "' File path longer than '" + + std::to_string(PATH_MAX) + "' characters"); } - - if (inFilePath.size() > PATH_MAX || realpath(inFilePath.c_str(), path) == nullptr) { - PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "input file '" - + inFilePath + "' not exist"); + if (realpath(inFilePath.c_str(), realFilePath) == nullptr) { + PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "The '" + inFilePath + + "' file does not exist or the path is invalid" + + "', parameter name '-" + key + "'"); return false; } - std::string charStr(path); + std::string charStr(realFilePath); (*options)[key] = charStr; - if (!FileUtils::IsValidFile(options->GetString(key))) { + if (!FileUtils::IsValidFile(inFilePath)) { return false; } } } - // check path exists - if (!outFilePath(options)) { - return false; - } + return true; } @@ -355,9 +342,6 @@ static bool UpdateParam(ParamsSharedPtr param) if (!UpdateParamForVariantBoolProfileSigned(param)) { return false; } - if (!UpdateParamForCheckFile(param)) { - return false; - } if (!UpdateParamForCheckSignAlg(param)) { return false; } diff --git a/hapsigntool_cpp/cmd/src/params_run_tool.cpp b/hapsigntool_cpp/cmd/src/params_run_tool.cpp index 96d1fa6f..5544b36e 100644 --- a/hapsigntool_cpp/cmd/src/params_run_tool.cpp +++ b/hapsigntool_cpp/cmd/src/params_run_tool.cpp @@ -102,6 +102,17 @@ bool ParamsRunTool::RunSignApp(Options* params, SignToolServiceImpl& api) if (!params->Required({Options::MODE, Options::IN_FILE, Options::OUT_FILE, Options::SIGN_ALG})) { return false; } + + if (!CmdUtil::UpdateParamForCheckInFile(params, {Options::IN_FILE, Options::APP_CERT_FILE, + Options::PROFILE_FILE, Options::KEY_STORE_FILE, + ParamConstants::PARAM_REMOTE_SIGNERPLUGIN})) { + return false; + } + + if (!CmdUtil::UpdateParamForCheckOutFile(params, {Options::OUT_FILE})) { + return false; + } + std::string mode = params->GetString(Options::MODE); if (!StringUtils::CaseCompare(mode, LOCAL_SIGN) && !StringUtils::CaseCompare(mode, REMOTE_SIGN)) { @@ -173,12 +184,17 @@ bool ParamsRunTool::RunCa(Options* params, SignToolServiceImpl& api) Options::KEY_SIZE, Options::SUBJECT, Options::SIGN_ALG, Options::KEY_STORE_FILE})) { return false; } + + if (!CmdUtil::UpdateParamForCheckOutFile(params, {Options::OUT_FILE, Options::KEY_STORE_FILE, Options::ISSUER_KEY_STORE_FILE})) { + return false; + } + std::string keyAlg = params->GetString(Options::KEY_ALG); if (!CmdUtil::JudgeAlgType(keyAlg)) { return false; } - int size = params->GetInt(Options::KEY_SIZE); - if (!CmdUtil::JudgeSize(size)) { + int keySize = params->GetInt(Options::KEY_SIZE); + if (!CmdUtil::JudgeSize(keySize)) { return false; } std::string signAlg = params->GetString(Options::SIGN_ALG); @@ -199,6 +215,15 @@ bool ParamsRunTool::RunCert(Options* params, SignToolServiceImpl& api) Options::SIGN_ALG, Options::KEY_STORE_FILE})) { return false; } + + if (!CmdUtil::UpdateParamForCheckInFile(params, {Options::KEY_STORE_FILE, Options::ISSUER_KEY_STORE_FILE})) { + return false; + } + + if (!CmdUtil::UpdateParamForCheckOutFile(params, {Options::OUT_FILE})) { + return false; + } + std::string keyusage = params->GetString(Options::KEY_USAGE); if (!CmdUtil::VerifyTypes(keyusage)) { return false; @@ -265,6 +290,15 @@ bool ParamsRunTool::CheckEndCertArguments(Options& params) bool ParamsRunTool::RunAppCert(Options* params, SignToolServiceImpl& api) { + if (!CmdUtil::UpdateParamForCheckInFile(params, {Options::KEY_STORE_FILE, Options::ISSUER_KEY_STORE_FILE, + Options::CA_CERT_FILE, Options::SUB_CA_CERT_FILE})) { + return false; + } + + if (!CmdUtil::UpdateParamForCheckOutFile(params, {Options::OUT_FILE})) { + return false; + } + if (!ParamsRunTool::CheckEndCertArguments(*params)) { return false; } @@ -273,6 +307,15 @@ bool ParamsRunTool::RunAppCert(Options* params, SignToolServiceImpl& api) bool ParamsRunTool::RunProfileCert(Options* params, SignToolServiceImpl& api) { + if (!CmdUtil::UpdateParamForCheckInFile(params, {Options::KEY_STORE_FILE, Options::ISSUER_KEY_STORE_FILE, + Options::CA_CERT_FILE, Options::SUB_CA_CERT_FILE})) { + return false; + } + + if (!CmdUtil::UpdateParamForCheckOutFile(params, {Options::OUT_FILE})) { + return false; + } + if (!ParamsRunTool::CheckEndCertArguments(*params)) { return false; } @@ -284,12 +327,17 @@ bool ParamsRunTool::RunKeypair(Options* params, SignToolServiceImpl& api) if (!params->Required({Options::KEY_ALIAS, Options::KEY_ALG, Options::KEY_SIZE, Options::KEY_STORE_FILE})) { return false; } - std::string keyAlg = params->GetString(Options::KEY_ALG); - if (!CmdUtil::JudgeAlgType(keyAlg)) { + + if (!CmdUtil::UpdateParamForCheckOutFile(params, {Options::KEY_STORE_FILE})) { + return false; + } + + std::string keyAlgorithm = params->GetString(Options::KEY_ALG); + if (!CmdUtil::JudgeAlgType(keyAlgorithm)) { return false; } - int size = params->GetInt(Options::KEY_SIZE); - if (!CmdUtil::JudgeSize(size)) { + int keyAlgorithmSize = params->GetInt(Options::KEY_SIZE); + if (!CmdUtil::JudgeSize(keyAlgorithmSize)) { return false; } if (!FileUtils::ValidFileType(params->GetString(Options::KEY_STORE_FILE), {"p12", "jks"})) { @@ -303,6 +351,14 @@ bool ParamsRunTool::RunCsr(Options* params, SignToolServiceImpl& api) if (!params->Required({Options::KEY_ALIAS, Options::SUBJECT, Options::SIGN_ALG, Options::KEY_STORE_FILE})) { return false; } + if (!CmdUtil::UpdateParamForCheckInFile(params, {Options::KEY_STORE_FILE})) { + return false; + } + + if (!CmdUtil::UpdateParamForCheckOutFile(params, {Options::OUT_FILE})) { + return false; + } + std::string signAlg = params->GetString(Options::SIGN_ALG); if (!CmdUtil::JudgeSignAlgType(signAlg)) { return false; @@ -323,6 +379,16 @@ bool ParamsRunTool::RunSignProfile(Options* params, SignToolServiceImpl& api) if (!params->Required({params->MODE, params->SIGN_ALG, params->OUT_FILE, params->IN_FILE})) { return false; } + + if (!CmdUtil::UpdateParamForCheckInFile(params, {Options::KEY_STORE_FILE, Options::PROFILE_CERT_FILE, + Options::IN_FILE})) { + return false; + } + + if (!CmdUtil::UpdateParamForCheckOutFile(params, {Options::OUT_FILE})) { + return false; + } + std::string mode = params->GetString(Options::MODE); if (!StringUtils::CaseCompare(mode, LOCAL_SIGN) && !StringUtils::CaseCompare(mode, REMOTE_SIGN)) { @@ -355,6 +421,14 @@ bool ParamsRunTool::RunVerifyProfile(Options* params, SignToolServiceImpl& api) return false; } + if (!CmdUtil::UpdateParamForCheckInFile(params, {Options::IN_FILE})) { + return false; + } + + if (!CmdUtil::UpdateParamForCheckOutFile(params, {Options::OUT_FILE})) { + return false; + } + if (!FileUtils::ValidFileType(params->GetString(Options::IN_FILE), {"p7b"})) { return false; } @@ -383,6 +457,15 @@ bool ParamsRunTool::RunVerifyApp(Options* params, SignToolServiceImpl& api) if (!params->Required({Options::IN_FILE, Options::OUT_CERT_CHAIN, Options::OUT_PROFILE})) { return false; } + + if (!CmdUtil::UpdateParamForCheckInFile(params, {Options::IN_FILE})) { + return false; + } + + if (!CmdUtil::UpdateParamForCheckOutFile(params, {Options::OUT_CERT_CHAIN, Options::OUT_PROFILE})) { + return false; + } + std::string inForm = params->GetString(Options::INFORM, ZIP); if (!StringUtils::ContainsCase(InformList, inForm)) { PrintErrorNumberMsg("NOT_SUPPORT_ERROR", NOT_SUPPORT_ERROR, "parameter '" + inForm diff --git a/hapsigntool_cpp/common/include/byte_buffer.h b/hapsigntool_cpp/common/include/byte_buffer.h index d32ae4e0..c3373425 100644 --- a/hapsigntool_cpp/common/include/byte_buffer.h +++ b/hapsigntool_cpp/common/include/byte_buffer.h @@ -61,8 +61,6 @@ public: DLL_EXPORT ByteBuffer(const ByteBuffer& other); DLL_EXPORT ~ByteBuffer(); DLL_EXPORT ByteBuffer& operator=(const ByteBuffer& other); - DLL_EXPORT bool GetUInt64(uint64_t& value); - DLL_EXPORT bool GetUInt64(int32_t index, uint64_t& value); DLL_EXPORT bool GetInt64(int64_t& value); DLL_EXPORT bool GetInt64(int32_t index, int64_t& value); DLL_EXPORT bool GetUInt32(uint32_t& value); @@ -80,7 +78,6 @@ public: DLL_EXPORT void PutUInt8(uint8_t value); DLL_EXPORT void PutUInt16(uint16_t value); DLL_EXPORT void PutUInt32(uint32_t value); - DLL_EXPORT void PutUInt64(uint64_t value); DLL_EXPORT void PutInt16(int16_t value); DLL_EXPORT void PutInt16(int32_t offset, int16_t value); DLL_EXPORT void PutInt32(int32_t value); diff --git a/hapsigntool_cpp/common/include/digest_parameter.h b/hapsigntool_cpp/common/include/digest_parameter.h index 09891b37..7fc910cb 100644 --- a/hapsigntool_cpp/common/include/digest_parameter.h +++ b/hapsigntool_cpp/common/include/digest_parameter.h @@ -31,7 +31,7 @@ public: public: int32_t digestOutputSizeBytes; const EVP_MD* md; - EVP_MD_CTX* ptrCtx; + EVP_MD_CTX* ctxPtr; }; } // namespace SignatureTools } // namespace OHOS diff --git a/hapsigntool_cpp/common/include/pkcs7_context.h b/hapsigntool_cpp/common/include/pkcs7_context.h index 5738ca3e..7a85a1e5 100644 --- a/hapsigntool_cpp/common/include/pkcs7_context.h +++ b/hapsigntool_cpp/common/include/pkcs7_context.h @@ -34,11 +34,11 @@ struct Pkcs7Context { MatchingResult matchResult; std::string certIssuer; PKCS7* p7; - Pkcs7CertChains certChains; + Pkcs7CertChains certChain; ByteBuffer content; Pkcs7Context() : needWriteCrl(false), digestAlgorithm(0), matchResult(), certIssuer(), - p7(nullptr), certChains(), content() + p7(nullptr), certChain(), content() { } ~Pkcs7Context() @@ -47,12 +47,12 @@ struct Pkcs7Context { PKCS7_free(p7); p7 = nullptr; } - for (auto certChain : certChains) { + for (auto certChain : certChain) { for (auto cert : certChain) { X509_free(cert); } } - certChains.clear(); + certChain.clear(); } }; } // namespace SignatureTools diff --git a/hapsigntool_cpp/common/src/byte_buffer.cpp b/hapsigntool_cpp/common/src/byte_buffer.cpp index 447b210b..7e663367 100644 --- a/hapsigntool_cpp/common/src/byte_buffer.cpp +++ b/hapsigntool_cpp/common/src/byte_buffer.cpp @@ -124,29 +124,6 @@ bool ByteBuffer::CheckInputForGettingData(int32_t index, int32_t dataLen) return true; } -bool ByteBuffer::GetUInt64(uint64_t& value) -{ - if (!GetUInt64(0, value)) { - SIGNATURE_TOOLS_LOGE("GetUInt64 failed"); - return false; - } - position += sizeof(uint64_t); - return true; -} - -bool ByteBuffer::GetUInt64(int32_t index, uint64_t& value) -{ - if (!CheckInputForGettingData(index, sizeof(uint64_t))) { - SIGNATURE_TOOLS_LOGE("Failed to get UInt64"); - return false; - } - if (memcpy_s(&value, sizeof(value), (buffer.get() + position + index), sizeof(uint64_t)) != EOK) { - SIGNATURE_TOOLS_LOGE("memcpy_s failed"); - return false; - } - return true; -} - bool ByteBuffer::GetInt64(int64_t& value) { if (!GetInt64(0, value)) { @@ -440,17 +417,6 @@ void ByteBuffer::PutUInt32(uint32_t value) } } -void ByteBuffer::PutUInt64(uint64_t value) -{ - if (limit - position >= static_cast(sizeof(value))) { - if (memcpy_s(buffer.get() + position, limit - position, &value, sizeof(value)) != EOK) { - SIGNATURE_TOOLS_LOGE("memcpy_s failed"); - } else { - position += sizeof(value); - } - } -} - void ByteBuffer::ClearData() { if (buffer != nullptr && position < capacity) { diff --git a/hapsigntool_cpp/common/src/digest_parameter.cpp b/hapsigntool_cpp/common/src/digest_parameter.cpp index 5db1f463..adfe0ecf 100644 --- a/hapsigntool_cpp/common/src/digest_parameter.cpp +++ b/hapsigntool_cpp/common/src/digest_parameter.cpp @@ -17,15 +17,15 @@ namespace OHOS { namespace SignatureTools { -DigestParameter::DigestParameter() : digestOutputSizeBytes(0), md(nullptr), ptrCtx(nullptr) +DigestParameter::DigestParameter() : digestOutputSizeBytes(0), md(nullptr), ctxPtr(nullptr) { } DigestParameter::~DigestParameter() { - if (ptrCtx != nullptr) { - EVP_MD_CTX_destroy(ptrCtx); - ptrCtx = nullptr; + if (ctxPtr != nullptr) { + EVP_MD_CTX_destroy(ctxPtr); + ctxPtr = nullptr; } /* md points to the OpenSSL global static struct constant, no need to free. */ md = nullptr; @@ -35,20 +35,20 @@ DigestParameter::DigestParameter(const DigestParameter& other) { digestOutputSizeBytes = other.digestOutputSizeBytes; md = other.md; - ptrCtx = EVP_MD_CTX_create(); - EVP_MD_CTX_copy(ptrCtx, other.ptrCtx); + ctxPtr = EVP_MD_CTX_create(); + EVP_MD_CTX_copy(ctxPtr, other.ctxPtr); } DigestParameter& DigestParameter::operator = (const DigestParameter& other) { - if (ptrCtx != nullptr) { - EVP_MD_CTX_destroy(ptrCtx); - ptrCtx = nullptr; + if (ctxPtr != nullptr) { + EVP_MD_CTX_destroy(ctxPtr); + ctxPtr = nullptr; } digestOutputSizeBytes = other.digestOutputSizeBytes; md = other.md; - ptrCtx = EVP_MD_CTX_create(); - EVP_MD_CTX_copy(ptrCtx, other.ptrCtx); + ctxPtr = EVP_MD_CTX_create(); + EVP_MD_CTX_copy(ctxPtr, other.ctxPtr); return *this; } } diff --git a/hapsigntool_cpp/common/src/random_access_file.cpp b/hapsigntool_cpp/common/src/random_access_file.cpp index 25139c20..9054ae1e 100644 --- a/hapsigntool_cpp/common/src/random_access_file.cpp +++ b/hapsigntool_cpp/common/src/random_access_file.cpp @@ -70,10 +70,10 @@ int64_t RandomAccessFile::GetLength() const bool RandomAccessFile::CheckLittleEndian() { union LittleEndian { - int32_t num; + int32_t number; char ch; } t; - t.num = 1; + t.number = 1; return (t.ch == 1); } diff --git a/hapsigntool_cpp/hap/verify/include/hap_verify_result.h b/hapsigntool_cpp/hap/verify/include/hap_verify_result.h index ba3c9bde..7d64fa6d 100644 --- a/hapsigntool_cpp/hap/verify/include/hap_verify_result.h +++ b/hapsigntool_cpp/hap/verify/include/hap_verify_result.h @@ -23,28 +23,28 @@ namespace OHOS { namespace SignatureTools { -enum class DevMode { +enum class ModeDev { DEFAULT = 0, DEV, NON_DEV, }; -enum HapVerifyResultCode { +enum VerifyHapResultCode { VERIFY_SUCCESS = 0, FILE_PATH_INVALID = -1, OPEN_FILE_ERROR = -2, SIGNATURE_NOT_FOUND = -3, - VERIFY_APP_PKCS7_FAIL = -4, - PROFILE_PARSE_FAIL = -5, - APP_SOURCE_NOT_TRUSTED = -6, - GET_DIGEST_FAIL = -7, + GET_DIGEST_FAIL = -4, + NO_PROFILE_BLOCK_FAIL = -5, + VERIFY_SIGNATURE_FAIL = -6, + VERIFY_SOURCE_INIT_FAIL = -7, VERIFY_INTEGRITY_FAIL = -8, FILE_SIZE_TOO_LARGE = -9, GET_PUBLICKEY_FAIL = -10, - GET_SIGNATURE_FAIL = -11, - NO_PROFILE_BLOCK_FAIL = -12, - VERIFY_SIGNATURE_FAIL = -13, - VERIFY_SOURCE_INIT_FAIL = -14, + VERIFY_APP_PKCS7_FAIL = -11, + PROFILE_PARSE_FAIL = -12, + APP_SOURCE_NOT_TRUSTED = -13, + GET_SIGNATURE_FAIL = -14, OUT_PUT_FILE_FAIL = -15, VERIFY_CODE_SIGN_FAIL = -16, }; @@ -62,7 +62,7 @@ struct OptionalBlock { class HapVerifyResult { public: DLL_EXPORT HapVerifyResult(); - DLL_EXPORT ~HapVerifyResult(); + DLL_EXPORT ~HapVerifyResult() = default; DLL_EXPORT int32_t GetVersion() const; DLL_EXPORT void SetVersion(int32_t signatureVersion); DLL_EXPORT void SetPkcs7SignBlock(const ByteBuffer& pkcs7); @@ -80,14 +80,14 @@ public: DLL_EXPORT int32_t GetBlockFromOptionalBlocks(int32_t blockType, std::string& block) const; private: - int32_t version = 0; - std::vector publicKeys; - std::vector signatures; - ByteBuffer pkcs7SignBlock; - ByteBuffer pkcs7ProfileBlock; - std::vector optionalBlocks; - ProfileInfo provisionInfo; - std::vector profile; + int32_t m_version = 0; + std::vector m_publicKeys; + std::vector m_signatures; + ByteBuffer m_pkcs7SignBlock; + ByteBuffer m_pkcs7ProfileBlock; + std::vector m_optionalBlocks; + ProfileInfo m_provisionInfo; + std::vector m_profile; }; } // namespace SignatureTools } // namespace OHOS diff --git a/hapsigntool_cpp/hap/verify/include/matching_result.h b/hapsigntool_cpp/hap/verify/include/matching_result.h index 9f56b1cf..2320b6f2 100644 --- a/hapsigntool_cpp/hap/verify/include/matching_result.h +++ b/hapsigntool_cpp/hap/verify/include/matching_result.h @@ -16,13 +16,13 @@ #define SIGNATRUETOOLS_MATCHING_RESULT_H namespace OHOS { namespace SignatureTools { -enum TrustedSources { +enum SourcesTrusted { OTHER_TRUSTED_SOURCE = 0, APP_GALLARY, APP_SYSTEM, APP_THIRD_PARTY_PRELOAD, }; -enum MatchingStates { +enum StatesMatching { DO_NOT_MATCH = 0, MATCH_WITH_SIGN, MATCH_WITH_PROFILE, @@ -30,8 +30,8 @@ enum MatchingStates { MATCH_WITH_TICKET, }; struct MatchingResult { - MatchingStates matchState; - TrustedSources source; + StatesMatching matchState; + SourcesTrusted source; }; } // namespace SignatureTools } // namespace OHOS diff --git a/hapsigntool_cpp/hap/verify/src/hap_verify_result.cpp b/hapsigntool_cpp/hap/verify/src/hap_verify_result.cpp index 292d507b..2686ce17 100644 --- a/hapsigntool_cpp/hap/verify/src/hap_verify_result.cpp +++ b/hapsigntool_cpp/hap/verify/src/hap_verify_result.cpp @@ -18,58 +18,54 @@ namespace OHOS { namespace SignatureTools { HapVerifyResult::HapVerifyResult() - : version(0), publicKeys(), signatures(), pkcs7SignBlock(), - pkcs7ProfileBlock(), optionalBlocks(), provisionInfo() + : m_version(0), m_publicKeys(), m_signatures(), m_pkcs7SignBlock(), + m_pkcs7ProfileBlock(), m_optionalBlocks(), m_provisionInfo() { } -HapVerifyResult::~HapVerifyResult() -{ -} - -int32_t HapVerifyResult::GetVersion() const +void HapVerifyResult::SetPkcs7SignBlock(const ByteBuffer& pkcs7) { - return version; + m_pkcs7SignBlock = pkcs7; } -void HapVerifyResult::SetVersion(int32_t signatureVersion) +void HapVerifyResult::SetPkcs7ProfileBlock(const ByteBuffer& pkcs7) { - version = signatureVersion; + m_pkcs7ProfileBlock = pkcs7; } -void HapVerifyResult::SetPkcs7SignBlock(const ByteBuffer& pkcs7) +void HapVerifyResult::SetOptionalBlocks(const std::vector& option) { - pkcs7SignBlock = pkcs7; + m_optionalBlocks = option; } -void HapVerifyResult::SetPkcs7ProfileBlock(const ByteBuffer& pkcs7) +int32_t HapVerifyResult::GetVersion() const { - pkcs7ProfileBlock = pkcs7; + return m_version; } -void HapVerifyResult::SetOptionalBlocks(const std::vector& option) +void HapVerifyResult::SetVersion(int32_t signatureVersion) { - optionalBlocks = option; + m_version = signatureVersion; } std::vector HapVerifyResult::GetPublicKey() const { - return publicKeys; + return m_publicKeys; } std::vector HapVerifyResult::GetSignature() const { - return signatures; + return m_signatures; } void HapVerifyResult::SetPublicKey(const std::vector& inputPubkeys) { - publicKeys = inputPubkeys; + m_publicKeys = inputPubkeys; } void HapVerifyResult::SetSignature(const std::vector& inputSignatures) { - signatures = inputSignatures; + m_signatures = inputSignatures; } int32_t HapVerifyResult::GetProperty(std::string& property) const @@ -79,9 +75,9 @@ int32_t HapVerifyResult::GetProperty(std::string& property) const int32_t HapVerifyResult::GetBlockFromOptionalBlocks(int32_t blockType, std::string& block) const { - for (unsigned long i = 0; i < optionalBlocks.size(); i++) { - if (optionalBlocks[i].optionalType == blockType) { - const ByteBuffer& option = optionalBlocks[i].optionalBlockValue; + for (unsigned long i = 0; i < m_optionalBlocks.size(); i++) { + if (m_optionalBlocks[i].optionalType == blockType) { + const ByteBuffer& option = m_optionalBlocks[i].optionalBlockValue; block += std::string(option.GetBufferPtr(), option.GetCapacity()); return GET_SUCCESS; } @@ -91,22 +87,22 @@ int32_t HapVerifyResult::GetBlockFromOptionalBlocks(int32_t blockType, std::stri void HapVerifyResult::SetProvisionInfo(const ProfileInfo& info) { - provisionInfo = info; + m_provisionInfo = info; } ProfileInfo HapVerifyResult::GetProvisionInfo() const { - return provisionInfo; + return m_provisionInfo; } std::vector HapVerifyResult::GetProfile() const { - return profile; + return m_profile; } void HapVerifyResult::SetProfile(std::vector profile) { - this->profile = profile; + this->m_profile = profile; } } // namespace SignatureTools } // namespace OHOS \ No newline at end of file diff --git a/hapsigntool_cpp/hap/verify/src/verify_hap.cpp b/hapsigntool_cpp/hap/verify/src/verify_hap.cpp index 1dca2fbb..7616cd8b 100644 --- a/hapsigntool_cpp/hap/verify/src/verify_hap.cpp +++ b/hapsigntool_cpp/hap/verify/src/verify_hap.cpp @@ -164,13 +164,13 @@ int32_t VerifyHap::Verify(RandomAccessFile& hapFile, HapVerifyResult& hapVerifyV return GET_DIGEST_FAIL; } std::vector publicKeys; - if (!VerifyHapOpensslUtils::GetPublickeys(pkcs7Context.certChains[0], publicKeys)) { + if (!VerifyHapOpensslUtils::GetPublickeys(pkcs7Context.certChain[0], publicKeys)) { SIGNATURE_TOOLS_LOGE("Get publicKeys failed"); return GET_PUBLICKEY_FAIL; } hapVerifyV1Result.SetPublicKey(publicKeys); std::vector certSignatures; - if (!VerifyHapOpensslUtils::GetSignatures(pkcs7Context.certChains[0], certSignatures)) { + if (!VerifyHapOpensslUtils::GetSignatures(pkcs7Context.certChain[0], certSignatures)) { SIGNATURE_TOOLS_LOGE("Get sianatures failed"); return GET_SIGNATURE_FAIL; } @@ -179,7 +179,7 @@ int32_t VerifyHap::Verify(RandomAccessFile& hapFile, HapVerifyResult& hapVerifyV SIGNATURE_TOOLS_LOGE("Verify Integrity failed"); return VERIFY_INTEGRITY_FAIL; } - if (!VerifyHap::HapOutPutCertChain(pkcs7Context.certChains[0], + if (!VerifyHap::HapOutPutCertChain(pkcs7Context.certChain[0], options->GetString(Options::OUT_CERT_CHAIN))) { SIGNATURE_TOOLS_LOGE("out put cert chain failed"); return OUT_PUT_FILE_FAIL; @@ -298,7 +298,7 @@ bool VerifyHap::VerifyAppSourceAndParseProfile(Pkcs7Context& pkcs7Context, bool& profileNeadWriteCrl) { std::string certSubject; - if (!VerifyCertOpensslUtils::GetSubjectFromX509(pkcs7Context.certChains[0][0], certSubject)) { + if (!VerifyCertOpensslUtils::GetSubjectFromX509(pkcs7Context.certChain[0][0], certSubject)) { SIGNATURE_TOOLS_LOGE("Get info of sign cert failed"); return false; } @@ -452,15 +452,15 @@ bool VerifyHap::IsAppDistributedTypeAllowInstall(const AppDistType& type, const ProfileInfo& provisionInfo) const { switch (type) { - case AppDistType::NONE_TYPE: - return false; + case AppDistType::CROWDTESTING: case AppDistType::APP_GALLERY: - case AppDistType::ENTERPRISE: - case AppDistType::ENTERPRISE_NORMAL: case AppDistType::ENTERPRISE_MDM: case AppDistType::OS_INTEGRATION: - case AppDistType::CROWDTESTING: + case AppDistType::ENTERPRISE: + case AppDistType::ENTERPRISE_NORMAL: return true; + case AppDistType::NONE_TYPE: + return false; default: return false; } @@ -556,25 +556,25 @@ int32_t VerifyHap::VerifyElfProfile(std::vector& profileData, HapVerifyR SIGNATURE_TOOLS_LOGE("verify signature failed"); return VERIFY_APP_PKCS7_FAIL; } - std::vector publicKeys; - if (!VerifyHapOpensslUtils::GetPublickeys(pkcs7Context.certChains[0], publicKeys)) { + std::vector elfPublicKeys; + if (!VerifyHapOpensslUtils::GetPublickeys(pkcs7Context.certChain[0], elfPublicKeys)) { SIGNATURE_TOOLS_LOGE("Get publicKeys failed"); return GET_PUBLICKEY_FAIL; } - hapVerifyV1Result.SetPublicKey(publicKeys); - std::vector certSignatures; - if (!VerifyHapOpensslUtils::GetSignatures(pkcs7Context.certChains[0], certSignatures)) { + hapVerifyV1Result.SetPublicKey(elfPublicKeys); + std::vector elfCertSignatures; + if (!VerifyHapOpensslUtils::GetSignatures(pkcs7Context.certChain[0], elfCertSignatures)) { SIGNATURE_TOOLS_LOGE("Get sianatures failed"); return GET_SIGNATURE_FAIL; } - hapVerifyV1Result.SetSignature(certSignatures); + hapVerifyV1Result.SetSignature(elfCertSignatures); return VERIFY_SUCCESS; } int32_t VerifyHap::WriteVerifyOutput(Pkcs7Context& pkcs7Context, std::vector profile, Options* options) { - if (pkcs7Context.certChains.size() > 0) { - bool flag = VerifyHap::HapOutPutCertChain(pkcs7Context.certChains[0], + if (pkcs7Context.certChain.size() > 0) { + bool flag = VerifyHap::HapOutPutCertChain(pkcs7Context.certChain[0], options->GetString(Options::OUT_CERT_CHAIN)); if (!flag) { SIGNATURE_TOOLS_LOGE("out put cert chain failed"); diff --git a/hapsigntool_cpp/profile/include/profile_info.h b/hapsigntool_cpp/profile/include/profile_info.h index e4b37a9b..e1938c5b 100644 --- a/hapsigntool_cpp/profile/include/profile_info.h +++ b/hapsigntool_cpp/profile/include/profile_info.h @@ -25,74 +25,75 @@ namespace OHOS { namespace SignatureTools { enum ProvisionType { - NONE_PROVISION_TYPE = 0, - RELEASE = 1, - DEBUG = 2 + NONE_PROVISION_TYPE, + RELEASE, + DEBUG }; enum AppDistType { - NONE_TYPE = 0, - APP_GALLERY = 1, - ENTERPRISE = 2, - OS_INTEGRATION = 3, - CROWDTESTING = 4, - ENTERPRISE_NORMAL = 5, - ENTERPRISE_MDM = 6, + NONE_TYPE, + APP_GALLERY, + ENTERPRISE, + OS_INTEGRATION, + CROWDTESTING, + ENTERPRISE_NORMAL, + ENTERPRISE_MDM }; -struct BundleInfo { +typedef struct BundleInfoSt { std::string developerId; - std::string developmentCertificate; + std::string apl; std::string distributionCertificate; + std::string developmentCertificate; std::string bundleName; - std::string apl; - std::string appFeature; std::string appIdentifier; std::vector dataGroupIds; -}; -struct Acls { + std::string appFeature; +}BundleInfo; +typedef struct AclsSt { std::vector allowedAcls; -}; -struct Permissions { - std::vector restrictedPermissions; +}Acls; +typedef struct PermissionsSt { std::vector restrictedCapabilities; -}; -struct DebugInfo { - std::string deviceIdType; + std::vector restrictedPermissions; +}Permissions; +typedef struct DebugInfoSt { std::vector deviceIds; -}; -struct Validity { - int64_t notBefore = 0; + std::string deviceIdType; +}DebugInfo; +typedef struct ValiditySt { int64_t notAfter = 0; -}; -struct Metadata { - std::string name; + int64_t notBefore = 0; +}Validity; +typedef struct MetadataSt { std::string value; std::string resource; -}; + std::string name; +}Metadata; struct ProfileInfo { DLL_EXPORT ProfileInfo(); DLL_EXPORT ~ProfileInfo(); DLL_EXPORT ProfileInfo(const ProfileInfo& info); DLL_EXPORT ProfileInfo& operator=(const ProfileInfo& info); int32_t versionCode = 0; - std::string versionName; std::string uuid; - ProvisionType type = NONE_PROVISION_TYPE; + std::string versionName; AppDistType distributionType = NONE_TYPE; - BundleInfo bundleInfo; - Acls acls; - Permissions permissions; - DebugInfo debugInfo; + ProvisionType type = NONE_PROVISION_TYPE; + BundleInfoSt bundleInfo; + PermissionsSt permissions; + AclsSt acls; std::string issuer; - std::string appId; + DebugInfoSt debugInfo; std::string fingerprint; + std::string appId; std::vector appPrivilegeCapabilities; - Validity validity; - std::vector metadatas; + ValiditySt validity; int32_t profileBlockLength = 0; - std::unique_ptr profileBlock; - std::string appServiceCapabilities; + std::vector metadatas; std::string organization; + std::string appServiceCapabilities; + std::unique_ptr profileBlock; }; } // namespace SignatureTools } // namespace OHOS + #endif // SIGNATRUETOOLS_PROFILE_INFO_H diff --git a/hapsigntool_cpp/profile/src/profile_info.cpp b/hapsigntool_cpp/profile/src/profile_info.cpp index 3dcf3cf3..0eaf00a5 100644 --- a/hapsigntool_cpp/profile/src/profile_info.cpp +++ b/hapsigntool_cpp/profile/src/profile_info.cpp @@ -28,43 +28,43 @@ ProfileInfo::~ProfileInfo() { profileBlock.reset(nullptr); } -ProfileInfo::ProfileInfo(const ProfileInfo& info) +ProfileInfo::ProfileInfo(const ProfileInfo& profileInfo) { - *this = info; + *this = profileInfo; } -ProfileInfo& ProfileInfo::operator=(const ProfileInfo& info) +ProfileInfo& ProfileInfo::operator=(const ProfileInfo& profileInfo) { - if (this == &info) { + if (this == &profileInfo) { return *this; } - this->versionCode = info.versionCode; - this->versionName = info.versionName; - this->uuid = info.uuid; - this->type = info.type; - this->distributionType = info.distributionType; - this->bundleInfo = info.bundleInfo; - this->acls = info.acls; - this->permissions = info.permissions; - this->debugInfo = info.debugInfo; - this->issuer = info.issuer; - this->appId = info.appId; - this->fingerprint = info.fingerprint; - this->appPrivilegeCapabilities = info.appPrivilegeCapabilities; - this->validity = info.validity; - this->metadatas = info.metadatas; - this->profileBlockLength = info.profileBlockLength; + this->versionCode = profileInfo.versionCode; + this->versionName = profileInfo.versionName; + this->uuid = profileInfo.uuid; + this->type = profileInfo.type; + this->distributionType = profileInfo.distributionType; + this->bundleInfo = profileInfo.bundleInfo; + this->acls = profileInfo.acls; + this->permissions = profileInfo.permissions; + this->debugInfo = profileInfo.debugInfo; + this->issuer = profileInfo.issuer; + this->appId = profileInfo.appId; + this->fingerprint = profileInfo.fingerprint; + this->appPrivilegeCapabilities = profileInfo.appPrivilegeCapabilities; + this->validity = profileInfo.validity; + this->metadatas = profileInfo.metadatas; + this->profileBlockLength = profileInfo.profileBlockLength; (this->profileBlock).reset(nullptr); - if (info.profileBlockLength != 0 && info.profileBlock != nullptr) { - this->profileBlock = std::make_unique(info.profileBlockLength); + if (profileInfo.profileBlockLength != 0 && profileInfo.profileBlock != nullptr) { + this->profileBlock = std::make_unique(profileInfo.profileBlockLength); unsigned char* profileBlockData = (this->profileBlock).get(); - unsigned char* originalProfile = info.profileBlock.get(); + unsigned char* originalProfile = profileInfo.profileBlock.get(); if (profileBlockData == nullptr) { return *this; } - std::copy(originalProfile, originalProfile + info.profileBlockLength, profileBlockData); + std::copy(originalProfile, originalProfile + profileInfo.profileBlockLength, profileBlockData); } - this->appServiceCapabilities = info.appServiceCapabilities; - this->organization = info.organization; + this->appServiceCapabilities = profileInfo.appServiceCapabilities; + this->organization = profileInfo.organization; return *this; } } // namespace SignatureTools diff --git a/hapsigntool_cpp/utils/include/hap_signer_block_utils.h b/hapsigntool_cpp/utils/include/hap_signer_block_utils.h index c45ba852..7c64d216 100644 --- a/hapsigntool_cpp/utils/include/hap_signer_block_utils.h +++ b/hapsigntool_cpp/utils/include/hap_signer_block_utils.h @@ -31,13 +31,6 @@ namespace SignatureTools { constexpr int32_t ZIP_CHUNK_DIGEST_PRIFIX_LEN = 5; -enum HapBlobType { - HAP_SIGN_BLOB = 0x20000000, - PROOF_ROTATION_BLOB = 0x20000001, - PROFILE_BLOB = 0x20000002, - PROPERTY_BLOB = 0x20000003, -}; - struct HapSignBlockHead { int32_t version = 0; int32_t blockCount = 0; @@ -46,6 +39,13 @@ struct HapSignBlockHead { int64_t hapSignBlockMagicHi; }; +enum HapBlobType { + HAP_SIGN_BLOB = 0x20000000, + PROOF_ROTATION_BLOB = 0x20000001, + PROFILE_BLOB = 0x20000002, + PROPERTY_BLOB = 0x20000003, +}; + struct HapSubSignBlockHead { uint32_t type = 0; uint32_t length = 0; diff --git a/hapsigntool_cpp/utils/include/key_store_helper.h b/hapsigntool_cpp/utils/include/key_store_helper.h index ab665586..7e98b791 100644 --- a/hapsigntool_cpp/utils/include/key_store_helper.h +++ b/hapsigntool_cpp/utils/include/key_store_helper.h @@ -35,10 +35,10 @@ public: char* keyPwd, EVP_PKEY** evpPkey); int GetPublicKey(PKCS7* safe, const std::string& alias, char* pass, int passlen, EVP_PKEY** publickey); int GetPrivateKey(PKCS7* safe, const std::string& alias, char* pass, int passlen, EVP_PKEY** keyPiar); - int SetCertPkcs12(X509* cert, PKCS12_SAFEBAG* bag, STACK_OF(PKCS12_SAFEBAG)* bags, unsigned char* keyId, + int SetCertPkcs12(X509* cert, PKCS12_SAFEBAG* bag, STACK_OF(PKCS12_SAFEBAG)* certBags, unsigned char* keyId, unsigned int keyIdLen, const char* name, STACK_OF(PKCS7)** safes, int certNid, int iter, const char* keyStorePwd); - int SetPkeyPkcs12(EVP_PKEY* pkey, PKCS12_SAFEBAG* bag, STACK_OF(PKCS12_SAFEBAG)* bags, + int SetPkeyPkcs12(EVP_PKEY* pkey, PKCS12_SAFEBAG* bag, STACK_OF(PKCS12_SAFEBAG)* keyBags, const char* name, STACK_OF(PKCS7)** safes, int iter, const char* keyPwd, int keyType, int keyNid, unsigned char* keyId, unsigned int keyIdLen); int GetAttrNid(PKCS12_SAFEBAG* bag, EVP_PKEY* pkey, int nid); diff --git a/hapsigntool_cpp/utils/include/signature_tools_log.h b/hapsigntool_cpp/utils/include/signature_tools_log.h index fc5af04a..5ec9fc8f 100644 --- a/hapsigntool_cpp/utils/include/signature_tools_log.h +++ b/hapsigntool_cpp/utils/include/signature_tools_log.h @@ -20,6 +20,7 @@ #include #include #include +#include #include "signature_tools_errno.h" @@ -43,6 +44,19 @@ namespace SignatureTools { #define SIGNATURE_TOOLS_LOGF(fmt, ...) SIGNATURE_LOG("Fatal", fmt, ##__VA_ARGS__) #define SIGNATURE_TOOLS_LOGE(fmt, ...) SIGNATURE_LOG("Error", fmt, ##__VA_ARGS__) +inline std::string GetSystemTime() +{ + std::string timeBuffer; + std::stringstream ss; + auto now = std::chrono::system_clock::now(); + std::time_t nowTime = std::chrono::system_clock::to_time_t(now); + std::tm* localTime = std::localtime(&nowTime); + auto ms = std::chrono::duration_cast(now.time_since_epoch()) % 1000; + ss << std::put_time(localTime, "%m-%d %H:%M:%S"); + ss << '.' << std::setfill('0') << std::setw(3) << ms.count(); + timeBuffer = ss.str(); + return timeBuffer; +} /* * Function: Print the error code and error message to the terminal. @@ -53,10 +67,7 @@ namespace SignatureTools { **/ inline void PrintErrorNumberMsg(const std::string& command, const int code, const std::string& details) { - auto now = std::chrono::system_clock::now(); - std::time_t nowTime = std::chrono::system_clock::to_time_t(now); - std::tm* localTime = std::localtime(&nowTime); - std::cerr << std::put_time(localTime, "%m-%d %H:%M:%S") << " ERROR - " << command << ", code: " + std::cerr << GetSystemTime() << " ERROR - " << command << ", code: " << code << ". Details: " << details << std::endl; } @@ -67,10 +78,7 @@ inline void PrintErrorNumberMsg(const std::string& command, const int code, cons **/ inline void PrintMsg(const std::string& message) { - auto now = std::chrono::system_clock::now(); - std::time_t nowTime = std::chrono::system_clock::to_time_t(now); - std::tm* localTime = std::localtime(&nowTime); - std::cout << std::put_time(localTime, "%m-%d %H:%M:%S") << " INFO - " << message << std::endl; + std::cout << GetSystemTime() << " INFO - " << message << std::endl; } } // namespace SignatureTools } // namespace OHOS diff --git a/hapsigntool_cpp/utils/include/verify_cert_openssl_utils.h b/hapsigntool_cpp/utils/include/verify_cert_openssl_utils.h index 4e07b83b..6581ed96 100644 --- a/hapsigntool_cpp/utils/include/verify_cert_openssl_utils.h +++ b/hapsigntool_cpp/utils/include/verify_cert_openssl_utils.h @@ -30,27 +30,13 @@ using CertSign = std::unordered_map; class VerifyCertOpensslUtils { public: VerifyCertOpensslUtils() = delete; - DLL_EXPORT static X509* GetX509CertFromPemString(const std::string& pemString); - DLL_EXPORT static X509* GetX509CertFromBase64String(const std::string& base64String); - DLL_EXPORT static X509_CRL* GetX509CrlFromDerBuffer(const ByteBuffer& crlBuffer, - int32_t offset, int32_t len); - DLL_EXPORT static void GenerateCertSignFromCertStack(STACK_OF(X509)* certs, CertSign& certVisitSign); - DLL_EXPORT static void ClearCertVisitSign(CertSign& certVisitSign); - DLL_EXPORT static bool GetCertsChain(CertChain& certsChain, CertSign& certVisitSign); - DLL_EXPORT static bool CertVerify(X509* cert, const X509* issuerCert); - DLL_EXPORT static bool GetSubjectFromX509(const X509* cert, std::string& subject); - DLL_EXPORT static bool GetIssuerFromX509(const X509* cert, std::string& issuer); - DLL_EXPORT static bool GetSerialNumberFromX509(const X509* cert, int64_t& certNumber); - DLL_EXPORT static bool GetIssuerFromX509Crl(const X509_CRL* crl, std::string& issuer); - DLL_EXPORT static bool VerifyCertChainPeriodOfValidity(CertChain& certsChain, - const ASN1_TYPE* signTime); DLL_EXPORT static bool VerifyCrl(CertChain& certsChain, STACK_OF(X509_CRL)* crls, - Pkcs7Context& pkcs7Context); + Pkcs7Context& pkcs7Context); DLL_EXPORT static bool CompareX509Cert(const X509* certA, const std::string& base64Cert); DLL_EXPORT static void WriteX509CrlToStream(std::ofstream& crlFile, X509_CRL* crl); DLL_EXPORT static bool GetPublickeyBase64FromPemCert(const std::string& certStr, std::string& publicKey); DLL_EXPORT static bool GetFingerprintBase64FromPemCert(const std::string& certStr, - std::string& fingerprint); + std::string& fingerprint); DLL_EXPORT static bool X509NameCompare(const X509_NAME* a, const X509_NAME* b); DLL_EXPORT static bool GetPublickeyBase64(const X509* cert, std::string& publicKey); DLL_EXPORT static int32_t CalculateLenAfterBase64Encode(int32_t len); @@ -58,18 +44,32 @@ public: DLL_EXPORT static X509* FindCertOfIssuer(X509* cert, CertSign& certVisitSign); DLL_EXPORT static std::string GetDnToString(X509_NAME* name); DLL_EXPORT static void GetTextFromX509Name(X509_NAME* name, int32_t nId, std::string& text); + DLL_EXPORT static X509* GetX509CertFromPemString(const std::string& pemString); + DLL_EXPORT static X509* GetX509CertFromBase64String(const std::string& base64String); + DLL_EXPORT static X509_CRL* GetX509CrlFromDerBuffer(const ByteBuffer& crlBuffer, + int32_t offset, int32_t len); DLL_EXPORT static X509_CRL* GetCrlBySignedCertIssuer(STACK_OF(X509_CRL)* crls, const X509* cert); DLL_EXPORT static bool CheckSignTimeInValidPeriod(const ASN1_TYPE* signTime, - const ASN1_TIME* notBefore, const ASN1_TIME* notAfter); + const ASN1_TIME* notBefore, const ASN1_TIME* notAfter); + DLL_EXPORT static void GenerateCertSignFromCertStack(STACK_OF(X509)* certs, CertSign& certVisitSign); + DLL_EXPORT static void ClearCertVisitSign(CertSign& certVisitSign); + DLL_EXPORT static bool GetCertsChain(CertChain& certsChain, CertSign& certVisitSign); + DLL_EXPORT static bool CertVerify(X509* cert, const X509* issuerCert); DLL_EXPORT static bool CheckAsn1TimeIsValid(const ASN1_TIME* asn1Time); DLL_EXPORT static bool CheckAsn1TypeIsValid(const ASN1_TYPE* asn1Type); + DLL_EXPORT static bool GetSubjectFromX509(const X509* cert, std::string& subject); + DLL_EXPORT static bool GetIssuerFromX509(const X509* cert, std::string& issuer); + DLL_EXPORT static bool GetSerialNumberFromX509(const X509* cert, int64_t& certNumber); + DLL_EXPORT static bool GetIssuerFromX509Crl(const X509_CRL* crl, std::string& issuer); + DLL_EXPORT static bool VerifyCertChainPeriodOfValidity(CertChain& certsChain, + const ASN1_TYPE* signTime); private: - static const uint32_t MIN_CERT_CHAIN_LEN_NEED_VERIFY_CRL; - static const int32_t OPENSSL_READ_CRL_MAX_TIME; static const int32_t OPENSSL_READ_CRL_LEN_EACH_TIME; static const int32_t BASE64_ENCODE_LEN_OF_EACH_GROUP_DATA; static const int32_t BASE64_ENCODE_PACKET_LEN; + static const uint32_t MIN_CERT_CHAIN_LEN_NEED_VERIFY_CRL; + static const int32_t OPENSSL_READ_CRL_MAX_TIME; }; } // namespace SignatureTools } // namespace OHOS diff --git a/hapsigntool_cpp/utils/src/hap_signer_block_utils.cpp b/hapsigntool_cpp/utils/src/hap_signer_block_utils.cpp index c449d49f..c5600efc 100644 --- a/hapsigntool_cpp/utils/src/hap_signer_block_utils.cpp +++ b/hapsigntool_cpp/utils/src/hap_signer_block_utils.cpp @@ -156,20 +156,20 @@ bool HapSignerBlockUtils::FindEocdInSearchBuffer(ByteBuffer& searchBuffer, int& return false; } - int32_t currentOffset = searchBufferSize - ZIP_EOCD_SEG_MIN_SIZE; - while (currentOffset >= 0) { + int32_t calcCurrentOffset = searchBufferSize - ZIP_EOCD_SEG_MIN_SIZE; + while (calcCurrentOffset >= 0) { int32_t hapEocdSegmentFlag; - if (searchBuffer.GetInt32(currentOffset, hapEocdSegmentFlag) && + if (searchBuffer.GetInt32(calcCurrentOffset, hapEocdSegmentFlag) && (hapEocdSegmentFlag == ZIP_EOCD_SEGMENT_FLAG)) { unsigned short commentLength; - int32_t expectedCommentLength = searchBufferSize - ZIP_EOCD_SEG_MIN_SIZE - currentOffset; - if (searchBuffer.GetUInt16(currentOffset + ZIP_EOCD_COMMENT_LENGTH_OFFSET, commentLength) && + int32_t expectedCommentLength = searchBufferSize - ZIP_EOCD_SEG_MIN_SIZE - calcCurrentOffset; + if (searchBuffer.GetUInt16(calcCurrentOffset + ZIP_EOCD_COMMENT_LENGTH_OFFSET, commentLength) && static_cast(commentLength) == expectedCommentLength) { - offset = currentOffset; + offset = calcCurrentOffset; return true; } } - currentOffset--; + calcCurrentOffset--; } return false; } @@ -411,10 +411,10 @@ bool HapSignerBlockUtils::ClassifyHapSubSigningBlock(SignatureInfo& signInfo, case PROOF_ROTATION_BLOB: case PROPERTY_BLOB: { - OptionalBlock optionalBlock; - optionalBlock.optionalType = static_cast(type); - optionalBlock.optionalBlockValue = subBlock; - signInfo.optionBlocks.push_back(optionalBlock); + OptionalBlock optionalBlockObject; + optionalBlockObject.optionalType = static_cast(type); + optionalBlockObject.optionalBlockValue = subBlock; + signInfo.optionBlocks.push_back(optionalBlockObject); ret = true; break; } @@ -536,32 +536,32 @@ bool HapSignerBlockUtils::ComputeDigestsForEachChunk(const DigestParameter& dige result.PutInt32(1, chunkCount); int32_t chunkIndex = 0; - unsigned char out[EVP_MAX_MD_SIZE]; - unsigned char chunkContentPrefix[ZIP_CHUNK_DIGEST_PRIFIX_LEN] = { + unsigned char outBlock[EVP_MAX_MD_SIZE]; + unsigned char zipChunkContentPrefix[ZIP_CHUNK_DIGEST_PRIFIX_LEN] = { (unsigned char)ZIP_SECOND_LEVEL_CHUNK_PREFIX, 0, 0, 0, 0}; - int32_t offset = ZIP_CHUNK_DIGEST_PRIFIX_LEN; + int32_t zipOffset = ZIP_CHUNK_DIGEST_PRIFIX_LEN; for (int32_t i = 0; i < len; i++) { while (contents[i]->HasRemaining()) { - int32_t chunkSize = std::min(contents[i]->Remaining(), CHUNK_SIZE); - if (!InitDigestPrefix(digestParam, chunkContentPrefix, chunkSize)) { + int32_t digestChunkSize = std::min(contents[i]->Remaining(), CHUNK_SIZE); + if (!InitDigestPrefix(digestParam, zipChunkContentPrefix, digestChunkSize)) { SIGNATURE_TOOLS_LOGE("InitDigestPrefix failed"); return false; } - if (!contents[i]->ReadDataAndDigestUpdate(digestParam, chunkSize)) { + if (!contents[i]->ReadDataAndDigestUpdate(digestParam, digestChunkSize)) { SIGNATURE_TOOLS_LOGE("Copy Partial Buffer failed, count: %d", chunkIndex); return false; } - int32_t digestLen = VerifyHapOpensslUtils::GetDigest(digestParam, out); + int32_t digestLen = VerifyHapOpensslUtils::GetDigest(digestParam, outBlock); if (digestLen != digestParam.digestOutputSizeBytes) { SIGNATURE_TOOLS_LOGE("GetDigest failed len: %d digestSizeBytes: %d", digestLen, digestParam.digestOutputSizeBytes); return false; } - result.PutData(offset, reinterpret_cast(out), digestParam.digestOutputSizeBytes); - offset += digestLen; + result.PutData(zipOffset, reinterpret_cast(outBlock), digestParam.digestOutputSizeBytes); + zipOffset += digestLen; chunkIndex++; } } @@ -573,8 +573,8 @@ DigestParameter HapSignerBlockUtils::GetDigestParameter(int32_t nId) DigestParameter digestParam; digestParam.digestOutputSizeBytes = VerifyHapOpensslUtils::GetDigestAlgorithmOutputSizeBytes(nId); digestParam.md = EVP_get_digestbynid(nId); - digestParam.ptrCtx = EVP_MD_CTX_create(); - EVP_MD_CTX_init(digestParam.ptrCtx); + digestParam.ctxPtr = EVP_MD_CTX_create(); + EVP_MD_CTX_init(digestParam.ctxPtr); return digestParam; } @@ -616,49 +616,49 @@ bool HapSignerBlockUtils::InitDigestPrefix(const DigestParameter& digestParam, int64_t HapSignerBlockUtils::CreatTestZipFile(const std::string& pathFile, SignatureInfo& signInfo) { - std::ofstream hapFile(pathFile.c_str(), std::ios::binary | std::ios::out | std::ios::trunc); - if (!hapFile.is_open()) { + std::ofstream hapFileInfo(pathFile.c_str(), std::ios::binary | std::ios::out | std::ios::trunc); + if (!hapFileInfo.is_open()) { return 0; } char block[TEST_FILE_BLOCK_LENGTH] = {0}; /* input contents of ZIP entries */ - hapFile.seekp(0, std::ios_base::beg); - hapFile.write(block, sizeof(block)); + hapFileInfo.seekp(0, std::ios_base::beg); + hapFileInfo.write(block, sizeof(block)); /* input sign block */ HapSubSignBlockHead signBlob; HapSubSignBlockHead profileBlob; HapSubSignBlockHead propertyBlob; CreateHapSubSignBlockHead(signBlob, profileBlob, propertyBlob); - hapFile.write(reinterpret_cast(&signBlob), sizeof(signBlob)); - hapFile.write(reinterpret_cast(&profileBlob), sizeof(profileBlob)); - hapFile.write(reinterpret_cast(&propertyBlob), sizeof(propertyBlob)); + hapFileInfo.write(reinterpret_cast(&signBlob), sizeof(signBlob)); + hapFileInfo.write(reinterpret_cast(&profileBlob), sizeof(profileBlob)); + hapFileInfo.write(reinterpret_cast(&propertyBlob), sizeof(propertyBlob)); for (int32_t i = 0; i < TEST_FILE_BLOCK_COUNT; i++) { - hapFile.write(block, sizeof(block)); + hapFileInfo.write(block, sizeof(block)); } int32_t blockCount = TEST_FILE_BLOCK_COUNT; - hapFile.write(reinterpret_cast(&blockCount), sizeof(blockCount)); + hapFileInfo.write(reinterpret_cast(&blockCount), sizeof(blockCount)); int64_t signBlockSize = (sizeof(HapSubSignBlockHead) + sizeof(block)) * TEST_FILE_BLOCK_COUNT + HapSignerBlockUtils::ZIP_HEAD_OF_SIGNING_BLOCK_LENGTH; - hapFile.write(reinterpret_cast(&signBlockSize), sizeof(signBlockSize)); + hapFileInfo.write(reinterpret_cast(&signBlockSize), sizeof(signBlockSize)); int64_t magic = HapSignerBlockUtils::HAP_SIG_BLOCK_MAGIC_LOW_OLD; - hapFile.write(reinterpret_cast(&magic), sizeof(magic)); + hapFileInfo.write(reinterpret_cast(&magic), sizeof(magic)); magic = HapSignerBlockUtils::HAP_SIG_BLOCK_MAGIC_HIGH_OLD; - hapFile.write(reinterpret_cast(&magic), sizeof(magic)); + hapFileInfo.write(reinterpret_cast(&magic), sizeof(magic)); int32_t version = 1; - hapFile.write(reinterpret_cast(&version), sizeof(version)); + hapFileInfo.write(reinterpret_cast(&version), sizeof(version)); /* input central direction */ - hapFile.write(block, sizeof(block)); + hapFileInfo.write(block, sizeof(block)); /* input end of central direction */ int32_t zidEocdSign = HapSignerBlockUtils::ZIP_EOCD_SEGMENT_FLAG; - hapFile.write(reinterpret_cast(&zidEocdSign), sizeof(zidEocdSign)); - hapFile.write(reinterpret_cast(&magic), sizeof(magic)); + hapFileInfo.write(reinterpret_cast(&zidEocdSign), sizeof(zidEocdSign)); + hapFileInfo.write(reinterpret_cast(&magic), sizeof(magic)); uint32_t centralDirLen = sizeof(block); - hapFile.write(reinterpret_cast(¢ralDirLen), sizeof(centralDirLen)); + hapFileInfo.write(reinterpret_cast(¢ralDirLen), sizeof(centralDirLen)); uint32_t centralDirOffset = TEST_FILE_BLOCK_LENGTH + signBlockSize; - hapFile.write(reinterpret_cast(¢ralDirOffset), sizeof(centralDirOffset)); + hapFileInfo.write(reinterpret_cast(¢ralDirOffset), sizeof(centralDirOffset)); short eocdCommentLen = 0; - hapFile.write(reinterpret_cast(&eocdCommentLen), sizeof(eocdCommentLen)); - hapFile.close(); + hapFileInfo.write(reinterpret_cast(&eocdCommentLen), sizeof(eocdCommentLen)); + hapFileInfo.close(); signInfo.hapCentralDirOffset = centralDirOffset; signInfo.hapEocdOffset = centralDirOffset + centralDirLen; signInfo.hapSignatureBlock.SetCapacity(TEST_FILE_BLOCK_LENGTH); @@ -675,12 +675,12 @@ void HapSignerBlockUtils::CreateHapSubSignBlockHead(HapSubSignBlockHead& signBlo signBlob.type = HAP_SIGN_BLOB; signBlob.length = TEST_FILE_BLOCK_LENGTH; signBlob.offset = sizeof(HapSubSignBlockHead) * TEST_FILE_BLOCK_COUNT; - profileBlob.type = PROFILE_BLOB; - profileBlob.length = TEST_FILE_BLOCK_LENGTH; - profileBlob.offset = signBlob.offset + signBlob.length; propertyBlob.type = PROPERTY_BLOB; propertyBlob.length = TEST_FILE_BLOCK_LENGTH; propertyBlob.offset = profileBlob.offset + profileBlob.length; + profileBlob.type = PROFILE_BLOB; + profileBlob.length = TEST_FILE_BLOCK_LENGTH; + profileBlob.offset = signBlob.offset + signBlob.length; } } // namespace SignatureTools } // namespace OHOS \ No newline at end of file diff --git a/hapsigntool_cpp/utils/src/hash_utils.cpp b/hapsigntool_cpp/utils/src/hash_utils.cpp index 9f7434f4..ae01abf7 100644 --- a/hapsigntool_cpp/utils/src/hash_utils.cpp +++ b/hapsigntool_cpp/utils/src/hash_utils.cpp @@ -92,12 +92,12 @@ std::vector HashUtils::GetFileDigest(const std::string& inputFile, const return std::vector(); } - DigestUtils digestUtils(HASH_SHA256); - for (const auto& item : hashMap) { - std::string str(item.second.begin(), item.second.end()); - digestUtils.AddData(str); + DigestUtils fileDigestUtils(HASH_SHA256); + for (const auto& hashMapItem : hashMap) { + std::string str(hashMapItem.second.begin(), hashMapItem.second.end()); + fileDigestUtils.AddData(str); } - std::string digest = digestUtils.Result(DigestUtils::Type::BINARY); + std::string digest = fileDigestUtils.Result(DigestUtils::Type::BINARY); for (std::string::size_type i = 0; i < digest.size(); i++) { result.push_back(digest[i]); } diff --git a/hapsigntool_cpp/utils/src/key_store_helper.cpp b/hapsigntool_cpp/utils/src/key_store_helper.cpp index b5653863..6e86a666 100644 --- a/hapsigntool_cpp/utils/src/key_store_helper.cpp +++ b/hapsigntool_cpp/utils/src/key_store_helper.cpp @@ -608,13 +608,13 @@ void KeyStoreHelper::SetNidMac(int& nidKey, int& iter, int& macStatus) } } -int KeyStoreHelper::SetCertPkcs12(X509* cert, PKCS12_SAFEBAG* bag, STACK_OF(PKCS12_SAFEBAG)* bags, +int KeyStoreHelper::SetCertPkcs12(X509* cert, PKCS12_SAFEBAG* bag, STACK_OF(PKCS12_SAFEBAG)* certBags, unsigned char* keyId, unsigned int keyIdLen, const char* name, STACK_OF(PKCS7)** safes, int certNid, int iter, const char* keyStorePwd) { if (cert) { - bag = PKCS12_add_cert(&bags, cert); + bag = PKCS12_add_cert(&certBags, cert); if (name && !PKCS12_add_friendlyname(bag, name, -1)) { goto err; } @@ -624,25 +624,25 @@ int KeyStoreHelper::SetCertPkcs12(X509* cert, PKCS12_SAFEBAG* bag, STACK_OF(PKCS } } - if (bags && !PKCS12_add_safe(safes, bags, certNid, iter, keyStorePwd)) { + if (certBags && !PKCS12_add_safe(safes, certBags, certNid, iter, keyStorePwd)) { goto err; } - sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); - bags = NULL; + sk_PKCS12_SAFEBAG_pop_free(certBags, PKCS12_SAFEBAG_free); + certBags = nullptr; return RET_OK; err: - sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); - bags = NULL; + sk_PKCS12_SAFEBAG_pop_free(certBags, PKCS12_SAFEBAG_free); + certBags = nullptr; return RET_FAILED; } -int KeyStoreHelper::SetPkeyPkcs12(EVP_PKEY* pkey, PKCS12_SAFEBAG* bag, STACK_OF(PKCS12_SAFEBAG)* bags, +int KeyStoreHelper::SetPkeyPkcs12(EVP_PKEY* pkey, PKCS12_SAFEBAG* bag, STACK_OF(PKCS12_SAFEBAG)* keyBags, const char* name, STACK_OF(PKCS7)** safes, int iter, const char* keyPwd, int keyType, int keyNid, unsigned char* keyId, unsigned int keyIdLen) { if (pkey) { - bag = PKCS12_add_key(&bags, pkey, keyType, iter, keyNid, keyPwd); + bag = PKCS12_add_key(&keyBags, pkey, keyType, iter, keyNid, keyPwd); if (!bag) { return RET_FAILED; } @@ -663,16 +663,16 @@ int KeyStoreHelper::SetPkeyPkcs12(EVP_PKEY* pkey, PKCS12_SAFEBAG* bag, STACK_OF( goto err; } } - if (bags && !PKCS12_add_safe(safes, bags, -1, 0, NULL)) { + if (keyBags && !PKCS12_add_safe(safes, keyBags, -1, 0, NULL)) { goto err; } - sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); - bags = NULL; + sk_PKCS12_SAFEBAG_pop_free(keyBags, PKCS12_SAFEBAG_free); + keyBags = nullptr; return RET_OK; err: - sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); - bags = NULL; + sk_PKCS12_SAFEBAG_pop_free(keyBags, PKCS12_SAFEBAG_free); + keyBags = nullptr; return RET_FAILED; } diff --git a/hapsigntool_cpp/utils/src/verify_cert_openssl_utils.cpp b/hapsigntool_cpp/utils/src/verify_cert_openssl_utils.cpp index dd703042..24a5bbc5 100644 --- a/hapsigntool_cpp/utils/src/verify_cert_openssl_utils.cpp +++ b/hapsigntool_cpp/utils/src/verify_cert_openssl_utils.cpp @@ -261,17 +261,17 @@ void VerifyCertOpensslUtils::WriteX509CrlToStream(std::ofstream& crlFile, X509_C crlFile.seekp(posEnd); } -void VerifyCertOpensslUtils::GenerateCertSignFromCertStack(STACK_OF(X509)* certs, CertSign& certVisitSign) +void VerifyCertOpensslUtils::GenerateCertSignFromCertStack(STACK_OF(X509)* stackCerts, CertSign& certVisitSign) { - if (certs == nullptr) { + if (stackCerts == nullptr) { return; } - for (int32_t i = 0; i < sk_X509_num(certs); i++) { - X509* cert = sk_X509_value(certs, i); - if (cert == nullptr) { + for (int32_t i = 0; i < sk_X509_num(stackCerts); i++) { + X509* x509Cert = sk_X509_value(stackCerts, i); + if (x509Cert == nullptr) { continue; } - certVisitSign[cert] = false; + certVisitSign[x509Cert] = false; } } @@ -320,15 +320,15 @@ X509* VerifyCertOpensslUtils::FindCertOfIssuer(X509* cert, CertSign& certVisitSi SIGNATURE_TOOLS_LOGE("input is invalid"); return nullptr; } - X509_NAME* signCertIssuer = X509_get_issuer_name(cert); + X509_NAME* signCertIssuerName = X509_get_issuer_name(cert); for (auto certPair : certVisitSign) { if (certPair.second) { continue; } X509* issuerCert = certPair.first; - X509_NAME* issuerCertSubject = X509_get_subject_name(issuerCert); + X509_NAME* issuerCertSubjectName = X509_get_subject_name(issuerCert); /* verify sign and issuer */ - if (X509NameCompare(issuerCertSubject, signCertIssuer) && + if (X509NameCompare(issuerCertSubjectName, signCertIssuerName) && CertVerify(cert, issuerCert)) { return issuerCert; } @@ -445,15 +445,15 @@ X509_CRL* VerifyCertOpensslUtils::GetCrlBySignedCertIssuer(STACK_OF(X509_CRL)* c if (crls == nullptr || cert == nullptr) { return nullptr; } - X509_NAME* certIssuer = X509_get_issuer_name(cert); + X509_NAME* certIssuerName = X509_get_issuer_name(cert); for (int32_t i = 0; i < sk_X509_CRL_num(crls); i++) { - X509_CRL* crl = sk_X509_CRL_value(crls, i); - if (crl == nullptr) { + X509_CRL* x509Crl = sk_X509_CRL_value(crls, i); + if (x509Crl == nullptr) { continue; } - X509_NAME* crlIssuer = X509_CRL_get_issuer(crl); - if (X509NameCompare(crlIssuer, certIssuer)) { - return crl; + X509_NAME* crlIssuer = X509_CRL_get_issuer(x509Crl); + if (X509NameCompare(crlIssuer, certIssuerName)) { + return x509Crl; } } return nullptr; @@ -518,20 +518,20 @@ bool VerifyCertOpensslUtils::GetIssuerFromX509Crl(const X509_CRL* crl, std::stri return true; } -std::string VerifyCertOpensslUtils::GetDnToString(X509_NAME* name) +std::string VerifyCertOpensslUtils::GetDnToString(X509_NAME* x509Name) { - if (name == nullptr) { + if (x509Name == nullptr) { return ""; } - std::string countryName; - GetTextFromX509Name(name, NID_countryName, countryName); + std::string countryNameString; + GetTextFromX509Name(x509Name, NID_countryName, countryNameString); std::string organizationName; - GetTextFromX509Name(name, NID_organizationName, organizationName); + GetTextFromX509Name(x509Name, NID_organizationName, organizationName); std::string organizationalUnitName; - GetTextFromX509Name(name, NID_organizationalUnitName, organizationalUnitName); + GetTextFromX509Name(x509Name, NID_organizationalUnitName, organizationalUnitName); std::string commonName; - GetTextFromX509Name(name, NID_commonName, commonName); - return "C=" + countryName + ", O=" + organizationName + ", OU=" + organizationalUnitName + + GetTextFromX509Name(x509Name, NID_commonName, commonName); + return "C=" + countryNameString + ", O=" + organizationName + ", OU=" + organizationalUnitName + ", CN=" + commonName; } diff --git a/hapsigntool_cpp/utils/src/verify_hap_openssl_utils.cpp b/hapsigntool_cpp/utils/src/verify_hap_openssl_utils.cpp index 28a16ed8..dedc3c4b 100644 --- a/hapsigntool_cpp/utils/src/verify_hap_openssl_utils.cpp +++ b/hapsigntool_cpp/utils/src/verify_hap_openssl_utils.cpp @@ -95,11 +95,11 @@ bool VerifyHapOpensslUtils::GetCertChains(PKCS7* p7, Pkcs7Context& pkcs7Context) return false; } CertChain certChain; - pkcs7Context.certChains.push_back(certChain); - pkcs7Context.certChains[i].push_back(X509_dup(cert)); + pkcs7Context.certChain.push_back(certChain); + pkcs7Context.certChain[i].push_back(X509_dup(cert)); VerifyCertOpensslUtils::ClearCertVisitSign(certVisitSign); certVisitSign[cert] = true; - if (!VerifyCertChain(pkcs7Context.certChains[i], p7, signInfo, pkcs7Context, certVisitSign)) { + if (!VerifyCertChain(pkcs7Context.certChain[i], p7, signInfo, pkcs7Context, certVisitSign)) { SIGNATURE_TOOLS_LOGE("verify %dst certchain failed", i); return false; } @@ -199,7 +199,7 @@ bool VerifyHapOpensslUtils::VerifySignInfo(STACK_OF(PKCS7_SIGNER_INFO)* signerIn return false; } /* GET X509 certificate */ - X509* cert = pkcs7Context.certChains[signInfoNum][0]; + X509* cert = pkcs7Context.certChain[signInfoNum][0]; if (PKCS7_signatureVerify(p7Bio, pkcs7Context.p7, signInfo, cert) <= 0) { SIGNATURE_TOOLS_LOGE("PKCS7_signatureVerify %dst signInfo failed", signInfoNum); @@ -309,7 +309,7 @@ bool VerifyHapOpensslUtils::CheckDigestParameter(const DigestParameter& digestPa SIGNATURE_TOOLS_LOGE("md is nullptr"); return false; } - if (digestParameter.ptrCtx == nullptr) { + if (digestParameter.ctxPtr == nullptr) { SIGNATURE_TOOLS_LOGE("ptrCtx is nullptr"); return false; } @@ -321,7 +321,7 @@ bool VerifyHapOpensslUtils::DigestInit(const DigestParameter& digestParameter) if (!CheckDigestParameter(digestParameter)) { return false; } - if (EVP_DigestInit(digestParameter.ptrCtx, digestParameter.md) <= 0) { + if (EVP_DigestInit(digestParameter.ctxPtr, digestParameter.md) <= 0) { GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("EVP_DigestInit failed"); return false; @@ -340,7 +340,7 @@ bool VerifyHapOpensslUtils::DigestUpdate(const DigestParameter& digestParameter, if (!CheckDigestParameter(digestParameter)) { return false; } - if (EVP_DigestUpdate(digestParameter.ptrCtx, content, len) <= 0) { + if (EVP_DigestUpdate(digestParameter.ctxPtr, content, len) <= 0) { GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("EVP_DigestUpdate chunk failed"); return false; @@ -355,7 +355,7 @@ int32_t VerifyHapOpensslUtils::GetDigest(const DigestParameter& digestParameter, if (!CheckDigestParameter(digestParameter)) { return outLen; } - if (EVP_DigestFinal(digestParameter.ptrCtx, out, &outLen) <= 0) { + if (EVP_DigestFinal(digestParameter.ctxPtr, out, &outLen) <= 0) { GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("EVP_DigestFinal failed"); outLen = 0; @@ -374,30 +374,30 @@ int32_t VerifyHapOpensslUtils::GetDigest(const ByteBuffer& chunk, SIGNATURE_TOOLS_LOGE("md is nullprt"); return outLen; } - if (digestParameter.ptrCtx == nullptr) { + if (digestParameter.ctxPtr == nullptr) { SIGNATURE_TOOLS_LOGE("ptrCtx is nullprt"); return outLen; } - if (EVP_DigestInit(digestParameter.ptrCtx, digestParameter.md) <= 0) { + if (EVP_DigestInit(digestParameter.ctxPtr, digestParameter.md) <= 0) { GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("EVP_DigestInit failed"); return outLen; } - if (EVP_DigestUpdate(digestParameter.ptrCtx, chunk.GetBufferPtr(), chunkLen) <= 0) { + if (EVP_DigestUpdate(digestParameter.ctxPtr, chunk.GetBufferPtr(), chunkLen) <= 0) { GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("EVP_DigestUpdate chunk failed"); return outLen; } for (int32_t i = 0; i < static_cast(optionalBlocks.size()); i++) { chunkLen = optionalBlocks[i].optionalBlockValue.GetCapacity(); - if (EVP_DigestUpdate(digestParameter.ptrCtx, optionalBlocks[i].optionalBlockValue.GetBufferPtr(), + if (EVP_DigestUpdate(digestParameter.ctxPtr, optionalBlocks[i].optionalBlockValue.GetBufferPtr(), chunkLen) <= 0) { GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("EVP_DigestUpdate %dst optional block failed", i); return outLen; } } - if (EVP_DigestFinal(digestParameter.ptrCtx, out, &outLen) <= 0) { + if (EVP_DigestFinal(digestParameter.ctxPtr, out, &outLen) <= 0) { GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("EVP_DigestFinal failed"); outLen = 0; diff --git a/hapsigntool_cpp/zip/include/central_directory.h b/hapsigntool_cpp/zip/include/central_directory.h index 66fc961a..14ece622 100644 --- a/hapsigntool_cpp/zip/include/central_directory.h +++ b/hapsigntool_cpp/zip/include/central_directory.h @@ -70,13 +70,17 @@ public: void SetVersionExtra(short versionExtra); + short GetMethod(); + + void SetMethod(short method); + short GetFlag(); void SetFlag(short flag); - short GetMethod(); + int GetCrc32(); - void SetMethod(short method); + void SetCrc32(int crc32); short GetLastTime(); @@ -86,10 +90,6 @@ public: void SetLastDate(short lastDate); - int GetCrc32(); - - void SetCrc32(int crc32); - uint32_t GetCompressedSize(); void SetCompressedSize(uint32_t compressedSize); @@ -98,22 +98,22 @@ public: void SetUnCompressedSize(uint32_t unCompressedSize); - uint16_t GetFileNameLength(); - - void SetFileNameLength(uint16_t fileNameLength); - uint16_t GetExtraLength(); void SetExtraLength(uint16_t extraLength); - uint16_t GetCommentLength(); + uint16_t GetFileNameLength(); - void SetCommentLength(uint16_t commentLength); + void SetFileNameLength(uint16_t fileNameLength); uint16_t GetDiskNumStart(); void SetDiskNumStart(uint16_t diskNumStart); + uint16_t GetCommentLength(); + + void SetCommentLength(uint16_t commentLength); + short GetInternalFile(); void SetInternalFile(short internalFile); diff --git a/hapsigntool_cpp/zip/src/endof_central_directory.cpp b/hapsigntool_cpp/zip/src/endof_central_directory.cpp index d869e656..45ef47eb 100644 --- a/hapsigntool_cpp/zip/src/endof_central_directory.cpp +++ b/hapsigntool_cpp/zip/src/endof_central_directory.cpp @@ -15,7 +15,6 @@ #include -#include "byte_buffer.h" #include "endof_central_directory.h" #include "signature_tools_log.h" -- Gitee From c3306b59876e3c6569fd020dab9c805894ff083f Mon Sep 17 00:00:00 2001 From: zhanzeyi Date: Thu, 18 Jul 2024 15:04:18 +0800 Subject: [PATCH 3/8] fix code review Signed-off-by: zhanzeyi --- hapsigntool_cpp/api/include/cert_tools.h | 1 + hapsigntool_cpp/api/src/cert_tools.cpp | 23 + .../api/src/sign_tool_service_impl.cpp | 7 +- hapsigntool_cpp/cmd/include/cmd_util.h | 6 +- hapsigntool_cpp/cmd/include/options.h | 16 +- hapsigntool_cpp/cmd/include/params.h | 14 +- hapsigntool_cpp/cmd/include/params_run_tool.h | 4 +- .../cmd/include/params_trust_list.h | 5 +- hapsigntool_cpp/cmd/src/cmd_util.cpp | 45 +- hapsigntool_cpp/cmd/src/options.cpp | 20 +- hapsigntool_cpp/cmd/src/params.cpp | 12 +- hapsigntool_cpp/cmd/src/params_run_tool.cpp | 28 +- hapsigntool_cpp/cmd/src/params_trust_list.cpp | 14 +- .../datastructure/include/code_sign_block.h | 12 +- .../include/code_sign_block_header.h | 4 +- .../datastructure/include/elf_sign_block.h | 2 +- .../include/fs_verity_info_segment.h | 4 +- .../datastructure/include/hap_info_segment.h | 6 +- .../include/merkle_tree_extension.h | 2 +- .../include/native_lib_info_segment.h | 16 +- .../datastructure/include/sign_info.h | 10 +- .../include/unzip_handle_param.h | 6 +- .../datastructure/src/code_sign_block.cpp | 12 +- .../src/code_sign_block_header.cpp | 4 +- .../datastructure/src/elf_sign_block.cpp | 2 +- .../src/fs_verity_info_segment.cpp | 4 +- .../datastructure/src/hap_info_segment.cpp | 6 +- .../src/merkle_tree_extension.cpp | 4 +- .../src/native_lib_info_segment.cpp | 15 +- .../datastructure/src/sign_info.cpp | 12 +- .../datastructure/src/unzip_handle_param.cpp | 8 +- .../include/fs_verity_descriptor_with_sign.h | 2 +- .../src/fs_verity_descriptor_with_sign.cpp | 2 +- .../sign/include/bc_signeddata_generator.h | 2 +- .../codesigning/sign/include/code_signing.h | 18 +- .../sign/src/bc_signeddata_generator.cpp | 3 +- .../codesigning/sign/src/code_signing.cpp | 30 +- .../sign/src/verify_code_signature.cpp | 2 +- .../hap/entity/include/hw_block_data.h | 6 +- .../hap/entity/include/hw_block_head.h | 4 +- .../hap/entity/include/hw_sign_head.h | 4 +- .../hap/entity/include/sign_block_data.h | 10 +- .../hap/entity/include/sign_block_info.h | 8 +- .../hap/entity/include/sign_content_info.h | 8 +- .../include/signature_algorithm_helper.h | 6 +- .../hap/entity/include/signing_block.h | 6 +- .../hap/entity/src/hw_block_data.cpp | 6 +- .../hap/entity/src/hw_block_head.cpp | 4 +- .../hap/entity/src/hw_sign_head.cpp | 4 +- .../hap/entity/src/sign_block_data.cpp | 10 +- .../hap/entity/src/sign_block_info.cpp | 8 +- .../hap/entity/src/sign_content_info.cpp | 8 +- .../entity/src/signature_algorithm_helper.cpp | 8 +- .../hap/entity/src/signing_block.cpp | 6 +- .../hap/provider/include/sign_provider.h | 6 +- .../hap/provider/src/local_sign_provider.cpp | 18 +- .../hap/provider/src/remote_sign_provider.cpp | 19 +- .../hap/provider/src/sign_provider.cpp | 28 +- .../hap/sign/include/bc_pkcs7_generator.h | 2 +- hapsigntool_cpp/hap/sign/include/sign_elf.h | 24 +- hapsigntool_cpp/hap/sign/include/sign_hap.h | 1 - .../hap/sign/src/bc_pkcs7_generator.cpp | 2 +- hapsigntool_cpp/hap/sign/src/sign_elf.cpp | 18 +- hapsigntool_cpp/hap/signature_tools_hap.gni | 1 - .../hap/verify/include/hap_verify_result.h | 94 ----- .../hap/verify/include/verify_bin.h | 2 +- .../hap/verify/include/verify_elf.h | 5 +- .../hap/verify/include/verify_hap.h | 49 ++- .../hap/verify/src/hap_verify_result.cpp | 108 ----- hapsigntool_cpp/hap/verify/src/verify_bin.cpp | 18 +- hapsigntool_cpp/hap/verify/src/verify_elf.cpp | 36 +- hapsigntool_cpp/hap/verify/src/verify_hap.cpp | 394 +++++------------- hapsigntool_cpp/profile/include/pkcs7_data.h | 6 +- .../profile/include/profile_sign_tool.h | 2 +- .../profile/include/profile_verify.h | 1 - hapsigntool_cpp/profile/src/pkcs7_data.cpp | 6 +- .../profile/src/profile_sign_tool.cpp | 2 +- .../profile/src/profile_verify.cpp | 41 +- .../utils/include/hap_signer_block_utils.h | 1 - .../utils/include/signature_info.h | 6 +- .../utils/include/verify_cert_openssl_utils.h | 16 +- .../utils/include/verify_hap_openssl_utils.h | 15 +- .../utils/src/hap_signer_block_utils.cpp | 4 + .../utils/src/verify_cert_openssl_utils.cpp | 256 ------------ .../utils/src/verify_hap_openssl_utils.cpp | 90 ++-- 85 files changed, 522 insertions(+), 1238 deletions(-) delete mode 100644 hapsigntool_cpp/hap/verify/include/hap_verify_result.h delete mode 100644 hapsigntool_cpp/hap/verify/src/hap_verify_result.cpp diff --git a/hapsigntool_cpp/api/include/cert_tools.h b/hapsigntool_cpp/api/include/cert_tools.h index f95a6add..bf34fded 100644 --- a/hapsigntool_cpp/api/include/cert_tools.h +++ b/hapsigntool_cpp/api/include/cert_tools.h @@ -63,6 +63,7 @@ public: static bool SetExpandedInformation(X509* cert, Options* options); static bool SetPubkeyAndSignCert(X509* cert, X509_REQ* issuercsr, X509_REQ* certReq, EVP_PKEY* keyPair, Options* options); + static bool PrintCertChainToCmd(std::vector& certChain); CertTools() = default; ~CertTools() = default; }; diff --git a/hapsigntool_cpp/api/src/cert_tools.cpp b/hapsigntool_cpp/api/src/cert_tools.cpp index 87b4815e..24c32321 100644 --- a/hapsigntool_cpp/api/src/cert_tools.cpp +++ b/hapsigntool_cpp/api/src/cert_tools.cpp @@ -859,6 +859,29 @@ err: return nullptr; } +bool CertTools::PrintCertChainToCmd(std::vector& certChain) +{ + BIO* outFd = BIO_new_fp(stdout, BIO_NOCLOSE); + if (!outFd) { + PrintErrorNumberMsg("IO_ERROR", IO_ERROR, "The stdout stream may have errors"); + return false; + } + uint64_t format = XN_FLAG_SEP_COMMA_PLUS; // Print according to RFC2253 + uint64_t content = X509_FLAG_NO_EXTENSIONS | X509_FLAG_NO_ATTRIBUTES | X509_FLAG_NO_HEADER | X509_FLAG_NO_SIGDUMP; + int num = 0; + for (auto& cert : certChain) { + PrintMsg("+++++++++++++++++++++++++++++++++certificate #" + std::to_string(num) + "+++++++++++++++++++++++++++++++++++++"); + if (!X509_print_ex(outFd, cert, format, content)) { + VerifyHapOpensslUtils::GetOpensslErrorMessage(); + SIGNATURE_TOOLS_LOGE("print x509 cert to cmd failed"); + BIO_free(outFd); + return false; + } + ++num; + } + BIO_free(outFd); + return true; +} } // namespace SignatureTools } // namespace OHOS diff --git a/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp b/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp index b517a36f..a1d2030b 100644 --- a/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp +++ b/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp @@ -664,10 +664,9 @@ bool SignToolServiceImpl::VerifyHapSigner(Options* option) { std::string inForm = option->GetString(ParamConstants::PARAM_IN_FORM); if (inForm == ZIP) { - HapVerifyResult hapVerifyResult; - VerifyHap hapVerifyV2; - int32_t ret = hapVerifyV2.Verify(option->GetString(Options::IN_FILE), hapVerifyResult, option); - if (ret == VERIFY_SUCCESS) { + VerifyHap hapVerify; + int32_t ret = hapVerify.Verify(option->GetString(Options::IN_FILE), option); + if (ret == RET_OK) { PrintMsg("hap verify successed!"); return true; } diff --git a/hapsigntool_cpp/cmd/include/cmd_util.h b/hapsigntool_cpp/cmd/include/cmd_util.h index ac9abcab..a8a013aa 100644 --- a/hapsigntool_cpp/cmd/include/cmd_util.h +++ b/hapsigntool_cpp/cmd/include/cmd_util.h @@ -33,13 +33,13 @@ namespace OHOS { namespace SignatureTools { class CmdUtil final { public: - static bool Convert2Params(char** args, size_t size, const ParamsSharedPtr& param); + static bool Convert2Params(char** args, const size_t size, const ParamsSharedPtr& param); static bool JudgeAlgType(const std::string& keyAlg); static bool JudgeSize(const int size); static bool JudgeSignAlgType(const std::string& signAlg); static bool VerifyType(const std::string& inputType); static bool VerifyTypes(const std::string& inputType); - static bool VerifyType(const std::string& inputtype, const std::string& supportTypes); + static bool VerifyType(const std::string& inputType, const std::string& supportTypes); static bool String2Bool(Options* options, const std::string& option); static bool UpdateParamForCheckInFile(Options* options, const std::initializer_list& inFileKeys); static bool UpdateParamForCheckOutFile(Options* options, const std::initializer_list& outFileKeys); @@ -48,7 +48,7 @@ public: private: static int GetCommandParameterKey(const char strChar, std::string& strChars, std::vector& trustList, std::string& keyStandBy); - static bool ValidAndPutParam(ParamsSharedPtr params, const std::string& key, char* value); + static bool ValidAndPutParam(const ParamsSharedPtr& params, const std::string& key, char* value); static const std::regex INTEGER_PATTERN; }; } // namespace SignatureTools diff --git a/hapsigntool_cpp/cmd/include/options.h b/hapsigntool_cpp/cmd/include/options.h index f217a612..1042990d 100644 --- a/hapsigntool_cpp/cmd/include/options.h +++ b/hapsigntool_cpp/cmd/include/options.h @@ -29,14 +29,14 @@ class Options : public std::unordered_map keys); - bool IsEmpty(std::string cs); - bool GetBool(const std::string key); + char* GetChars(const std::string& key); + std::string GetString(const std::string& key); + std::string GetString(const std::string& key, const std::string& checkStr); + int GetInt(const std::string& key); + bool Equals(const std::string& argf, const std::string& args); + bool Required(const std::initializer_list& keys); + bool IsEmpty(const std::string& cs); + bool GetBool(const std::string& key); public: /* Key alias parameter name. */ diff --git a/hapsigntool_cpp/cmd/include/params.h b/hapsigntool_cpp/cmd/include/params.h index 192dd538..95476ebb 100644 --- a/hapsigntool_cpp/cmd/include/params.h +++ b/hapsigntool_cpp/cmd/include/params.h @@ -33,16 +33,14 @@ class Params { public: static std::unordered_set InitParamField(const std::vector& paramFields); static bool GetSignatureAlgorithm(const std::string& signatureAlgorithm, SignatureAlgorithmHelper& out); - Params() = default; - virtual ~Params() = default; - virtual std::string GetMethod(); - virtual void SetMethod(const std::string& method); - virtual Options* GetOptions(); - -private: - std::shared_ptr options = std::make_shared(); + Params(); + ~Params(); + std::string GetMethod(); + void SetMethod(const std::string& method); + Options* GetOptions(); private: + Options* options; std::string method; }; diff --git a/hapsigntool_cpp/cmd/include/params_run_tool.h b/hapsigntool_cpp/cmd/include/params_run_tool.h index b8459782..b6e36981 100644 --- a/hapsigntool_cpp/cmd/include/params_run_tool.h +++ b/hapsigntool_cpp/cmd/include/params_run_tool.h @@ -32,8 +32,8 @@ class ParamsRunTool final { public: ParamsRunTool() = delete; static bool ProcessCmd(char** args, size_t size); - static bool DispatchParams(ParamsSharedPtr params, SignToolServiceImpl& api); - static bool CallGenerators(ParamsSharedPtr params, SignToolServiceImpl& api); + static bool DispatchParams(const ParamsSharedPtr& params, SignToolServiceImpl& api); + static bool CallGenerators(const ParamsSharedPtr& params, SignToolServiceImpl& api); static bool RunKeypair(Options* params, SignToolServiceImpl& api); static bool RunCa(Options* params, SignToolServiceImpl& api); static bool RunCert(Options* params, SignToolServiceImpl& api); diff --git a/hapsigntool_cpp/cmd/include/params_trust_list.h b/hapsigntool_cpp/cmd/include/params_trust_list.h index 8d3da08c..931484e3 100644 --- a/hapsigntool_cpp/cmd/include/params_trust_list.h +++ b/hapsigntool_cpp/cmd/include/params_trust_list.h @@ -22,13 +22,12 @@ #include #include #include "signature_tools_log.h" -#include "hap_verify_result.h" namespace OHOS { namespace SignatureTools { class ParamsTrustList final { public: - static ParamsTrustList* GetInstance(); + static ParamsTrustList GetInstance(); std::vector GetTrustList(const std::string& command); private: @@ -37,8 +36,6 @@ private: void GenerateTrustList(); private: - static std::unique_ptr paramTrustListInstance; - static std::mutex mtx; std::unordered_map> trustMap; }; } // namespace SignatureTools diff --git a/hapsigntool_cpp/cmd/src/cmd_util.cpp b/hapsigntool_cpp/cmd/src/cmd_util.cpp index 9e914bc8..7766e7c1 100644 --- a/hapsigntool_cpp/cmd/src/cmd_util.cpp +++ b/hapsigntool_cpp/cmd/src/cmd_util.cpp @@ -32,13 +32,14 @@ bool CmdUtil::String2Bool(Options* options, const std::string& option) } else if (val == "0" || val == "false" || val == "FALSE") { (*options)[option] = false; } else { - PrintErrorNumberMsg("COMMAND_PARAM_ERROR", COMMAND_PARAM_ERROR, val + "is not valid value for " + "-" + option); + PrintErrorNumberMsg("COMMAND_PARAM_ERROR", COMMAND_PARAM_ERROR, + val + "is not valid value for " + "-" + option); return false; } return true; } -static bool UpdateParamForVariantCertInt(ParamsSharedPtr param) +static bool UpdateParamForVariantCertInt(const ParamsSharedPtr& param) { int defaultValidity = 0; Options* options = param->GetOptions(); @@ -70,7 +71,7 @@ static bool UpdateParamForVariantCertInt(ParamsSharedPtr param) return true; } -static bool UpdateParamForVariantInt(ParamsSharedPtr param) +static bool UpdateParamForVariantInt(const ParamsSharedPtr& param) { Options* options = param->GetOptions(); // general @@ -104,7 +105,7 @@ static bool UpdateParamForVariantInt(ParamsSharedPtr param) return true; } -static bool UpdateParamForVariantBoolKeyUsage(ParamsSharedPtr param) +static bool UpdateParamForVariantBoolKeyUsage(const ParamsSharedPtr& param) { Options* options = param->GetOptions(); @@ -128,7 +129,7 @@ static bool UpdateParamForVariantBoolKeyUsage(ParamsSharedPtr param) return true; } -static bool UpdateParamForVariantBoolConstraints(ParamsSharedPtr param) +static bool UpdateParamForVariantBoolConstraints(const ParamsSharedPtr& param) { Options* options = param->GetOptions(); @@ -152,7 +153,7 @@ static bool UpdateParamForVariantBoolConstraints(ParamsSharedPtr param) return true; } -static bool UpdateParamForVariantBoolProfileSigned(ParamsSharedPtr param) +static bool UpdateParamForVariantBoolProfileSigned(const ParamsSharedPtr& param) { Options* options = param->GetOptions(); @@ -203,6 +204,7 @@ bool CmdUtil::UpdateParamForCheckOutFile(Options* options, const std::initialize if (parentPath.size() > PATH_MAX) { PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "'" + outFilePath + "' File path longer than '" + std::to_string(PATH_MAX) + "' characters"); + return false; } if (realpath(parentPath.c_str(), realFilePath) == nullptr) { PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "The '" + outFilePath + @@ -232,6 +234,7 @@ bool CmdUtil::UpdateParamForCheckInFile(Options* options, const std::initializer if (inFilePath.size() > PATH_MAX) { PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "'" + inFilePath + "' File path longer than '" + std::to_string(PATH_MAX) + "' characters"); + return false; } if (realpath(inFilePath.c_str(), realFilePath) == nullptr) { PrintErrorNumberMsg("FILE_NOT_FOUND", FILE_NOT_FOUND, "The '" + inFilePath + @@ -251,7 +254,7 @@ bool CmdUtil::UpdateParamForCheckInFile(Options* options, const std::initializer return true; } -static bool UpdateParamForCheckSignAlg(ParamsSharedPtr param) +static bool UpdateParamForCheckSignAlg(const ParamsSharedPtr& param) { // check signAlg Options* options = param->GetOptions(); @@ -265,7 +268,7 @@ static bool UpdateParamForCheckSignAlg(ParamsSharedPtr param) return true; } -static bool UpdateParamForInform(ParamsSharedPtr param) +static bool UpdateParamForInform(const ParamsSharedPtr& param) { // check sign_app verify_app inform Options* options = param->GetOptions(); @@ -285,7 +288,7 @@ static bool UpdateParamForInform(ParamsSharedPtr param) return true; } -static bool UpdateParamForOutform(ParamsSharedPtr param) +static bool UpdateParamForOutform(const ParamsSharedPtr& param) { // check generate_app_cert generate_profile_cert Options* options = param->GetOptions(); @@ -306,14 +309,14 @@ static bool UpdateParamForOutform(ParamsSharedPtr param) } //Check "remoteSign" additional parameters are required -static bool UpdateParamForCheckRemoteSignProfile(ParamsSharedPtr param) +static bool UpdateParamForCheckRemoteSignProfile(const ParamsSharedPtr& param) { Options* options = param->GetOptions(); std::set signProfileRemoteParams{ParamConstants::PARAM_REMOTE_SERVER, - ParamConstants::PARAM_REMOTE_USERNAME, - ParamConstants::PARAM_REMOTE_USERPWD, - ParamConstants::PARAM_REMOTE_ONLINEAUTHMODE, - ParamConstants::PARAM_REMOTE_SIGNERPLUGIN}; + ParamConstants::PARAM_REMOTE_USERNAME, + ParamConstants::PARAM_REMOTE_USERPWD, + ParamConstants::PARAM_REMOTE_ONLINEAUTHMODE, + ParamConstants::PARAM_REMOTE_SIGNERPLUGIN}; if (param->GetMethod() == SIGN_PROFILE && options->count(Options::MODE) && options->GetString(Options::MODE) == REMOTE_SIGN) { @@ -328,7 +331,7 @@ static bool UpdateParamForCheckRemoteSignProfile(ParamsSharedPtr param) return true; } -static bool UpdateParam(ParamsSharedPtr param) +static bool UpdateParam(const ParamsSharedPtr& param) { if (!UpdateParamForVariantInt(param)) { return false; @@ -377,12 +380,12 @@ int CmdUtil::GetCommandParameterKey(const char strChar, std::string& strChars, s return RET_OK; } -bool CmdUtil::Convert2Params(char** args, size_t size, const ParamsSharedPtr& param) +bool CmdUtil::Convert2Params(char** args, const size_t size, const ParamsSharedPtr& param) { param->SetMethod(args[1]); std::string keyStandBy = ""; bool readKey = true; - std::vector trustList = ParamsTrustList::GetInstance()->GetTrustList(args[1]); + std::vector trustList = ParamsTrustList::GetInstance().GetTrustList(args[1]); if (trustList.empty()) { return false; } @@ -416,7 +419,7 @@ bool CmdUtil::Convert2Params(char** args, size_t size, const ParamsSharedPtr& pa return true; } -bool CmdUtil::ValidAndPutParam(ParamsSharedPtr params, const std::string& key, char* value) +bool CmdUtil::ValidAndPutParam(const ParamsSharedPtr& params, const std::string& key, char* value) { std::string str = "Pwd"; bool result; @@ -523,15 +526,15 @@ bool CmdUtil::VerifyType(const std::string& inputType) return true; } -bool CmdUtil::VerifyType(const std::string& inputtype, const std::string& supportTypes) +bool CmdUtil::VerifyType(const std::string& inputType, const std::string& supportTypes) { std::string firstStr = supportTypes.substr(0, supportTypes.find_last_of(",")); std::string secondStr = supportTypes.substr(supportTypes.find_first_of(",") + 1, supportTypes.size() - supportTypes.find_first_of(",")); - if (inputtype == firstStr || inputtype == secondStr) { + if (inputType == firstStr || inputType == secondStr) { return true; } - PrintErrorNumberMsg("COMMAND_PARAM_ERROR", COMMAND_PARAM_ERROR, "Not support command param '" + inputtype + "'"); + PrintErrorNumberMsg("COMMAND_PARAM_ERROR", COMMAND_PARAM_ERROR, "Not support command param '" + inputType + "'"); return false; } diff --git a/hapsigntool_cpp/cmd/src/options.cpp b/hapsigntool_cpp/cmd/src/options.cpp index 24a98b6d..b405f27f 100644 --- a/hapsigntool_cpp/cmd/src/options.cpp +++ b/hapsigntool_cpp/cmd/src/options.cpp @@ -57,7 +57,7 @@ const std::string Options::PROOF_FILE = "outproof"; const std::string Options::PROFILE_FILE = "profileFile"; const std::string Options::PROFILE_SIGNED = "profileSigned"; -char* Options::GetChars(const std::string key) +char* Options::GetChars(const std::string& key) { if (this->count(key) == 0) { return nullptr; @@ -72,7 +72,7 @@ char* Options::GetChars(const std::string key) return *charsPtr; } -std::string Options::GetString(const std::string key) +std::string Options::GetString(const std::string& key) { if (this->count(key) == 0) { return ""; @@ -87,7 +87,7 @@ std::string Options::GetString(const std::string key) return *stringPtr; } -std::string Options::GetString(const std::string key, std::string checkStr) +std::string Options::GetString(const std::string& key, const std::string& checkStr) { if (this->count(key) == 0) { return ""; @@ -102,7 +102,7 @@ std::string Options::GetString(const std::string key, std::string checkStr) return *stringPtr; } -int Options::GetInt(const std::string key) +int Options::GetInt(const std::string& key) { if (this->count(key) == 0) { return 0; @@ -117,17 +117,17 @@ int Options::GetInt(const std::string key) return *stringPtr; } -bool Options::Equals(const std::string key1, const std::string& key2) +bool Options::Equals(const std::string& argf, const std::string& args) { - std::string ksFile = GetString(key1); - std::string iksFile = GetString(key2); + std::string ksFile = GetString(argf); + std::string iksFile = GetString(args); if (ksFile == iksFile) { return true; } return false; } -bool Options::Required(const std::initializer_list keys) +bool Options::Required(const std::initializer_list& keys) { for (auto& key : keys) { if (!this->IsEmpty(key) && !(this->find(key) != this->end())) { @@ -138,7 +138,7 @@ bool Options::Required(const std::initializer_list keys) return true; } -bool Options::IsEmpty(std::string cs) +bool Options::IsEmpty(const std::string& cs) { if (cs.empty()) { return true; @@ -146,7 +146,7 @@ bool Options::IsEmpty(std::string cs) return false; } -bool Options::GetBool(const std::string key) +bool Options::GetBool(const std::string& key) { auto value = (*this)[key]; bool* stringPtr = std::get_if(&value); diff --git a/hapsigntool_cpp/cmd/src/params.cpp b/hapsigntool_cpp/cmd/src/params.cpp index 81819176..fdbc479a 100644 --- a/hapsigntool_cpp/cmd/src/params.cpp +++ b/hapsigntool_cpp/cmd/src/params.cpp @@ -17,6 +17,16 @@ namespace OHOS { namespace SignatureTools { +Params::Params() : options(new Options) { +} + +Params::~Params() { + if (options) { + delete options; + options = NULL; + } +} + std::string Params::GetMethod() { return method; @@ -29,7 +39,7 @@ void Params::SetMethod(const std::string& method) Options* Params::GetOptions() { - return options.get(); + return options; } std::unordered_set Params::InitParamField(const std::vector& paramFields) diff --git a/hapsigntool_cpp/cmd/src/params_run_tool.cpp b/hapsigntool_cpp/cmd/src/params_run_tool.cpp index 5544b36e..23da1233 100644 --- a/hapsigntool_cpp/cmd/src/params_run_tool.cpp +++ b/hapsigntool_cpp/cmd/src/params_run_tool.cpp @@ -73,7 +73,7 @@ bool ParamsRunTool::ProcessCmd(char** args, size_t size) } PrintMsg("Start " + param->GetMethod()); SIGNATURE_TOOLS_LOGD("%s run start time ", param->GetMethod().c_str()); - if (!DispatchParams(param, *serviceApi.get())) { + if (!DispatchParams(param, *serviceApi)) { SIGNATURE_TOOLS_LOGD("%s run end time ", param->GetMethod().c_str()); PrintMsg(param->GetMethod() + " failed"); return false; @@ -84,7 +84,7 @@ bool ParamsRunTool::ProcessCmd(char** args, size_t size) return true; } -bool ParamsRunTool::CallGenerators(ParamsSharedPtr params, SignToolServiceImpl& api) +bool ParamsRunTool::CallGenerators(const ParamsSharedPtr& params, SignToolServiceImpl& api) { bool isSuccess = false; std::string method = params->GetMethod(); @@ -166,7 +166,7 @@ bool ParamsRunTool::CheckProfile(Options& params) return true; } -bool ParamsRunTool::DispatchParams(ParamsSharedPtr params, SignToolServiceImpl& api) +bool ParamsRunTool::DispatchParams(const ParamsSharedPtr& params, SignToolServiceImpl& api) { bool isSuccess = false; std::string method = params->GetMethod(); @@ -246,40 +246,40 @@ bool ParamsRunTool::RunCert(Options* params, SignToolServiceImpl& api) bool ParamsRunTool::CheckEndCertArguments(Options& params) { - if (!params.Required({params.KEY_ALIAS, params.ISSUER, params.ISSUER_KEY_ALIAS, - params.SUBJECT, params.SIGN_ALG, params.KEY_STORE_FILE})) { + if (!params.Required({Options::KEY_ALIAS, Options::ISSUER, Options::ISSUER_KEY_ALIAS, + Options::SUBJECT, Options::SIGN_ALG, Options::KEY_STORE_FILE})) { return false; } - std::string signAlg = params.GetString(params.SIGN_ALG); + std::string signAlg = params.GetString(Options::SIGN_ALG); if (!CmdUtil::JudgeSignAlgType(signAlg)) { return false; } - std::string outForm = params.GetString(params.OUT_FORM); + std::string outForm = params.GetString(Options::OUT_FORM); if (!outForm.empty()) { if (!CmdUtil::VerifyType(outForm, Options::OUT_FORM_SCOPE)) { return false; } } if (!outForm.empty() && "certChain" == outForm) { - if (!params.Required({params.SUB_CA_CERT_FILE, params.CA_CERT_FILE})) { + if (!params.Required({Options::SUB_CA_CERT_FILE, Options::CA_CERT_FILE})) { return false; } - if (!FileUtils::ValidFileType(params.GetString(params.SUB_CA_CERT_FILE), {"cer"}) || - !FileUtils::ValidFileType(params.GetString(params.CA_CERT_FILE), {"cer"})) { + if (!FileUtils::ValidFileType(params.GetString(Options::SUB_CA_CERT_FILE), {"cer"}) || + !FileUtils::ValidFileType(params.GetString(Options::CA_CERT_FILE), {"cer"})) { return false; } } - std::string keyStoreFile = params.GetString(params.KEY_STORE_FILE); + std::string keyStoreFile = params.GetString(Options::KEY_STORE_FILE); if (!FileUtils::ValidFileType(keyStoreFile, {"p12", "jks"})) { return false; } - if (params.find(params.ISSUER_KEY_STORE_FILE) != params.end()) { - std::string issuerKeyStoreFile = params.GetString(params.ISSUER_KEY_STORE_FILE); + if (params.find(Options::ISSUER_KEY_STORE_FILE) != params.end()) { + std::string issuerKeyStoreFile = params.GetString(Options::ISSUER_KEY_STORE_FILE); if (!FileUtils::ValidFileType(issuerKeyStoreFile, {"p12", "jks"})) { return false; } } - std::string outFile = params.GetString(params.OUT_FILE); + std::string outFile = params.GetString(Options::OUT_FILE); if (!outFile.empty()) { if (!FileUtils::ValidFileType(outFile, {"cer", "pem"})) { return false; diff --git a/hapsigntool_cpp/cmd/src/params_trust_list.cpp b/hapsigntool_cpp/cmd/src/params_trust_list.cpp index 28ce5177..1a3c3785 100644 --- a/hapsigntool_cpp/cmd/src/params_trust_list.cpp +++ b/hapsigntool_cpp/cmd/src/params_trust_list.cpp @@ -22,8 +22,6 @@ namespace OHOS { namespace SignatureTools { const std::string options = "[options]:"; -std::unique_ptr ParamsTrustList::paramTrustListInstance = nullptr; -std::mutex ParamsTrustList::mtx; const std::vector commands = { GENERATE_KEYPAIR + options, @@ -38,16 +36,10 @@ const std::vector commands = { VERIFY_APP + options }; -ParamsTrustList* ParamsTrustList::GetInstance() +ParamsTrustList ParamsTrustList::GetInstance() { - if (!paramTrustListInstance) { - std::lock_guard lock(mtx); - if (!paramTrustListInstance) { - paramTrustListInstance = std::make_unique(); - } - } - - return paramTrustListInstance.get(); + static ParamsTrustList instance; + return instance; } void ParamsTrustList::PutTrustMap(const std::string& cmdStandBy, const std::string& param) diff --git a/hapsigntool_cpp/codesigning/datastructure/include/code_sign_block.h b/hapsigntool_cpp/codesigning/datastructure/include/code_sign_block.h index b0248149..4c19d70c 100644 --- a/hapsigntool_cpp/codesigning/datastructure/include/code_sign_block.h +++ b/hapsigntool_cpp/codesigning/datastructure/include/code_sign_block.h @@ -35,20 +35,20 @@ public: static constexpr int SEGMENT_HEADER_COUNT = 3; CodeSignBlock(); virtual ~CodeSignBlock(); - void AddOneMerkleTree(const std::string& key, std::vector& merkleTree); + void AddOneMerkleTree(const std::string& key, const std::vector& merkleTree); std::vector GetOneMerkleTreeByFileName(const std::string& key); void SetCodeSignBlockFlag(); void SetSegmentNum(); - void AddToSegmentList(SegmentHeader sh); + void AddToSegmentList(const SegmentHeader& sh); std::vector& GetSegmentHeaderList(); void SetSegmentHeaders(); CodeSignBlockHeader& GetCodeSignBlockHeader(); - void SetCodeSignBlockHeader(CodeSignBlockHeader& csbHeader); - void SetFsVerityInfoSegment(FsVerityInfoSegment& fsVeritySeg); + void SetCodeSignBlockHeader(const CodeSignBlockHeader& csbHeader); + void SetFsVerityInfoSegment(const FsVerityInfoSegment& fsVeritySeg); HapInfoSegment& GetHapInfoSegment(); - void SetHapInfoSegment(HapInfoSegment& hapSeg); + void SetHapInfoSegment(const HapInfoSegment& hapSeg); NativeLibInfoSegment& GetSoInfoSegment(); - void SetSoInfoSegment(NativeLibInfoSegment soSeg); + void SetSoInfoSegment(const NativeLibInfoSegment& soSeg); void ToByteArray(std::vector& ret); void ComputeSegmentOffset(); int64_t ComputeMerkleTreeOffset(int64_t codeSignBlockOffset); diff --git a/hapsigntool_cpp/codesigning/datastructure/include/code_sign_block_header.h b/hapsigntool_cpp/codesigning/datastructure/include/code_sign_block_header.h index 75c0c702..31fd33ec 100644 --- a/hapsigntool_cpp/codesigning/datastructure/include/code_sign_block_header.h +++ b/hapsigntool_cpp/codesigning/datastructure/include/code_sign_block_header.h @@ -36,7 +36,7 @@ public: virtual Builder* SetBlockSize(int blockSize); virtual Builder* SetSegmentNum(int segmentNum); virtual Builder* SetFlags(int flags); - virtual Builder* SetReserved(std::vector& reserved); + virtual Builder* SetReserved(const std::vector& reserved); int64_t magic = MAGIC_NUM; int version = CODE_SIGNING_VERSION; @@ -52,7 +52,7 @@ public: CodeSignBlockHeader(); CodeSignBlockHeader(Builder* builder); virtual ~CodeSignBlockHeader(); - static CodeSignBlockHeader* FromByteArray(std::vector& bytes); + static CodeSignBlockHeader* FromByteArray(const std::vector& bytes); static int Size(); virtual void SetSegmentNum(int num); virtual int GetSegmentNum(); diff --git a/hapsigntool_cpp/codesigning/datastructure/include/elf_sign_block.h b/hapsigntool_cpp/codesigning/datastructure/include/elf_sign_block.h index f2c44fb3..745feecd 100644 --- a/hapsigntool_cpp/codesigning/datastructure/include/elf_sign_block.h +++ b/hapsigntool_cpp/codesigning/datastructure/include/elf_sign_block.h @@ -36,7 +36,7 @@ public: std::vector& GetMerkleTreeWithPadding(); int64_t GetDataSize(); int64_t GetTreeOffset(); - std::vector GetSignature(); + std::vector& GetSignature(); void ToByteArray(std::vector& ret); static bool FromByteArray(std::vector& bytes, ElfSignBlock& elfSignBlock); static int32_t ComputeMerkleTreePaddingLength(int64_t signBlockOffset); diff --git a/hapsigntool_cpp/codesigning/datastructure/include/fs_verity_info_segment.h b/hapsigntool_cpp/codesigning/datastructure/include/fs_verity_info_segment.h index 8c8ce508..1f874fe5 100644 --- a/hapsigntool_cpp/codesigning/datastructure/include/fs_verity_info_segment.h +++ b/hapsigntool_cpp/codesigning/datastructure/include/fs_verity_info_segment.h @@ -31,11 +31,11 @@ public: FsVerityInfoSegment(); FsVerityInfoSegment(int8_t version, int8_t hashAlgorithm, int8_t log2BlockSize); FsVerityInfoSegment(int magic, int8_t version, int8_t hashAlgorithm, - int8_t log2BlockSize, std::vector reserved); + int8_t log2BlockSize, const std::vector& reserved); virtual ~FsVerityInfoSegment(); virtual int Size(); virtual void ToByteArray(std::vector& ret); - static FsVerityInfoSegment FromByteArray(std::vector &bytes); + static FsVerityInfoSegment FromByteArray(const std::vector& bytes); private: static constexpr int MAGIC = static_cast((0x1E38 << 16) + (0x31AB));; diff --git a/hapsigntool_cpp/codesigning/datastructure/include/hap_info_segment.h b/hapsigntool_cpp/codesigning/datastructure/include/hap_info_segment.h index 09217224..9c81ffc1 100644 --- a/hapsigntool_cpp/codesigning/datastructure/include/hap_info_segment.h +++ b/hapsigntool_cpp/codesigning/datastructure/include/hap_info_segment.h @@ -29,12 +29,12 @@ namespace SignatureTools { class HapInfoSegment { public: HapInfoSegment(); - HapInfoSegment(int32_t magic, SignInfo signInfo); - void SetSignInfo(SignInfo signInfo); + HapInfoSegment(int32_t magic, const SignInfo& signInfo); + void SetSignInfo(const SignInfo& signInfo); SignInfo& GetSignInfo(); int32_t GetSize(); void ToByteArray(std::vector& ret); - static HapInfoSegment FromByteArray(std::vector bytes); + static HapInfoSegment FromByteArray(std::vector& bytes); private: static const int32_t MAGIC_NUM_BYTES = 4; diff --git a/hapsigntool_cpp/codesigning/datastructure/include/merkle_tree_extension.h b/hapsigntool_cpp/codesigning/datastructure/include/merkle_tree_extension.h index fa7ce5d1..cea429bc 100644 --- a/hapsigntool_cpp/codesigning/datastructure/include/merkle_tree_extension.h +++ b/hapsigntool_cpp/codesigning/datastructure/include/merkle_tree_extension.h @@ -29,7 +29,7 @@ public: static constexpr int32_t MERKLE_TREE_INLINED = 0x1; static constexpr int32_t MERKLE_TREE_EXTENSION_DATA_SIZE = 80; MerkleTreeExtension(); - MerkleTreeExtension(int64_t merkleTreeSize, int64_t merkleTreeOffset, std::vector rootHash); + MerkleTreeExtension(int64_t merkleTreeSize, int64_t merkleTreeOffset, const std::vector rootHash); virtual ~MerkleTreeExtension(); static MerkleTreeExtension* FromByteArray(std::vector& bytes); virtual int32_t GetSize(); diff --git a/hapsigntool_cpp/codesigning/datastructure/include/native_lib_info_segment.h b/hapsigntool_cpp/codesigning/datastructure/include/native_lib_info_segment.h index 6ed61213..fca7a120 100644 --- a/hapsigntool_cpp/codesigning/datastructure/include/native_lib_info_segment.h +++ b/hapsigntool_cpp/codesigning/datastructure/include/native_lib_info_segment.h @@ -35,15 +35,15 @@ public: NativeLibInfoSegment(int32_t magic, int32_t segmentSize, int32_t sectionNum, - std::vector signedFilePosList, - std::vector fileNameList, - std::vector signInfoList, - std::vector zeroPadding); - static NativeLibInfoSegment FromByteArray(std::vector &bytes); - void SetSoInfoList(std::vector> &soInfoList); + const std::vector& signedFilePosList, + const std::vector& fileNameList, + const std::vector& signInfoList, + const std::vector& zeroPadding); + static NativeLibInfoSegment FromByteArray(std::vector& bytes); + void SetSoInfoList(const std::vector>& soInfoList); int32_t GetSectionNum(); - std::vector GetFileNameList(); - std::vector GetSignInfoList(); + std::vector& GetFileNameList(); + std::vector& GetSignInfoList(); int32_t Size(); void ToByteArray(std::vector &ret); diff --git a/hapsigntool_cpp/codesigning/datastructure/include/sign_info.h b/hapsigntool_cpp/codesigning/datastructure/include/sign_info.h index eee3c20a..7d1adb55 100644 --- a/hapsigntool_cpp/codesigning/datastructure/include/sign_info.h +++ b/hapsigntool_cpp/codesigning/datastructure/include/sign_info.h @@ -36,17 +36,17 @@ public: static constexpr int32_t SIGNATURE_ALIGNMENT = 4; SignInfo(); SignInfo(int32_t saltSize, int32_t flags, int64_t dataSize, - std::vector &salt, std::vector &sig); + const std::vector& salt, const std::vector& sig); SignInfo(int32_t saltSize, int32_t sigSize, int32_t flags, int64_t dataSize, - std::vector &salt, + const std::vector& salt, int32_t extensionNum, int32_t extensionOffset, - std::vector &signature, - std::vector &zeroPadding, - std::vector extensionList); + const std::vector& signature, + const std::vector& zeroPadding, + const std::vector& extensionList); SignInfo(const SignInfo& other); SignInfo& operator=(const SignInfo& other); virtual ~SignInfo(); diff --git a/hapsigntool_cpp/codesigning/datastructure/include/unzip_handle_param.h b/hapsigntool_cpp/codesigning/datastructure/include/unzip_handle_param.h index 949fef97..ef070c9c 100644 --- a/hapsigntool_cpp/codesigning/datastructure/include/unzip_handle_param.h +++ b/hapsigntool_cpp/codesigning/datastructure/include/unzip_handle_param.h @@ -24,11 +24,11 @@ namespace OHOS { namespace SignatureTools { class UnzipHandleParam { public: - UnzipHandleParam(CodeSignBlock& csb, std::pair& pairResult, bool isSign); - UnzipHandleParam(std::vector>& ret, std::string& ownerID, bool isSign); + UnzipHandleParam(const CodeSignBlock& csb, const std::pair& pairResult, bool isSign); + UnzipHandleParam(std::vector>& ret, const std::string& ownerID, bool isSign); CodeSignBlock& GetCodeSignBlock(); std::pair& GetPairResult(); - std::vector>* GetRet(); + std::vector>& GetRet(); std::string& GetOwnerID(); bool IsSign(); diff --git a/hapsigntool_cpp/codesigning/datastructure/src/code_sign_block.cpp b/hapsigntool_cpp/codesigning/datastructure/src/code_sign_block.cpp index 16b0e5ea..fd2ed72e 100644 --- a/hapsigntool_cpp/codesigning/datastructure/src/code_sign_block.cpp +++ b/hapsigntool_cpp/codesigning/datastructure/src/code_sign_block.cpp @@ -26,7 +26,7 @@ CodeSignBlock::~CodeSignBlock() { } -void CodeSignBlock::AddOneMerkleTree(const std::string& key, std::vector& merkleTree) +void CodeSignBlock::AddOneMerkleTree(const std::string& key, const std::vector& merkleTree) { if (key.empty()) { return; @@ -62,7 +62,7 @@ void CodeSignBlock::SetSegmentNum() codeSignBlockHeader.SetSegmentNum(static_cast(segmentHeaderList.size())); } -void CodeSignBlock::AddToSegmentList(SegmentHeader sh) +void CodeSignBlock::AddToSegmentList(const SegmentHeader& sh) { segmentHeaderList.push_back(sh); } @@ -90,12 +90,12 @@ CodeSignBlockHeader& CodeSignBlock::GetCodeSignBlockHeader() return codeSignBlockHeader; } -void CodeSignBlock::SetCodeSignBlockHeader(CodeSignBlockHeader& csbHeader) +void CodeSignBlock::SetCodeSignBlockHeader(const CodeSignBlockHeader& csbHeader) { codeSignBlockHeader = csbHeader; } -void CodeSignBlock::SetFsVerityInfoSegment(FsVerityInfoSegment& fsVeritySeg) +void CodeSignBlock::SetFsVerityInfoSegment(const FsVerityInfoSegment& fsVeritySeg) { fsVerityInfoSegment = fsVeritySeg; } @@ -105,7 +105,7 @@ HapInfoSegment& CodeSignBlock::GetHapInfoSegment() return hapInfoSegment; } -void CodeSignBlock::SetHapInfoSegment(HapInfoSegment& hapSeg) +void CodeSignBlock::SetHapInfoSegment(const HapInfoSegment& hapSeg) { hapInfoSegment = hapSeg; } @@ -115,7 +115,7 @@ NativeLibInfoSegment& CodeSignBlock::GetSoInfoSegment() return nativeLibInfoSegment; } -void CodeSignBlock::SetSoInfoSegment(NativeLibInfoSegment soSeg) +void CodeSignBlock::SetSoInfoSegment(const NativeLibInfoSegment& soSeg) { nativeLibInfoSegment = soSeg; } diff --git a/hapsigntool_cpp/codesigning/datastructure/src/code_sign_block_header.cpp b/hapsigntool_cpp/codesigning/datastructure/src/code_sign_block_header.cpp index 42a87c42..1099a5af 100644 --- a/hapsigntool_cpp/codesigning/datastructure/src/code_sign_block_header.cpp +++ b/hapsigntool_cpp/codesigning/datastructure/src/code_sign_block_header.cpp @@ -75,7 +75,7 @@ void CodeSignBlockHeader::ToByteArray(std::vector& ret) ret = std::vector(bf.GetBufferPtr(), bf.GetBufferPtr() + bf.GetPosition()); } -CodeSignBlockHeader* CodeSignBlockHeader::FromByteArray(std::vector& bytes) +CodeSignBlockHeader* CodeSignBlockHeader::FromByteArray(const std::vector& bytes) { if (bytes.size() != Size()) { PrintErrorNumberMsg("SIGN_ERROR", SIGN_ERROR, @@ -161,7 +161,7 @@ CodeSignBlockHeader::Builder* CodeSignBlockHeader::Builder::SetFlags(int flags) return this; } -CodeSignBlockHeader::Builder* CodeSignBlockHeader::Builder::SetReserved(std::vector& reserved) +CodeSignBlockHeader::Builder* CodeSignBlockHeader::Builder::SetReserved(const std::vector& reserved) { this->reserved = reserved; return this; diff --git a/hapsigntool_cpp/codesigning/datastructure/src/elf_sign_block.cpp b/hapsigntool_cpp/codesigning/datastructure/src/elf_sign_block.cpp index 575ca658..e9508345 100644 --- a/hapsigntool_cpp/codesigning/datastructure/src/elf_sign_block.cpp +++ b/hapsigntool_cpp/codesigning/datastructure/src/elf_sign_block.cpp @@ -58,7 +58,7 @@ int64_t ElfSignBlock::GetTreeOffset() return descriptorWithSign.GetFsVerityDescriptor().GetMerkleTreeOffset(); } -std::vector ElfSignBlock::GetSignature() +std::vector& ElfSignBlock::GetSignature() { return descriptorWithSign.GetSignature(); } diff --git a/hapsigntool_cpp/codesigning/datastructure/src/fs_verity_info_segment.cpp b/hapsigntool_cpp/codesigning/datastructure/src/fs_verity_info_segment.cpp index 50971cb2..5247adea 100644 --- a/hapsigntool_cpp/codesigning/datastructure/src/fs_verity_info_segment.cpp +++ b/hapsigntool_cpp/codesigning/datastructure/src/fs_verity_info_segment.cpp @@ -33,7 +33,7 @@ FsVerityInfoSegment::FsVerityInfoSegment(int8_t version, int8_t hashAlgorithm, i } FsVerityInfoSegment::FsVerityInfoSegment(int magic, int8_t version, int8_t hashAlgorithm, - int8_t log2BlockSize, std::vector reserved) + int8_t log2BlockSize, const std::vector& reserved) { this->magic = magic; this->version = version; @@ -62,7 +62,7 @@ void FsVerityInfoSegment::ToByteArray(std::vector& ret) ret = std::vector(bf->GetBufferPtr(), bf->GetBufferPtr() + bf->GetPosition()); } -FsVerityInfoSegment FsVerityInfoSegment::FromByteArray(std::vector &bytes) +FsVerityInfoSegment FsVerityInfoSegment::FromByteArray(const std::vector& bytes) { if (bytes.size() != FS_VERITY_INFO_SEGMENT_SIZE) { PrintErrorNumberMsg("SIGN_ERROR", SIGN_ERROR, diff --git a/hapsigntool_cpp/codesigning/datastructure/src/hap_info_segment.cpp b/hapsigntool_cpp/codesigning/datastructure/src/hap_info_segment.cpp index 7f18961e..1c27a48e 100644 --- a/hapsigntool_cpp/codesigning/datastructure/src/hap_info_segment.cpp +++ b/hapsigntool_cpp/codesigning/datastructure/src/hap_info_segment.cpp @@ -24,13 +24,13 @@ HapInfoSegment::HapInfoSegment() signInfo = SignInfo(0, 0, 0, emptyVector, emptyVector); } -HapInfoSegment::HapInfoSegment(int32_t magic, SignInfo signInfo) +HapInfoSegment::HapInfoSegment(int32_t magic, const SignInfo& signInfo) { this->magic = magic; this->signInfo = signInfo; } -void HapInfoSegment::SetSignInfo(SignInfo signInfo) +void HapInfoSegment::SetSignInfo(const SignInfo& signInfo) { this->signInfo = signInfo; } @@ -57,7 +57,7 @@ void HapInfoSegment::ToByteArray(std::vector &ret) return; } -HapInfoSegment HapInfoSegment::FromByteArray(std::vector bytes) +HapInfoSegment HapInfoSegment::FromByteArray(std::vector& bytes) { std::unique_ptr bf = std::make_unique(ByteBuffer(bytes.size())); bf->PutData(bytes.data(), bytes.size()); diff --git a/hapsigntool_cpp/codesigning/datastructure/src/merkle_tree_extension.cpp b/hapsigntool_cpp/codesigning/datastructure/src/merkle_tree_extension.cpp index 95ba27b6..1966eb75 100644 --- a/hapsigntool_cpp/codesigning/datastructure/src/merkle_tree_extension.cpp +++ b/hapsigntool_cpp/codesigning/datastructure/src/merkle_tree_extension.cpp @@ -24,8 +24,8 @@ MerkleTreeExtension::MerkleTreeExtension() merkleTreeOffset = 0; } -MerkleTreeExtension::MerkleTreeExtension(int64_t merkleTreeSize, int64_t merkleTreeOffset, std::vector rootHash) - : Extension(MERKLE_TREE_INLINED, MERKLE_TREE_EXTENSION_DATA_SIZE) +MerkleTreeExtension::MerkleTreeExtension(int64_t merkleTreeSize, int64_t merkleTreeOffset, + const std::vector rootHash) : Extension(MERKLE_TREE_INLINED, MERKLE_TREE_EXTENSION_DATA_SIZE) { this->merkleTreeSize = merkleTreeSize; this->merkleTreeOffset = merkleTreeOffset; diff --git a/hapsigntool_cpp/codesigning/datastructure/src/native_lib_info_segment.cpp b/hapsigntool_cpp/codesigning/datastructure/src/native_lib_info_segment.cpp index 50054c19..34a65e61 100644 --- a/hapsigntool_cpp/codesigning/datastructure/src/native_lib_info_segment.cpp +++ b/hapsigntool_cpp/codesigning/datastructure/src/native_lib_info_segment.cpp @@ -30,11 +30,10 @@ NativeLibInfoSegment::NativeLibInfoSegment() NativeLibInfoSegment::NativeLibInfoSegment(int32_t magic, int32_t segmentSize, int32_t sectionNum, - std::vector signedFilePosList, - std::vector fileNameList, - std::vector signInfoList, - std::vector zeroPadding -) + const std::vector& signedFilePosList, + const std::vector& fileNameList, + const std::vector& signInfoList, + const std::vector& zeroPadding) { this->magic = magic; this->segmentSize = segmentSize; @@ -47,7 +46,7 @@ NativeLibInfoSegment::NativeLibInfoSegment(int32_t magic, signInfoListBlockSize = 0; } -void NativeLibInfoSegment::SetSoInfoList(std::vector> &soInfoList) +void NativeLibInfoSegment::SetSoInfoList(const std::vector> &soInfoList) { this->soInfoList = soInfoList; // Once map is set, update length, sectionNum as well @@ -61,12 +60,12 @@ int32_t NativeLibInfoSegment::GetSectionNum() return sectionNum; } -std::vector NativeLibInfoSegment::GetFileNameList() +std::vector& NativeLibInfoSegment::GetFileNameList() { return fileNameList; } -std::vector NativeLibInfoSegment::GetSignInfoList() +std::vector& NativeLibInfoSegment::GetSignInfoList() { return signInfoList; } diff --git a/hapsigntool_cpp/codesigning/datastructure/src/sign_info.cpp b/hapsigntool_cpp/codesigning/datastructure/src/sign_info.cpp index 78becf0a..15b3a94a 100644 --- a/hapsigntool_cpp/codesigning/datastructure/src/sign_info.cpp +++ b/hapsigntool_cpp/codesigning/datastructure/src/sign_info.cpp @@ -33,8 +33,8 @@ SignInfo::SignInfo() SignInfo::SignInfo(int32_t saltSize, int32_t flags, int64_t dataSize, - std::vector &salt, - std::vector &sig) + const std::vector& salt, + const std::vector& sig) { this->saltSize = saltSize; this->flags = flags; @@ -58,12 +58,12 @@ SignInfo::SignInfo(int32_t saltSize, int32_t sigSize, int32_t flags, int64_t dataSize, - std::vector& salt, + const std::vector& salt, int32_t extensionNum, int32_t extensionOffset, - std::vector& signature, - std::vector& zeroPadding, - std::vector extensionList) + const std::vector& signature, + const std::vector& zeroPadding, + const std::vector& extensionList) { this->saltSize = saltSize; this->sigSize = sigSize; diff --git a/hapsigntool_cpp/codesigning/datastructure/src/unzip_handle_param.cpp b/hapsigntool_cpp/codesigning/datastructure/src/unzip_handle_param.cpp index 81ad2713..112acab9 100644 --- a/hapsigntool_cpp/codesigning/datastructure/src/unzip_handle_param.cpp +++ b/hapsigntool_cpp/codesigning/datastructure/src/unzip_handle_param.cpp @@ -18,7 +18,7 @@ namespace OHOS { namespace SignatureTools { -UnzipHandleParam::UnzipHandleParam(CodeSignBlock& csb, std::pair& pairResult, +UnzipHandleParam::UnzipHandleParam(const CodeSignBlock& csb, const std::pair& pairResult, bool isSign) { this->csb = csb; @@ -27,7 +27,7 @@ UnzipHandleParam::UnzipHandleParam(CodeSignBlock& csb, std::pair>& ret, - std::string& ownerID, bool isSign) + const std::string& ownerID, bool isSign) { this->ret = ret; this->ownerID = ownerID; @@ -44,9 +44,9 @@ std::pair& UnzipHandleParam::GetPairResult() return pairResult; } -std::vector>* UnzipHandleParam::GetRet() +std::vector>& UnzipHandleParam::GetRet() { - return &ret; + return ret; } std::string& UnzipHandleParam::GetOwnerID() diff --git a/hapsigntool_cpp/codesigning/fsverity/include/fs_verity_descriptor_with_sign.h b/hapsigntool_cpp/codesigning/fsverity/include/fs_verity_descriptor_with_sign.h index c248b083..d0d49bae 100644 --- a/hapsigntool_cpp/codesigning/fsverity/include/fs_verity_descriptor_with_sign.h +++ b/hapsigntool_cpp/codesigning/fsverity/include/fs_verity_descriptor_with_sign.h @@ -34,7 +34,7 @@ public: int32_t Size(); void ToByteArray(std::vector &ret); FsVerityDescriptor GetFsVerityDescriptor(); - std::vector GetSignature(); + std::vector& GetSignature(); private: int32_t type = FsVerityDescriptor::FS_VERITY_DESCRIPTOR_TYPE;; diff --git a/hapsigntool_cpp/codesigning/fsverity/src/fs_verity_descriptor_with_sign.cpp b/hapsigntool_cpp/codesigning/fsverity/src/fs_verity_descriptor_with_sign.cpp index 97b8f012..7f885a84 100644 --- a/hapsigntool_cpp/codesigning/fsverity/src/fs_verity_descriptor_with_sign.cpp +++ b/hapsigntool_cpp/codesigning/fsverity/src/fs_verity_descriptor_with_sign.cpp @@ -66,7 +66,7 @@ FsVerityDescriptor FsVerityDescriptorWithSign::GetFsVerityDescriptor() return fsVerityDescriptor; } -std::vector FsVerityDescriptorWithSign::GetSignature() +std::vector& FsVerityDescriptorWithSign::GetSignature() { return signature; } diff --git a/hapsigntool_cpp/codesigning/sign/include/bc_signeddata_generator.h b/hapsigntool_cpp/codesigning/sign/include/bc_signeddata_generator.h index 79d115aa..b87daf50 100644 --- a/hapsigntool_cpp/codesigning/sign/include/bc_signeddata_generator.h +++ b/hapsigntool_cpp/codesigning/sign/include/bc_signeddata_generator.h @@ -46,7 +46,7 @@ private: // @return 0(NID_undef) >0: success(new NID) static int CreateNIDFromOID(const std::string& oid, const std::string& shortName, const std::string& longName); - int PackageSignedData(const std::string& content, std::shared_ptr signer, + int PackageSignedData(const std::string& content, const std::shared_ptr& signer, const std::string& sigAlg, std::string& ret); // @return 0:success <0 :error int AddOwnerID(std::vector& attrs, const std::string& ownerID); diff --git a/hapsigntool_cpp/codesigning/sign/include/code_signing.h b/hapsigntool_cpp/codesigning/sign/include/code_signing.h index 6c8f3bcd..0fdfb324 100644 --- a/hapsigntool_cpp/codesigning/sign/include/code_signing.h +++ b/hapsigntool_cpp/codesigning/sign/include/code_signing.h @@ -45,25 +45,25 @@ public: bool SignFile(std::istream& inputStream, int64_t fileSize, bool storeTree, - int64_t fsvTreeOffset, std::string ownerID, + int64_t fsvTreeOffset, const std::string &ownerID, std::pair>& ret); - bool GetCodeSignBlock(const std::string input, int64_t offset, - std::string inForm, std::string profileContent, + bool GetCodeSignBlock(const std::string &input, int64_t offset, + const std::string &inForm, const std::string &profileContent, ZipSigner& zip, std::vector& ret); - bool GetElfCodeSignBlock(std::string input, int64_t offset, - std::string inForm, std::string profileContent, + bool GetElfCodeSignBlock(const std::string &input, int64_t offset, + const std::string &inForm, const std::string &profileContent, std::vector &codesignData); public: const std::string NATIVE_LIB_AN_SUFFIX = ".an"; const std::string NATIVE_LIB_SO_SUFFIX = ".so"; - static bool IsNativeFile(std::string& input); + static bool IsNativeFile(const std::string& input); uint32_t ComputeDataSize(ZipSigner& zip); int64_t GetTimestamp(); - bool SignNativeLibs(std::string input, std::string ownerID); + bool SignNativeLibs(const std::string &input, std::string &ownerID); void UpdateCodeSignBlock(); - bool GetNativeEntriesFromHap(std::string& packageName, UnzipHandleParam& param); - bool GenerateSignature(std::vector& signedData, const std::string&, + bool GetNativeEntriesFromHap(const std::string& packageName, UnzipHandleParam& param); + bool GenerateSignature(const std::vector& signedData, const std::string&, std::vector&); int64_t m_timestamp = 0; std::vector m_extractedNativeLibSuffixs; diff --git a/hapsigntool_cpp/codesigning/sign/src/bc_signeddata_generator.cpp b/hapsigntool_cpp/codesigning/sign/src/bc_signeddata_generator.cpp index 43df8299..961b96de 100644 --- a/hapsigntool_cpp/codesigning/sign/src/bc_signeddata_generator.cpp +++ b/hapsigntool_cpp/codesigning/sign/src/bc_signeddata_generator.cpp @@ -65,8 +65,7 @@ void BCSignedDataGenerator::SetOwnerId(const std::string& ownerID) m_ownerID = ownerID; } -int BCSignedDataGenerator::PackageSignedData(const std::string& content, - std::shared_ptr signer, +int BCSignedDataGenerator::PackageSignedData(const std::string& content, const std::shared_ptr& signer, const std::string& sigAlg, std::string& ret) { int result = RET_OK; diff --git a/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp b/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp index 7033053a..6b50dd6f 100644 --- a/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp +++ b/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp @@ -43,8 +43,8 @@ CodeSigning::CodeSigning() { } -bool CodeSigning::GetCodeSignBlock(const std::string input, int64_t offset, - std::string inForm, std::string profileContent, +bool CodeSigning::GetCodeSignBlock(const std::string &input, int64_t offset, + const std::string &inForm, const std::string &profileContent, ZipSigner& zip, std::vector& ret) { SIGNATURE_TOOLS_LOGI("Start to sign code."); @@ -128,7 +128,7 @@ int64_t CodeSigning::GetTimestamp() } bool CodeSigning::SignFile(std::istream& inputStream, int64_t fileSize, bool storeTree, - int64_t fsvTreeOffset, std::string ownerID, std::pair>& ret) + int64_t fsvTreeOffset, const std::string &ownerID, std::pair>& ret) { std::unique_ptr fsVerityGenerator = std::make_unique(); @@ -163,8 +163,8 @@ bool CodeSigning::SignFile(std::istream& inputStream, int64_t fileSize, bool sto return true; } -bool CodeSigning::GetElfCodeSignBlock(std::string input, int64_t offset, - std::string inForm, std::string profileContent, +bool CodeSigning::GetElfCodeSignBlock(const std::string &input, int64_t offset, + const std::string &inForm, const std::string &profileContent, std::vector& codesignData) { SIGNATURE_TOOLS_LOGI("Start to sign elf code."); @@ -209,7 +209,7 @@ bool CodeSigning::GetElfCodeSignBlock(std::string input, int64_t offset, return true; } -bool CodeSigning::SignNativeLibs(std::string input, std::string ownerID) +bool CodeSigning::SignNativeLibs(const std::string &input, std::string &ownerID) { // 'an' libs are always signed m_extractedNativeLibSuffixs.push_back(NATIVE_LIB_AN_SUFFIX); @@ -223,12 +223,12 @@ bool CodeSigning::SignNativeLibs(std::string input, std::string ownerID) SIGNATURE_TOOLS_LOGE("%s native libs handle failed", input.c_str()); return false; } - std::vector> *nativeLibInfoList = param.GetRet(); - if (nativeLibInfoList->empty()) { + std::vector>& nativeLibInfoList = param.GetRet(); + if (nativeLibInfoList.empty()) { SIGNATURE_TOOLS_LOGI("No native libs."); return true; } - m_codeSignBlock.GetSoInfoSegment().SetSoInfoList(*nativeLibInfoList); + m_codeSignBlock.GetSoInfoSegment().SetSoInfoList(nativeLibInfoList); return true; } @@ -244,7 +244,7 @@ void CodeSigning::UpdateCodeSignBlock() m_codeSignBlock.ComputeSegmentOffset(); } -bool CodeSigning::GetNativeEntriesFromHap(std::string& packageName, UnzipHandleParam& param) +bool CodeSigning::GetNativeEntriesFromHap(const std::string& packageName, UnzipHandleParam& param) { unzFile zFile = unzOpen(packageName.c_str()); if (zFile == NULL) { @@ -335,11 +335,11 @@ bool CodeSigning::DoNativeLibSignOrVerify(std::string fileName, std::stringbuf& if (!signFileFlag) { return false; } - std::vector> *ret = param.GetRet(); - ret->push_back(std::make_pair(fileName, pairSignInfoAndMerkleTreeBytes.first)); + std::vector>& ret = param.GetRet(); + ret.push_back(std::make_pair(fileName, pairSignInfoAndMerkleTreeBytes.first)); } else { CodeSignBlock csb = param.GetCodeSignBlock(); - std::vector fileNames = csb.GetSoInfoSegment().GetFileNameList(); + std::vector& fileNames = csb.GetSoInfoSegment().GetFileNameList(); bool isContainFileName = std::find(fileNames.begin(), fileNames.end(), fileName) != fileNames.end(); if (!isContainFileName) { PrintErrorNumberMsg("VERIFY_ERROR", VERIFY_ERROR, @@ -416,7 +416,7 @@ bool CodeSigning::CheckFileName(unzFile& zFile, char fileName[], size_t* nameLen return true; } -bool CodeSigning::IsNativeFile(std::string& input) +bool CodeSigning::IsNativeFile(const std::string& input) { size_t dotPos = input.rfind('.'); if (dotPos == std::string::npos) { @@ -434,7 +434,7 @@ bool CodeSigning::IsNativeFile(std::string& input) return false; } -bool CodeSigning::GenerateSignature(std::vector& signedData, const std::string& ownerID, +bool CodeSigning::GenerateSignature(const std::vector& signedData, const std::string& ownerID, std::vector& ret) { if (m_signConfig->GetSigner() != nullptr) { diff --git a/hapsigntool_cpp/codesigning/sign/src/verify_code_signature.cpp b/hapsigntool_cpp/codesigning/sign/src/verify_code_signature.cpp index 76719c3e..de4f4431 100644 --- a/hapsigntool_cpp/codesigning/sign/src/verify_code_signature.cpp +++ b/hapsigntool_cpp/codesigning/sign/src/verify_code_signature.cpp @@ -84,7 +84,7 @@ bool VerifyCodeSignature::VerifyElf(std::string file, int64_t offset, int64_t le // 3) check ownerID if (!profileContent.empty()) { std::pair pairResult = HapUtils::ParseAppIdentifier(profileContent); - std::vector signature = elfSignBlock.GetSignature(); + std::vector& signature = elfSignBlock.GetSignature(); std::string signatureStr(signature.begin(), signature.end()); bool checkOwnerIDFlag = CmsUtils::CheckOwnerID(signatureStr, pairResult.first, pairResult.second); if (!checkOwnerIDFlag) { diff --git a/hapsigntool_cpp/hap/entity/include/hw_block_data.h b/hapsigntool_cpp/hap/entity/include/hw_block_data.h index 5ef2f768..17564965 100644 --- a/hapsigntool_cpp/hap/entity/include/hw_block_data.h +++ b/hapsigntool_cpp/hap/entity/include/hw_block_data.h @@ -22,12 +22,12 @@ namespace OHOS { namespace SignatureTools { class HwBlockData { public: - HwBlockData(int32_t blockNum, int64_t blockStart); + HwBlockData(const int32_t blockNum, const int64_t blockStart); int32_t GetBlockNum(); - void SetBlockNum(int32_t blockNum); + void SetBlockNum(const int32_t blockNum); int64_t GetBlockStart(); - void SetBlockStart(int64_t blockStart); + void SetBlockStart(const int64_t blockStart); private: int32_t m_blockNum; diff --git a/hapsigntool_cpp/hap/entity/include/hw_block_head.h b/hapsigntool_cpp/hap/entity/include/hw_block_head.h index 8a397b3f..b82103b7 100644 --- a/hapsigntool_cpp/hap/entity/include/hw_block_head.h +++ b/hapsigntool_cpp/hap/entity/include/hw_block_head.h @@ -33,8 +33,8 @@ public: public: static int GetBlockLen(); static int GetElfBlockLen(); - static std::string GetBlockHead(char type, char tag, short length, int offset); - static std::vector GetBlockHeadLittleEndian(char type, char tag, int length, int offset); + static std::string GetBlockHead(const char type, const char tag, const short length, const int offset); + static std::vector GetBlockHeadLittleEndian(const char type, const char tag, const int length, const int offset); }; } // namespace SignatureTools } // namespace OHOS diff --git a/hapsigntool_cpp/hap/entity/include/hw_sign_head.h b/hapsigntool_cpp/hap/entity/include/hw_sign_head.h index 63ddb9e2..7607dd2d 100644 --- a/hapsigntool_cpp/hap/entity/include/hw_sign_head.h +++ b/hapsigntool_cpp/hap/entity/include/hw_sign_head.h @@ -25,14 +25,14 @@ class HwSignHead { public: HwSignHead(); - std::vector GetSignHead(int subBlockSize); + std::vector GetSignHead(const int subBlockSize); static const int SIGN_HEAD_LEN; static const std::string MAGIC; static const std::string ELF_MAGIC; static const std::string VERSION; static const int32_t ELF_BLOCK_LEN; static const int32_t BIN_BLOCK_LEN; - static std::vector GetSignHeadLittleEndian(int subBlockSize, int subBlockNum); + static std::vector GetSignHeadLittleEndian(const int subBlockSize, const int subBlockNum); private: static const int NUM_OF_BLOCK; diff --git a/hapsigntool_cpp/hap/entity/include/sign_block_data.h b/hapsigntool_cpp/hap/entity/include/sign_block_data.h index c1e616cb..4f659be3 100644 --- a/hapsigntool_cpp/hap/entity/include/sign_block_data.h +++ b/hapsigntool_cpp/hap/entity/include/sign_block_data.h @@ -25,13 +25,13 @@ namespace OHOS { namespace SignatureTools { class SignBlockData { public: - SignBlockData(std::vector& signData, char type); - SignBlockData(std::string &signFile, char type); + SignBlockData(const std::vector& signData, const char type); + SignBlockData(const std::string &signFile, const char type); char GetType(); - std::vector GetBlockHead(); - void SetBlockHead(std::vector &blockHead); - std::vector GetSignData(); + std::vector& GetBlockHead(); + void SetBlockHead(const std::vector& blockHead); + std::vector& GetSignData(); std::string GetSignFile(); long GetLen(); bool GetByte(); diff --git a/hapsigntool_cpp/hap/entity/include/sign_block_info.h b/hapsigntool_cpp/hap/entity/include/sign_block_info.h index 9c575d0f..ff803e7e 100644 --- a/hapsigntool_cpp/hap/entity/include/sign_block_info.h +++ b/hapsigntool_cpp/hap/entity/include/sign_block_info.h @@ -30,10 +30,10 @@ public: public: std::unordered_map& GetSignBlockMap(); - std::vector GetFileDigest(); - void SetFileDigest(std::vector fileDigest); - std::vector GetRawDigest(); - void SetRawDigest(std::vector rawDigest); + std::vector& GetFileDigest(); + void SetFileDigest(const std::vector& fileDigest); + std::vector& GetRawDigest(); + void SetRawDigest(const std::vector& rawDigest); bool GetNeedGenerateDigest(); private: diff --git a/hapsigntool_cpp/hap/entity/include/sign_content_info.h b/hapsigntool_cpp/hap/entity/include/sign_content_info.h index 990342ed..023ba34b 100644 --- a/hapsigntool_cpp/hap/entity/include/sign_content_info.h +++ b/hapsigntool_cpp/hap/entity/include/sign_content_info.h @@ -25,7 +25,8 @@ namespace OHOS { namespace SignatureTools { class SignContentHash { public: - SignContentHash(char type, char tag, short algId, int length, std::vector hash); + SignContentHash(const char type, const char tag, const short algId, + const int length, const std::vector& hash); public: static const int CONTENT_HEAD_SIZE = 8; @@ -42,8 +43,9 @@ public: SignContentInfo(); public: - void AddContentHashData(char type, char tag, short algId, int length, std::vector hash); - void AddHashData(SignContentHash signInfo); + void AddContentHashData(const char type, const char tag, const short algId, + const int length, const std::vector &hash); + void AddHashData(const SignContentHash &signInfo); std::vector GetByteContent(); private: diff --git a/hapsigntool_cpp/hap/entity/include/signature_algorithm_helper.h b/hapsigntool_cpp/hap/entity/include/signature_algorithm_helper.h index f818d1ce..359bf41a 100644 --- a/hapsigntool_cpp/hap/entity/include/signature_algorithm_helper.h +++ b/hapsigntool_cpp/hap/entity/include/signature_algorithm_helper.h @@ -37,12 +37,12 @@ public: SignatureAlgorithmHelper(); SignatureAlgorithmHelper(const SignatureAlgorithmHelper& other); - SignatureAlgorithmHelper(SignatureAlgorithmId id_, std::string keyAlg_, ContentDigestAlgorithm digestAlg_, - std::pair sigParams_); + SignatureAlgorithmHelper(const SignatureAlgorithmId &id_, const std::string &keyAlg_, const ContentDigestAlgorithm& digestAlg_, + const std::pair& sigParams_); SignatureAlgorithmHelper& operator=(const SignatureAlgorithmHelper& other); ~SignatureAlgorithmHelper(); - static const SignatureAlgorithmHelper* FindById(SignatureAlgorithmId id); + static const SignatureAlgorithmHelper* FindById(const SignatureAlgorithmId id); SignatureAlgorithmId m_id; std::string m_keyAlgorithm; diff --git a/hapsigntool_cpp/hap/entity/include/signing_block.h b/hapsigntool_cpp/hap/entity/include/signing_block.h index e4a5bb43..a7a3c9c4 100644 --- a/hapsigntool_cpp/hap/entity/include/signing_block.h +++ b/hapsigntool_cpp/hap/entity/include/signing_block.h @@ -25,11 +25,11 @@ namespace OHOS { namespace SignatureTools { class SigningBlock { public: - SigningBlock(int32_t type, std::vector value); - SigningBlock(int32_t type, std::vector value, int64_t offset); + SigningBlock(const int32_t type, const std::vector &value); + SigningBlock(const int32_t type, const std::vector &value, const int64_t offset); int32_t GetLength(); - std::vector GetValue(); + std::vector& GetValue(); int64_t GetOffset(); private: diff --git a/hapsigntool_cpp/hap/entity/src/hw_block_data.cpp b/hapsigntool_cpp/hap/entity/src/hw_block_data.cpp index 711a40b9..b9a02a64 100644 --- a/hapsigntool_cpp/hap/entity/src/hw_block_data.cpp +++ b/hapsigntool_cpp/hap/entity/src/hw_block_data.cpp @@ -18,7 +18,7 @@ namespace OHOS { namespace SignatureTools { -HwBlockData::HwBlockData(int32_t blockNum, int64_t blockStart) +HwBlockData::HwBlockData(const int32_t blockNum, const int64_t blockStart) { m_blockNum = blockNum; m_blockStart = blockStart; @@ -29,7 +29,7 @@ int32_t HwBlockData::GetBlockNum() return m_blockNum; } -void HwBlockData::SetBlockNum(int32_t blockNum) +void HwBlockData::SetBlockNum(const int32_t blockNum) { m_blockNum = blockNum; } @@ -39,7 +39,7 @@ int64_t HwBlockData::GetBlockStart() return m_blockStart; } -void HwBlockData::SetBlockStart(int64_t blockStart) +void HwBlockData::SetBlockStart(const int64_t blockStart) { m_blockStart = blockStart; } diff --git a/hapsigntool_cpp/hap/entity/src/hw_block_head.cpp b/hapsigntool_cpp/hap/entity/src/hw_block_head.cpp index 71116ea2..6084bad3 100644 --- a/hapsigntool_cpp/hap/entity/src/hw_block_head.cpp +++ b/hapsigntool_cpp/hap/entity/src/hw_block_head.cpp @@ -30,7 +30,7 @@ int HwBlockHead::GetElfBlockLen() return ELF_BLOCK_LEN; } -std::string HwBlockHead::GetBlockHead(char type, char tag, short length, int offset) +std::string HwBlockHead::GetBlockHead(const char type, const char tag, const short length, const int offset) { std::vector tmpVec; tmpVec.push_back(type); @@ -45,7 +45,7 @@ std::string HwBlockHead::GetBlockHead(char type, char tag, short length, int off return std::string(tmpVec.begin(), tmpVec.end()); } -std::vector HwBlockHead::GetBlockHeadLittleEndian(char type, char tag, int length, int offset) +std::vector HwBlockHead::GetBlockHeadLittleEndian(const char type, const char tag, const int length, const int offset) { ByteBuffer bf = ByteBuffer(HwBlockHead::ELF_BLOCK_LEN); bf.PutByte(type); diff --git a/hapsigntool_cpp/hap/entity/src/hw_sign_head.cpp b/hapsigntool_cpp/hap/entity/src/hw_sign_head.cpp index 0852ab10..c2764b2c 100644 --- a/hapsigntool_cpp/hap/entity/src/hw_sign_head.cpp +++ b/hapsigntool_cpp/hap/entity/src/hw_sign_head.cpp @@ -37,7 +37,7 @@ HwSignHead::HwSignHead() { } -std::vector HwSignHead::GetSignHead(int subBlockSize) +std::vector HwSignHead::GetSignHead(const int subBlockSize) { int size = subBlockSize; std::vector signHead(SIGN_HEAD_LEN, 0); @@ -70,7 +70,7 @@ std::vector HwSignHead::GetSignHead(int subBlockSize) return signHead; } -std::vector HwSignHead::GetSignHeadLittleEndian(int subBlockSize, int subBlockNum) +std::vector HwSignHead::GetSignHeadLittleEndian(const int subBlockSize, const int subBlockNum) { ByteBuffer bf = ByteBuffer(HwSignHead::SIGN_HEAD_LEN); for (char c : HwSignHead::ELF_MAGIC) { diff --git a/hapsigntool_cpp/hap/entity/src/sign_block_data.cpp b/hapsigntool_cpp/hap/entity/src/sign_block_data.cpp index 05efa28f..cdfe4ad6 100644 --- a/hapsigntool_cpp/hap/entity/src/sign_block_data.cpp +++ b/hapsigntool_cpp/hap/entity/src/sign_block_data.cpp @@ -18,7 +18,7 @@ namespace OHOS { namespace SignatureTools { -SignBlockData::SignBlockData(std::vector& signData, char type) +SignBlockData::SignBlockData(const std::vector& signData, const char type) { m_signData = signData; m_type = type; @@ -26,7 +26,7 @@ SignBlockData::SignBlockData(std::vector& signData, char type) m_isByte = true; } -SignBlockData::SignBlockData(std::string& signFile, char type) +SignBlockData::SignBlockData(const std::string& signFile, const char type) { m_signFile = signFile; m_type = type; @@ -39,17 +39,17 @@ char SignBlockData::GetType() return m_type; } -std::vector SignBlockData::GetBlockHead() +std::vector& SignBlockData::GetBlockHead() { return m_blockHead; } -void SignBlockData::SetBlockHead(std::vector& blockHead) +void SignBlockData::SetBlockHead(const std::vector& blockHead) { m_blockHead = blockHead; } -std::vector SignBlockData::GetSignData() +std::vector& SignBlockData::GetSignData() { return m_signData; } diff --git a/hapsigntool_cpp/hap/entity/src/sign_block_info.cpp b/hapsigntool_cpp/hap/entity/src/sign_block_info.cpp index 545e9551..dada721e 100644 --- a/hapsigntool_cpp/hap/entity/src/sign_block_info.cpp +++ b/hapsigntool_cpp/hap/entity/src/sign_block_info.cpp @@ -32,22 +32,22 @@ std::unordered_map& SignBlockInfo::GetSignBlockMap() return m_signBlockMap; } -std::vector SignBlockInfo::GetFileDigest() +std::vector& SignBlockInfo::GetFileDigest() { return m_fileDigest; } -void SignBlockInfo::SetFileDigest(std::vector fileDigest) +void SignBlockInfo::SetFileDigest(const std::vector& fileDigest) { m_fileDigest = fileDigest; } -std::vector SignBlockInfo::GetRawDigest() +std::vector& SignBlockInfo::GetRawDigest() { return m_rawDigest; } -void SignBlockInfo::SetRawDigest(std::vector rawDigest) +void SignBlockInfo::SetRawDigest(const std::vector& rawDigest) { m_rawDigest = rawDigest; } diff --git a/hapsigntool_cpp/hap/entity/src/sign_content_info.cpp b/hapsigntool_cpp/hap/entity/src/sign_content_info.cpp index a111d4f7..1ef57cf0 100644 --- a/hapsigntool_cpp/hap/entity/src/sign_content_info.cpp +++ b/hapsigntool_cpp/hap/entity/src/sign_content_info.cpp @@ -20,7 +20,8 @@ namespace OHOS { namespace SignatureTools { -SignContentHash::SignContentHash(char type, char tag, short algId, int length, std::vector hash) +SignContentHash::SignContentHash(const char type, const char tag, const short algId, + const int length, const std::vector &hash) { m_type = type; m_tag = tag; @@ -37,13 +38,14 @@ SignContentInfo::SignContentInfo() m_numOfBlocks = 0; } -void SignContentInfo::AddContentHashData(char type, char tag, short algId, int length, std::vector hash) +void SignContentInfo::AddContentHashData(const char type, const char tag, const short algId, + const int length, const std::vector &hash) { SignContentHash signInfo(type, tag, algId, length, hash); AddHashData(signInfo); } -void SignContentInfo::AddHashData(SignContentHash signInfo) +void SignContentInfo::AddHashData(const SignContentHash& signInfo) { m_hashData.push_back(signInfo); ++m_numOfBlocks; diff --git a/hapsigntool_cpp/hap/entity/src/signature_algorithm_helper.cpp b/hapsigntool_cpp/hap/entity/src/signature_algorithm_helper.cpp index f6af5064..ae8eeff2 100644 --- a/hapsigntool_cpp/hap/entity/src/signature_algorithm_helper.cpp +++ b/hapsigntool_cpp/hap/entity/src/signature_algorithm_helper.cpp @@ -38,9 +38,9 @@ SignatureAlgorithmHelper::SignatureAlgorithmHelper(const SignatureAlgorithmHelpe { } -SignatureAlgorithmHelper::SignatureAlgorithmHelper(SignatureAlgorithmId id_, std::string keyAlg_, - ContentDigestAlgorithm digestAlg_, - std::pair sigParams_) +SignatureAlgorithmHelper::SignatureAlgorithmHelper(const SignatureAlgorithmId& id_, const std::string& keyAlg_, + const ContentDigestAlgorithm& digestAlg_, + const std::pair& sigParams_) : m_id(id_), m_keyAlgorithm(keyAlg_), m_contentDigestAlgorithm(digestAlg_), m_signatureAlgAndParams(sigParams_) { } @@ -61,7 +61,7 @@ SignatureAlgorithmHelper::~SignatureAlgorithmHelper() { } -const SignatureAlgorithmHelper* SignatureAlgorithmHelper::FindById(SignatureAlgorithmId id) +const SignatureAlgorithmHelper* SignatureAlgorithmHelper::FindById(const SignatureAlgorithmId id) { if (id == SignatureAlgorithmId::ECDSA_WITH_SHA256) return &ECDSA_WITH_SHA256_INSTANCE; if (id == SignatureAlgorithmId::ECDSA_WITH_SHA384) return &ECDSA_WITH_SHA384_INSTANCE; diff --git a/hapsigntool_cpp/hap/entity/src/signing_block.cpp b/hapsigntool_cpp/hap/entity/src/signing_block.cpp index 0f273388..9bb4a054 100644 --- a/hapsigntool_cpp/hap/entity/src/signing_block.cpp +++ b/hapsigntool_cpp/hap/entity/src/signing_block.cpp @@ -18,14 +18,14 @@ namespace OHOS { namespace SignatureTools { -SigningBlock::SigningBlock(int32_t type, std::vector value) +SigningBlock::SigningBlock(const int32_t type, const std::vector &value) { m_type = type; m_length = value.size(); m_value = value; } -SigningBlock::SigningBlock(int32_t type, std::vector value, int64_t offset) +SigningBlock::SigningBlock(const int32_t type, const std::vector &value, const int64_t offset) { m_type = type; m_length = value.size(); @@ -38,7 +38,7 @@ int32_t SigningBlock::GetLength() return m_length; } -std::vector SigningBlock::GetValue() +std::vector& SigningBlock::GetValue() { return m_value; } diff --git a/hapsigntool_cpp/hap/provider/include/sign_provider.h b/hapsigntool_cpp/hap/provider/include/sign_provider.h index 2c67def4..80bd3f33 100644 --- a/hapsigntool_cpp/hap/provider/include/sign_provider.h +++ b/hapsigntool_cpp/hap/provider/include/sign_provider.h @@ -32,7 +32,6 @@ #include "options.h" #include "signature_tools_errno.h" #include "hap_utils.h" -#include "hap_verify_result.h" #include "hap_signer_block_utils.h" #include "sign_hap.h" #include "signature_tools_log.h" @@ -62,6 +61,7 @@ public: bool Sign(Options* options); bool SignElf(Options* options); bool SignBin(Options* options); + bool SetSignParams(Options* options, std::unordered_set& paramSet); virtual std::optional GetCrl(); virtual bool CheckParams(Options* options); virtual bool CheckInputCertMatchWithProfile(X509* inputCert, X509* certInProfile)const; @@ -100,13 +100,13 @@ private: fileIOTuple PrepareIOStreams(const std::string& inputPath, const std::string& outputPath, bool& ret); bool InitZipOutput(std::shared_ptr outputHap, std::shared_ptr zip, - std::shared_ptr, std::shared_ptrtmpOutput, std::string path); + std::shared_ptr, std::shared_ptrtmpOutput, const std::string& path); bool PrintErrorLog(const std::string& log, const int& errorCode, std::string path = ""); bool InitSigerConfig(SignerConfig& signerConfig, STACK_OF(X509)* publicCerts, Options* options); - bool DoAfterSign(bool isPathOverlap, std::string tmpOutputFile, std::string inputFilePath); + bool DoAfterSign(bool isPathOverlap,const std::string& tmpOutputFile, const std::string& inputFilePath); bool CreateSignerConfigs(STACK_OF(X509)* certificates, const std::optional& crl, Options* options, SignerConfig&); diff --git a/hapsigntool_cpp/hap/provider/src/local_sign_provider.cpp b/hapsigntool_cpp/hap/provider/src/local_sign_provider.cpp index b63038de..343d504c 100644 --- a/hapsigntool_cpp/hap/provider/src/local_sign_provider.cpp +++ b/hapsigntool_cpp/hap/provider/src/local_sign_provider.cpp @@ -24,7 +24,6 @@ std::optional LocalSignProvider::GetCrl() bool LocalSignProvider::CheckParams(Options* options) { - bool flag = false; if (!SignProvider::CheckParams(options)) { SIGNATURE_TOOLS_LOGE("Parameter check failed !"); return false; @@ -34,25 +33,14 @@ bool LocalSignProvider::CheckParams(Options* options) paramFileds.emplace_back(ParamConstants::PARAM_LOCAL_JKS_KEYSTORE_CODE); paramFileds.emplace_back(ParamConstants::PARAM_LOCAL_JKS_KEYALIAS_CODE); std::unordered_set paramSet = Params::InitParamField(paramFileds); - for (auto it = options->begin(); it != options->end(); it++) { - flag = (paramSet.find(it->first) != paramSet.end()); - if (flag) { - size_t size = it->first.size(); - std::string str = it->first.substr(size - 3); - if (str == "Pwd") { - std::string strPwd = options->GetChars(it->first); - signParams.insert(std::make_pair(it->first, strPwd)); - } else { - signParams.insert(std::make_pair(it->first, options->GetString(it->first))); - } - } + if (!this->SetSignParams(options, paramSet)) { + return false; } if (!CheckSignCode()) { SIGNATURE_TOOLS_LOGE("signCode Parameter must 0 or 1"); return false; } - flag = !CheckPublicKeyPath(); - if (flag) { + if (!CheckPublicKeyPath()) { SIGNATURE_TOOLS_LOGE("appCertFile Parameter check error !"); return false; } diff --git a/hapsigntool_cpp/hap/provider/src/remote_sign_provider.cpp b/hapsigntool_cpp/hap/provider/src/remote_sign_provider.cpp index 6d2740b3..ec55e0f6 100644 --- a/hapsigntool_cpp/hap/provider/src/remote_sign_provider.cpp +++ b/hapsigntool_cpp/hap/provider/src/remote_sign_provider.cpp @@ -28,7 +28,6 @@ RemoteSignProvider::~RemoteSignProvider() bool RemoteSignProvider::CheckParams(Options* options) { - bool flag = false; if (!SignProvider::CheckParams(options)) { SIGNATURE_TOOLS_LOGE("SignProvider::Parameter check failed !"); return false; @@ -40,23 +39,11 @@ bool RemoteSignProvider::CheckParams(Options* options) paramFileds.emplace_back(ParamConstants::PARAM_REMOTE_ONLINEAUTHMODE); paramFileds.emplace_back(ParamConstants::PARAM_REMOTE_SIGNERPLUGIN); std::unordered_set paramSet = Params::InitParamField(paramFileds); - for (auto it = options->begin(); it != options->end(); it++) { - flag = (paramSet.find(it->first) != paramSet.end()); - if (flag) { - size_t size = it->first.size(); - std::string str = it->first.substr(size - 3); - if (str == "Pwd") { - std::string strPwd = options->GetChars(it->first); - strPwd = ""; - signParams.insert(std::make_pair(it->first, strPwd)); - } else { - signParams.insert(std::make_pair(it->first, options->GetString(it->first))); - } - } + if (!this->SetSignParams(options, paramSet)) { + return false; } for (const auto& param : paramFileds) { - flag = (signParams.find(param) == signParams.end()); - if (flag) { + if (signParams.find(param) == signParams.end()) { PrintErrorNumberMsg("COMMAND_PARAM_ERROR", COMMAND_PARAM_ERROR, "Missing parameter:" + param); return false; diff --git a/hapsigntool_cpp/hap/provider/src/sign_provider.cpp b/hapsigntool_cpp/hap/provider/src/sign_provider.cpp index cdb3667e..4ee1047a 100644 --- a/hapsigntool_cpp/hap/provider/src/sign_provider.cpp +++ b/hapsigntool_cpp/hap/provider/src/sign_provider.cpp @@ -132,7 +132,7 @@ bool SignProvider::InitZipOutput(std::shared_ptr outputHap, std::shared_ptr zip, std::shared_ptr inputStream, std::shared_ptrtmpOutput, - std::string Path) + const std::string& Path) { int alignment; if (!StringUtils::CheckStringToint(signParams.at(ParamConstants::PARAM_BASIC_ALIGNMENT), alignment)) { @@ -534,7 +534,7 @@ int SignProvider::GetCertListFromFile(const std::string& certsFile, STACK_OF(X50 return RET_OK; } -bool SignProvider::DoAfterSign(bool isPathOverlap, std::string tmpOutputFile, std::string inputFilePath) +bool SignProvider::DoAfterSign(bool isPathOverlap, const std::string& tmpOutputFile, const std::string& inputFilePath) { if (isPathOverlap) { remove(inputFilePath.c_str()); @@ -562,6 +562,30 @@ bool SignProvider::CopyFileAndAlignment(std::ifstream& input, std::ofstream& tmp return true; } +bool SignProvider::SetSignParams(Options* options, std::unordered_set& paramSet) +{ + for (auto it = options->begin(); it != options->end(); it++) { + if (paramSet.find(it->first) != paramSet.end()) { + size_t size = it->first.size(); + std::string str = it->first.substr(size - 3); + if (str != "Pwd") { + this->signParams.insert(std::make_pair(it->first, options->GetString(it->first))); + continue; + } + + char* passWord = options->GetChars(it->first); + if (passWord == nullptr) { + SIGNATURE_TOOLS_LOGE("Get password error"); + return false; + } + std::string strPwd = passWord; + this->signParams.insert(std::make_pair(it->first, strPwd)); + } + } + + return true; +} + bool SignProvider::CheckParams(Options* options) { std::vector paramFileds; diff --git a/hapsigntool_cpp/hap/sign/include/bc_pkcs7_generator.h b/hapsigntool_cpp/hap/sign/include/bc_pkcs7_generator.h index cce86f75..fb2c4ae1 100644 --- a/hapsigntool_cpp/hap/sign/include/bc_pkcs7_generator.h +++ b/hapsigntool_cpp/hap/sign/include/bc_pkcs7_generator.h @@ -38,7 +38,7 @@ public: virtual ~BCPkcs7Generator(); int GenerateSignedData(const std::string& content, SignerConfig* signerConfig, std::string& ret) override; private: - int PackagePKCS7(const std::string& content, std::shared_ptr signer, + int PackagePKCS7(const std::string& content, const std::shared_ptr& signer, const std::string& sigAlg, std::string& ret); }; } // namespace SignatureTools diff --git a/hapsigntool_cpp/hap/sign/include/sign_elf.h b/hapsigntool_cpp/hap/sign/include/sign_elf.h index a554311d..a65ac8fd 100644 --- a/hapsigntool_cpp/hap/sign/include/sign_elf.h +++ b/hapsigntool_cpp/hap/sign/include/sign_elf.h @@ -41,22 +41,22 @@ private: static constexpr int FILE_BUFFER_BLOCK = 16384; static const std::string CODESIGN_OFF; - static bool AlignFileBy4kBytes(std::string& inputFile, std::string& tmp); + static bool AlignFileBy4kBytes(const std::string& inputFile, std::string& tmp); static bool WriteBlockDataToFile(SignerConfig& signerConfig, - std::string inputFile, std::string outputFile, - std::string profileSigned, - std::map signParams); - static bool WriteSignedElf(std::string inputFile, - std::list& signBlockList, std::string outputFile); + const std::string& inputFile, std::string& outputFile, + const std::string &profileSigned, + const std::map& signParams); + static bool WriteSignedElf(const std::string &inputFile, + std::list& signBlockList, std::string &outputFile); static bool WriteSignBlockData(std::list& signBlockList, std::ofstream& fileOutputStream); static bool GenerateSignBlockHead(std::list& signDataList); static SignBlockData GenerateProfileSignByte(std::string profileFile, std::string profileSigned); - static bool GenerateCodeSignByte(SignerConfig& signerConfig, std::map signParams, - std::string inputFile, int blockNum, - long binFileLen, SignBlockData** codeSign); - static bool WriteSignHeadDataToOutputFile(std::string inputFile, std::string outputFile, int blockNum); - static bool IsLongOverflowInteger(int64_t num); - static bool IsLongOverflowShort(int64_t num); + static bool GenerateCodeSignByte(SignerConfig& signerConfig, const std::map &signParams, + const std::string &inputFile, const int blockNum, + const long binFileLen, SignBlockData** codeSign); + static bool WriteSignHeadDataToOutputFile(const std::string &inputFile, const std::string &outputFile, const int blockNum); + static bool IsLongOverflowInteger(const int64_t num); + static bool IsLongOverflowShort(const int64_t num); }; } // namespace SignatureTools } // namespace OHOS diff --git a/hapsigntool_cpp/hap/sign/include/sign_hap.h b/hapsigntool_cpp/hap/sign/include/sign_hap.h index 40b9501c..85c901fd 100644 --- a/hapsigntool_cpp/hap/sign/include/sign_hap.h +++ b/hapsigntool_cpp/hap/sign/include/sign_hap.h @@ -20,7 +20,6 @@ #include #include "hap_utils.h" -#include "hap_verify_result.h" #include "signer_config.h" #include "hap_signer_block_utils.h" #include "securec.h" diff --git a/hapsigntool_cpp/hap/sign/src/bc_pkcs7_generator.cpp b/hapsigntool_cpp/hap/sign/src/bc_pkcs7_generator.cpp index ba729012..b03a24f1 100644 --- a/hapsigntool_cpp/hap/sign/src/bc_pkcs7_generator.cpp +++ b/hapsigntool_cpp/hap/sign/src/bc_pkcs7_generator.cpp @@ -58,7 +58,7 @@ int BCPkcs7Generator::GenerateSignedData(const std::string& content, } return result; } -int BCPkcs7Generator::PackagePKCS7(const std::string& content, std::shared_ptr signer, +int BCPkcs7Generator::PackagePKCS7(const std::string& content, const std::shared_ptr& signer, const std::string& sigAlg, std::string& ret) { PKCS7Data p7Data; diff --git a/hapsigntool_cpp/hap/sign/src/sign_elf.cpp b/hapsigntool_cpp/hap/sign/src/sign_elf.cpp index 3f66fc7a..cc00f4eb 100644 --- a/hapsigntool_cpp/hap/sign/src/sign_elf.cpp +++ b/hapsigntool_cpp/hap/sign/src/sign_elf.cpp @@ -58,7 +58,7 @@ bool SignElf::Sign(SignerConfig& signerConfig, std::map signParams) + const std::string &inputFile, std::string& outputFile, const std::string& profileSigned, + const std::map& signParams) { std::string proFile; if (signParams.find(ParamConstants::PARAM_BASIC_PROFILE) != signParams.end()) { @@ -143,7 +143,7 @@ bool SignElf::WriteBlockDataToFile(SignerConfig& signerConfig, return WriteSignedElf(inputFile, signDataList, outputFile); } -bool SignElf::WriteSignedElf(std::string inputFile, std::list& signBlockList, std::string outputFile) +bool SignElf::WriteSignedElf(const std::string &inputFile, std::list& signBlockList, std::string &outputFile) { std::ifstream fileInputStream(inputFile, std::ios::binary); std::ofstream fileOutputStream(outputFile, std::ios::binary); @@ -239,8 +239,8 @@ SignBlockData SignElf::GenerateProfileSignByte(std::string profileFile, std::str return SignBlockData(profileFile, isSigned); } -bool SignElf::GenerateCodeSignByte(SignerConfig& signerConfig, std::map signParams, - std::string inputFile, int blockNum, long binFileLen, SignBlockData** codeSign) +bool SignElf::GenerateCodeSignByte(SignerConfig& signerConfig, const std::map &signParams, + const std::string &inputFile, const int blockNum, const long binFileLen, SignBlockData** codeSign) { if (signParams.at(ParamConstants::PARAM_SIGN_CODE) == CODESIGN_OFF) { PrintErrorNumberMsg("SIGN_ERROR", SIGN_ERROR, "[SignElf] check pamams signCode = 0 error."); @@ -264,7 +264,7 @@ bool SignElf::GenerateCodeSignByte(SignerConfig& signerConfig, std::map -#include - -#include "export_define.h" -#include "byte_buffer.h" -#include "profile_info.h" - -namespace OHOS { -namespace SignatureTools { -enum class ModeDev { - DEFAULT = 0, - DEV, - NON_DEV, -}; - -enum VerifyHapResultCode { - VERIFY_SUCCESS = 0, - FILE_PATH_INVALID = -1, - OPEN_FILE_ERROR = -2, - SIGNATURE_NOT_FOUND = -3, - GET_DIGEST_FAIL = -4, - NO_PROFILE_BLOCK_FAIL = -5, - VERIFY_SIGNATURE_FAIL = -6, - VERIFY_SOURCE_INIT_FAIL = -7, - VERIFY_INTEGRITY_FAIL = -8, - FILE_SIZE_TOO_LARGE = -9, - GET_PUBLICKEY_FAIL = -10, - VERIFY_APP_PKCS7_FAIL = -11, - PROFILE_PARSE_FAIL = -12, - APP_SOURCE_NOT_TRUSTED = -13, - GET_SIGNATURE_FAIL = -14, - OUT_PUT_FILE_FAIL = -15, - VERIFY_CODE_SIGN_FAIL = -16, -}; - -enum GetOptionalBlockResultCode { - GET_SUCCESS = 0, - NO_THIS_BLOCK_IN_PACKAGE = 1, -}; - -struct OptionalBlock { - int32_t optionalType = 0; - ByteBuffer optionalBlockValue; -}; - -class HapVerifyResult { -public: - DLL_EXPORT HapVerifyResult(); - DLL_EXPORT ~HapVerifyResult() = default; - DLL_EXPORT int32_t GetVersion() const; - DLL_EXPORT void SetVersion(int32_t signatureVersion); - DLL_EXPORT void SetPkcs7SignBlock(const ByteBuffer& pkcs7); - DLL_EXPORT void SetPkcs7ProfileBlock(const ByteBuffer& pkcs7); - DLL_EXPORT void SetOptionalBlocks(const std::vector& option); - DLL_EXPORT void SetProvisionInfo(const ProfileInfo& info); - DLL_EXPORT int32_t GetProperty(std::string& property) const; - DLL_EXPORT ProfileInfo GetProvisionInfo() const; - DLL_EXPORT std::vector GetPublicKey() const; - DLL_EXPORT std::vector GetSignature() const; - DLL_EXPORT std::vector GetProfile() const; - DLL_EXPORT void SetProfile(std::vector profile); - void SetPublicKey(const std::vector& inputPubkeys); - void SetSignature(const std::vector& inputSignatures); - DLL_EXPORT int32_t GetBlockFromOptionalBlocks(int32_t blockType, std::string& block) const; - -private: - int32_t m_version = 0; - std::vector m_publicKeys; - std::vector m_signatures; - ByteBuffer m_pkcs7SignBlock; - ByteBuffer m_pkcs7ProfileBlock; - std::vector m_optionalBlocks; - ProfileInfo m_provisionInfo; - std::vector m_profile; -}; -} // namespace SignatureTools -} // namespace OHOS -#endif // SIGNATRUETOOLS_VERIFY_RESULT_H diff --git a/hapsigntool_cpp/hap/verify/include/verify_bin.h b/hapsigntool_cpp/hap/verify/include/verify_bin.h index 41948878..1dc6c64a 100644 --- a/hapsigntool_cpp/hap/verify/include/verify_bin.h +++ b/hapsigntool_cpp/hap/verify/include/verify_bin.h @@ -28,7 +28,7 @@ public: bool Verify(Options* options); private: - bool VerifyBinFile(const std::string& binFile, HapVerifyResult& verifyResult, + bool VerifyBinFile(const std::string& binFile, std::vector& profileVec, Options* options, Pkcs7Context& pkcs7Context); bool VerifyBinDigest(SignBlockInfo& signBlockInfo); }; diff --git a/hapsigntool_cpp/hap/verify/include/verify_elf.h b/hapsigntool_cpp/hap/verify/include/verify_elf.h index 6045a890..78303364 100644 --- a/hapsigntool_cpp/hap/verify/include/verify_elf.h +++ b/hapsigntool_cpp/hap/verify/include/verify_elf.h @@ -20,7 +20,6 @@ #include #include "options.h" -#include "hap_verify_result.h" #include "hw_block_data.h" #include "signing_block.h" #include "pkcs7_context.h" @@ -48,10 +47,10 @@ public: SignBlockInfo& signBlockInfo); static bool GetRawContent(std::vector& contentVec, std::string& rawContent); static bool VerifyP7b(std::unordered_map& signBlockMap, Options* options, - Pkcs7Context& pkcs7Context, HapVerifyResult& verifyResult, std::string& profileJson); + Pkcs7Context& pkcs7Context, std::vector& profileVec, std::string& profileJson); private: - bool VerifyElfFile(const std::string& elfFile, HapVerifyResult& verifyResult, + bool VerifyElfFile(const std::string& elfFile, std::vector& profileVec, Options* options, Pkcs7Context& pkcs7Context); static bool CheckMagicAndVersion(std::vector& bytes, int64_t& offset, const std::string fileType); diff --git a/hapsigntool_cpp/hap/verify/include/verify_hap.h b/hapsigntool_cpp/hap/verify/include/verify_hap.h index bf0cb744..aafb3008 100644 --- a/hapsigntool_cpp/hap/verify/include/verify_hap.h +++ b/hapsigntool_cpp/hap/verify/include/verify_hap.h @@ -18,7 +18,6 @@ #include "byte_buffer.h" #include "random_access_file.h" -#include "hap_verify_result.h" #include "profile_verify.h" #include "verify_hap_openssl_utils.h" #include "signature_info.h" @@ -41,36 +40,36 @@ public: static const int OFFSET_ZERO = 0; static const int OFFSET_FOUR = 4; static const int OFFSET_EIGHT = 8; - int32_t Verify(const std::string& filePath, HapVerifyResult& hapVerifyV1Result, Options* options); + + VerifyHap(); + VerifyHap(bool isPrintCert); + void setIsPrintCert(bool printCert); + + bool HapOutPutPkcs7(PKCS7* p7, const std::string& outPutPath); DLL_EXPORT bool CheckFilePath(const std::string& filePath, std::string& standardFilePath); - static bool HapOutPutPkcs7(PKCS7* p7, const std::string& outPutPath); - static bool HapOutPutCertChain(std::vector& certs, const std::string& outPutPath); - int32_t VerifyElfProfile(std::vector& profileData, HapVerifyResult& hapVerifyV1Result, - Options* options, Pkcs7Context& pkcs7Context); - int32_t WriteVerifyOutput(Pkcs7Context& pkcs7Context, std::vector profile, Options* options); - int32_t InithapVerify(RandomAccessFile& hapFile, const std::string& filePath, - SignatureInfo& hapSignInfo, HapVerifyResult& hapVerifyV1Result); - int32_t Verify(RandomAccessFile& hapFile, HapVerifyResult& hapVerifyV1Result, Options* options, - const std::string& filePath); + + bool outputOptionalBlocks(const std::string& outputProfileFile, const std::string& outputProofFile, + const std::string& outputPropertyFile, + const std::vector& optionBlocks); + bool writeOptionalBytesToFile(const OptionalBlock& optionalBlock, const std::string& path); + + bool HapOutPutCertChain(std::vector& certs, const std::string& outPutPath); + + int32_t Verify(const std::string& filePath, Options* options); + + int32_t WriteVerifyOutput(Pkcs7Context& pkcs7Context, std::vector& profile, Options* options); + + int32_t Verify(RandomAccessFile& hapFile, Options* options, const std::string& filePath); + bool CheckCodeSign(const std::string& hapFilePath, const std::vector& optionalBlocks)const; static int GetProfileContent(const std::string profile, std::string& ret); - bool VerifyAppSourceAndParseProfile(Pkcs7Context& pkcs7Context, const ByteBuffer& hapProfileBlock, - HapVerifyResult& hapVerifyV1Result, bool& profileNeadWriteCrl); + bool VerifyAppPkcs7(Pkcs7Context& pkcs7Context, const ByteBuffer& hapSignatureBlock); DLL_EXPORT bool GetDigestAndAlgorithm(Pkcs7Context& digest); - DLL_EXPORT bool ParseAndVerifyProfileIfNeed(const std::string& profile, ProfileInfo& provisionInfo, - bool isCallParseAndVerify); - bool IsAppDistributedTypeAllowInstall(const AppDistType& type, const ProfileInfo& provisionInfo) const; - DLL_EXPORT bool VerifyProfileInfo(const Pkcs7Context& pkcs7Context, const Pkcs7Context& profileContext, - ProfileInfo& provisionInfo); - DLL_EXPORT bool GenerateAppId(ProfileInfo& provisionInfo); - DLL_EXPORT bool GenerateFingerprint(ProfileInfo& provisionInfo); - bool VerifyProfileSignature(const Pkcs7Context& pkcs7Context, Pkcs7Context& profileContext); - void SetProfileBlockData(const Pkcs7Context& pkcs7Context, const ByteBuffer& hapProfileBlock, - ProfileInfo& provisionInfo); - void SetOrganization(ProfileInfo& provisionInfo); - bool NeedParseJson(const ByteBuffer& buffer); + +private: + bool isPrintCert; }; } // namespace SignatureTools } // namespace OHOS diff --git a/hapsigntool_cpp/hap/verify/src/hap_verify_result.cpp b/hapsigntool_cpp/hap/verify/src/hap_verify_result.cpp deleted file mode 100644 index 2686ce17..00000000 --- a/hapsigntool_cpp/hap/verify/src/hap_verify_result.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2024-2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "hap_signer_block_utils.h" -#include "hap_verify_result.h" - -namespace OHOS { -namespace SignatureTools { -HapVerifyResult::HapVerifyResult() - : m_version(0), m_publicKeys(), m_signatures(), m_pkcs7SignBlock(), - m_pkcs7ProfileBlock(), m_optionalBlocks(), m_provisionInfo() -{ -} - -void HapVerifyResult::SetPkcs7SignBlock(const ByteBuffer& pkcs7) -{ - m_pkcs7SignBlock = pkcs7; -} - -void HapVerifyResult::SetPkcs7ProfileBlock(const ByteBuffer& pkcs7) -{ - m_pkcs7ProfileBlock = pkcs7; -} - -void HapVerifyResult::SetOptionalBlocks(const std::vector& option) -{ - m_optionalBlocks = option; -} - -int32_t HapVerifyResult::GetVersion() const -{ - return m_version; -} - -void HapVerifyResult::SetVersion(int32_t signatureVersion) -{ - m_version = signatureVersion; -} - -std::vector HapVerifyResult::GetPublicKey() const -{ - return m_publicKeys; -} - -std::vector HapVerifyResult::GetSignature() const -{ - return m_signatures; -} - -void HapVerifyResult::SetPublicKey(const std::vector& inputPubkeys) -{ - m_publicKeys = inputPubkeys; -} - -void HapVerifyResult::SetSignature(const std::vector& inputSignatures) -{ - m_signatures = inputSignatures; -} - -int32_t HapVerifyResult::GetProperty(std::string& property) const -{ - return GetBlockFromOptionalBlocks(PROPERTY_BLOB, property); -} - -int32_t HapVerifyResult::GetBlockFromOptionalBlocks(int32_t blockType, std::string& block) const -{ - for (unsigned long i = 0; i < m_optionalBlocks.size(); i++) { - if (m_optionalBlocks[i].optionalType == blockType) { - const ByteBuffer& option = m_optionalBlocks[i].optionalBlockValue; - block += std::string(option.GetBufferPtr(), option.GetCapacity()); - return GET_SUCCESS; - } - } - return NO_THIS_BLOCK_IN_PACKAGE; -} - -void HapVerifyResult::SetProvisionInfo(const ProfileInfo& info) -{ - m_provisionInfo = info; -} - -ProfileInfo HapVerifyResult::GetProvisionInfo() const -{ - return m_provisionInfo; -} - -std::vector HapVerifyResult::GetProfile() const -{ - return m_profile; -} - -void HapVerifyResult::SetProfile(std::vector profile) -{ - this->m_profile = profile; -} -} // namespace SignatureTools -} // namespace OHOS \ No newline at end of file diff --git a/hapsigntool_cpp/hap/verify/src/verify_bin.cpp b/hapsigntool_cpp/hap/verify/src/verify_bin.cpp index 243fc3b2..e1149e2b 100644 --- a/hapsigntool_cpp/hap/verify/src/verify_bin.cpp +++ b/hapsigntool_cpp/hap/verify/src/verify_bin.cpp @@ -38,24 +38,24 @@ bool VerifyBin::Verify(Options* options) return false; } // verify bin - HapVerifyResult verifyResult; + std::vector profileVec; Pkcs7Context pkcs7Context; - bool verifyBinFileFLag = VerifyBinFile(filePath, verifyResult, options, pkcs7Context); + bool verifyBinFileFLag = VerifyBinFile(filePath, profileVec, options, pkcs7Context); if (!verifyBinFileFLag) { SIGNATURE_TOOLS_LOGE("verify bin file %s failed!", filePath.c_str()); return false; } // write certificate and p7b file - VerifyHap hapVerifyV2; - int32_t writeFlag = hapVerifyV2.WriteVerifyOutput(pkcs7Context, verifyResult.GetProfile(), options); - if (writeFlag != VERIFY_SUCCESS) { + VerifyHap hapVerify(false); + int32_t writeFlag = hapVerify.WriteVerifyOutput(pkcs7Context, profileVec, options); + if (writeFlag != RET_OK) { SIGNATURE_TOOLS_LOGE("write elf output failed on verify bin!"); return false; } return true; } -bool VerifyBin::VerifyBinFile(const std::string& binFile, HapVerifyResult& verifyResult, +bool VerifyBin::VerifyBinFile(const std::string& binFile, std::vector& profileVec, Options* options, Pkcs7Context& pkcs7Context) { SignBlockInfo signBlockInfo(true); @@ -67,7 +67,7 @@ bool VerifyBin::VerifyBinFile(const std::string& binFile, HapVerifyResult& verif // verify profile std::string profileJson; bool verifyP7bFlag = VerifyElf::VerifyP7b(signBlockInfo.GetSignBlockMap(), options, pkcs7Context, - verifyResult, profileJson); + profileVec, profileJson); if (!verifyP7bFlag) { SIGNATURE_TOOLS_LOGE("verify profile failed on verify bin %s", binFile.c_str()); return false; @@ -83,8 +83,8 @@ bool VerifyBin::VerifyBinFile(const std::string& binFile, HapVerifyResult& verif bool VerifyBin::VerifyBinDigest(SignBlockInfo& signBlockInfo) { - std::vector rawDigest = signBlockInfo.GetRawDigest(); - std::vector generatedDig = signBlockInfo.GetFileDigest(); + std::vector& rawDigest = signBlockInfo.GetRawDigest(); + std::vector& generatedDig = signBlockInfo.GetFileDigest(); bool isEqual = rawDigest.empty() || generatedDig.empty() || !std::equal(rawDigest.begin(), rawDigest.end(), generatedDig.begin()); if (isEqual) { diff --git a/hapsigntool_cpp/hap/verify/src/verify_elf.cpp b/hapsigntool_cpp/hap/verify/src/verify_elf.cpp index 31eefa11..88733e90 100644 --- a/hapsigntool_cpp/hap/verify/src/verify_elf.cpp +++ b/hapsigntool_cpp/hap/verify/src/verify_elf.cpp @@ -54,24 +54,24 @@ bool VerifyElf::Verify(Options* options) return false; } // verify elf - HapVerifyResult verifyResult; + std::vector profileVec; Pkcs7Context pkcs7Context; - bool verifyElfFileFlag = VerifyElfFile(filePath, verifyResult, options, pkcs7Context); + bool verifyElfFileFlag = VerifyElfFile(filePath, profileVec, options, pkcs7Context); if (!verifyElfFileFlag) { SIGNATURE_TOOLS_LOGE("verify elf file %s failed!", filePath.c_str()); return false; } // write certificate and p7b file - VerifyHap hapVerifyV2; - int32_t writeVerifyOutputFlag = hapVerifyV2.WriteVerifyOutput(pkcs7Context, verifyResult.GetProfile(), options); - if (writeVerifyOutputFlag != VERIFY_SUCCESS) { + VerifyHap hapVerify(false); + int32_t writeVerifyOutputFlag = hapVerify.WriteVerifyOutput(pkcs7Context, profileVec, options); + if (writeVerifyOutputFlag != RET_OK) { SIGNATURE_TOOLS_LOGE("write elf output failed on verify elf!"); return false; } return true; } -bool VerifyElf::VerifyElfFile(const std::string& elfFile, HapVerifyResult& verifyResult, +bool VerifyElf::VerifyElfFile(const std::string& elfFile, std::vector& profileVec, Options* options, Pkcs7Context& pkcs7Context) { SignBlockInfo signBlockInfo(false); @@ -82,7 +82,7 @@ bool VerifyElf::VerifyElfFile(const std::string& elfFile, HapVerifyResult& verif } // verify profile std::string profileJson; - bool verifyP7b = VerifyP7b(signBlockInfo.GetSignBlockMap(), options, pkcs7Context, verifyResult, profileJson); + bool verifyP7b = VerifyP7b(signBlockInfo.GetSignBlockMap(), options, pkcs7Context, profileVec, profileJson); if (!verifyP7b) { SIGNATURE_TOOLS_LOGE("verify profile failed on verify elf %s", elfFile.c_str()); return false; @@ -104,31 +104,33 @@ bool VerifyElf::VerifyElfFile(const std::string& elfFile, HapVerifyResult& verif bool VerifyElf::VerifyP7b(std::unordered_map& signBlockMap, Options* options, Pkcs7Context& pkcs7Context, - HapVerifyResult& verifyResult, std::string& profileJson) + std::vector& profileVec, std::string& profileJson) { if (signBlockMap.find(PROFILE_NOSIGNED_BLOCK) != signBlockMap.end()) { // verify unsigned profile - std::vector profileByte = signBlockMap.find(PROFILE_NOSIGNED_BLOCK)->second.GetValue(); + std::vector& profileByte = signBlockMap.find(PROFILE_NOSIGNED_BLOCK)->second.GetValue(); std::string fromByteStr(profileByte.begin(), profileByte.end()); profileJson = fromByteStr; - verifyResult.SetProfile(profileByte); + profileVec = profileByte; SIGNATURE_TOOLS_LOGW("profile is not signed."); } else if (signBlockMap.find(PROFILE_SIGNED_BLOCK) != signBlockMap.end()) { // verify signed profile SigningBlock profileSign = signBlockMap.find(PROFILE_SIGNED_BLOCK)->second; - std::vector profileByte = profileSign.GetValue(); + std::vector& profileByte = profileSign.GetValue(); bool getRawContentFlag = GetRawContent(profileByte, profileJson); if (!getRawContentFlag) { SIGNATURE_TOOLS_LOGE("get profile content failed on verify elf!"); return false; } - VerifyHap hapVerifyV2; - int32_t resultCode = hapVerifyV2.VerifyElfProfile(profileByte, verifyResult, options, pkcs7Context); - if (resultCode != VERIFY_SUCCESS) { + VerifyHap hapVerify(false); + std::unique_ptr profileBuffer = + std::make_unique((char*)profileByte.data(), profileByte.size()); + bool resultFlag = hapVerify.VerifyAppPkcs7(pkcs7Context, *profileBuffer); + if (!resultFlag) { SIGNATURE_TOOLS_LOGE("verify elf profile failed on verify elf!"); return false; } - verifyResult.SetProfile(profileByte); + profileVec = profileByte; SIGNATURE_TOOLS_LOGI("verify profile success."); } else { SIGNATURE_TOOLS_LOGW("can not found profile sign block."); @@ -171,7 +173,7 @@ bool VerifyElf::GetSignBlockInfo(const std::string& file, SignBlockInfo& signBlo // get bin file digest bool needGenerateDigest = signBlockInfo.GetNeedGenerateDigest(); if (needGenerateDigest) { - std::vector signatrue = signBlockInfo.GetSignBlockMap().find(0)->second.GetValue(); + std::vector& signatrue = signBlockInfo.GetSignBlockMap().find(0)->second.GetValue(); bool getFileDigest = GetFileDigest(*((std::vector*)fileBytes), signatrue, signBlockInfo); if (!getFileDigest) { SIGNATURE_TOOLS_LOGE("getFileDigest failed on verify bin file %s", file.c_str()); @@ -201,7 +203,7 @@ bool VerifyElf::GetFileDigest(std::vector& fileBytes, std::vector& fileBytes, SignBlockInfo& signBlockInfo) { // get algId - std::vector rawDigest = signBlockInfo.GetRawDigest(); + std::vector& rawDigest = signBlockInfo.GetRawDigest(); std::unique_ptr digBuffer = std::make_unique(rawDigest.size()); digBuffer->PutData(rawDigest.data(), rawDigest.size()); digBuffer->Flip(); diff --git a/hapsigntool_cpp/hap/verify/src/verify_hap.cpp b/hapsigntool_cpp/hap/verify/src/verify_hap.cpp index 7616cd8b..498b8c66 100644 --- a/hapsigntool_cpp/hap/verify/src/verify_hap.cpp +++ b/hapsigntool_cpp/hap/verify/src/verify_hap.cpp @@ -31,6 +31,8 @@ #include "param_constants.h" #include "file_utils.h" #include "nlohmann/json.hpp" +#include "hap_utils.h" +#include "cert_tools.h" #include "verify_hap.h" using namespace nlohmann; @@ -46,6 +48,21 @@ const std::string VerifyHap::HQF_APP_PATTERN = "[^]*.hqf$"; const std::string VerifyHap::HSP_APP_PATTERN = "[^]*.hsp$"; const std::string VerifyHap::APP_APP_PATTERN = "[^]*.app$"; static constexpr int ZIP_HEAD_OF_SUBSIGNING_BLOCK_LENGTH = 12; + +VerifyHap::VerifyHap() : isPrintCert(true) +{ +} + +VerifyHap::VerifyHap(bool printCert) +{ + isPrintCert = printCert; +} + +void VerifyHap::setIsPrintCert(bool printCert) +{ + isPrintCert = printCert; +} + bool VerifyHap::HapOutPutPkcs7(PKCS7* p7, const std::string& outPutPath) { std::string p7bContent = StringUtils::Pkcs7ToString(p7); @@ -60,8 +77,51 @@ bool VerifyHap::HapOutPutPkcs7(PKCS7* p7, const std::string& outPutPath) return true; } +bool VerifyHap::outputOptionalBlocks(const std::string& outputProfileFile, const std::string& outputProofFile, + const std::string& outputPropertyFile, const std::vector& optionBlocks) +{ + for (auto& optionBlock : optionBlocks) { + if (optionBlock.optionalType == HapUtils::HAP_PROFILE_BLOCK_ID) { + if (!writeOptionalBytesToFile(optionBlock, outputProfileFile)) { + return false; + } + } else if(optionBlock.optionalType == HapUtils::HAP_PROPERTY_BLOCK_ID) { + if (!writeOptionalBytesToFile(optionBlock, outputPropertyFile)) { + return false; + } + } else if(optionBlock.optionalType == HapUtils::HAP_PROOF_OF_ROTATION_BLOCK_ID) { + if (!writeOptionalBytesToFile(optionBlock, outputPropertyFile)) { + return false; + } + } else { + SIGNATURE_TOOLS_LOGE("Unsupported Block Id: %d", optionBlock.optionalType); + return false; + } + } + return true; +} +bool VerifyHap::writeOptionalBytesToFile(const OptionalBlock& optionalBlock, const std::string& path) +{ + if (path.empty()) { + return true; + } + std::string optionBlockString(optionalBlock.optionalBlockValue.GetBufferPtr(), + optionalBlock.optionalBlockValue.GetCapacity()); + if (FileUtils::Write(optionBlockString, path) < 0) { + PrintErrorNumberMsg("IO_ERROR", IO_ERROR, "write optional bytes to file:" + path + " falied!"); + return false; + } + return true; +} + bool VerifyHap::HapOutPutCertChain(std::vector& certs, const std::string& outPutPath) { + if (isPrintCert) { + if (!CertTools::PrintCertChainToCmd(certs)) { + SIGNATURE_TOOLS_LOGE("print cert chain to cmd failed\n"); + return false; + } + } VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGD("outPutPath = %s", outPutPath.c_str()); std::vector certStr; @@ -80,21 +140,21 @@ bool VerifyHap::HapOutPutCertChain(std::vector& certs, const std::string& return true; } -int32_t VerifyHap::Verify(const std::string& filePath, HapVerifyResult& hapVerifyV1Result, Options* options) +int32_t VerifyHap::Verify(const std::string& filePath, Options* options) { SIGNATURE_TOOLS_LOGD("Start Verify"); std::string standardFilePath; if (!CheckFilePath(filePath, standardFilePath)) { SIGNATURE_TOOLS_LOGE("Check file path%s failed", filePath.c_str()); - return FILE_PATH_INVALID; + return IO_ERROR; } RandomAccessFile hapFile; if (!hapFile.Init(standardFilePath)) { SIGNATURE_TOOLS_LOGE("%s init failed", standardFilePath.c_str()); - return OPEN_FILE_ERROR; + return ZIP_ERROR; } - int32_t resultCode = Verify(hapFile, hapVerifyV1Result, options, filePath); - if (resultCode != VERIFY_SUCCESS) { + int32_t resultCode = Verify(hapFile, options, filePath); + if (resultCode != RET_OK) { PrintErrorNumberMsg("VERIFY_ERROR", VERIFY_ERROR, standardFilePath + " verify failed"); } return resultCode; @@ -121,74 +181,57 @@ bool VerifyHap::CheckFilePath(const std::string& filePath, std::string& standard return true; } -int32_t VerifyHap::InithapVerify(RandomAccessFile& hapFile, const std::string& filePath, - SignatureInfo& hapSignInfo, HapVerifyResult& hapVerifyV1Result) +int32_t VerifyHap::Verify(RandomAccessFile& hapFile, Options* options, const std::string& filePath) { + SignatureInfo hapSignInfo; if (!HapSignerBlockUtils::FindHapSignature(hapFile, hapSignInfo)) { - return SIGNATURE_NOT_FOUND; + return ZIP_ERROR; } + if (CheckCodeSign(filePath, hapSignInfo.optionBlocks) == false) { SIGNATURE_TOOLS_LOGE("check coode sign failed\n"); - return VERIFY_CODE_SIGN_FAIL; + return VERIFY_ERROR; } - hapVerifyV1Result.SetVersion(hapSignInfo.version); - hapVerifyV1Result.SetPkcs7SignBlock(hapSignInfo.hapSignatureBlock); - hapVerifyV1Result.SetPkcs7ProfileBlock(hapSignInfo.hapSignatureBlock); - hapVerifyV1Result.SetOptionalBlocks(hapSignInfo.optionBlocks); - return VERIFY_SUCCESS; -} -int32_t VerifyHap::Verify(RandomAccessFile& hapFile, HapVerifyResult& hapVerifyV1Result, - Options* options, const std::string& filePath) -{ - SignatureInfo hapSignInfo; - if (InithapVerify(hapFile, filePath, hapSignInfo, hapVerifyV1Result) != VERIFY_SUCCESS) { - return SIGNATURE_NOT_FOUND; - } Pkcs7Context pkcs7Context; if (!VerifyAppPkcs7(pkcs7Context, hapSignInfo.hapSignatureBlock)) { - return VERIFY_APP_PKCS7_FAIL; - } - int32_t profileIndex = 0; - if (!HapSignerBlockUtils::GetOptionalBlockIndex(hapSignInfo.optionBlocks, PROFILE_BLOB, profileIndex)) { - return NO_PROFILE_BLOCK_FAIL; - } - bool profileNeedWriteCrl = false; - if (!VerifyAppSourceAndParseProfile(pkcs7Context, hapSignInfo.optionBlocks[profileIndex].optionalBlockValue, - hapVerifyV1Result, profileNeedWriteCrl)) { - SIGNATURE_TOOLS_LOGE("APP source is not trusted"); - return APP_SOURCE_NOT_TRUSTED; + return PARSE_ERROR; } + if (!GetDigestAndAlgorithm(pkcs7Context)) { SIGNATURE_TOOLS_LOGE("Get digest failed"); - return GET_DIGEST_FAIL; + return PARSE_ERROR; } - std::vector publicKeys; - if (!VerifyHapOpensslUtils::GetPublickeys(pkcs7Context.certChain[0], publicKeys)) { - SIGNATURE_TOOLS_LOGE("Get publicKeys failed"); - return GET_PUBLICKEY_FAIL; + + STACK_OF(X509_CRL)* x509Crl = nullptr; + if (!VerifyHapOpensslUtils::GetCrlStack(pkcs7Context.p7, x509Crl)) { + SIGNATURE_TOOLS_LOGE("Get Crl stack failed"); + return PARSE_ERROR; } - hapVerifyV1Result.SetPublicKey(publicKeys); - std::vector certSignatures; - if (!VerifyHapOpensslUtils::GetSignatures(pkcs7Context.certChain[0], certSignatures)) { - SIGNATURE_TOOLS_LOGE("Get sianatures failed"); - return GET_SIGNATURE_FAIL; + + if (!VerifyCertOpensslUtils::VerifyCrl(pkcs7Context.certChain[0], x509Crl, pkcs7Context)) { + SIGNATURE_TOOLS_LOGE("Verify Crl stack failed"); + return VERIFY_ERROR; } - hapVerifyV1Result.SetSignature(certSignatures); + if (!HapSignerBlockUtils::VerifyHapIntegrity(pkcs7Context, hapFile, hapSignInfo)) { SIGNATURE_TOOLS_LOGE("Verify Integrity failed"); - return VERIFY_INTEGRITY_FAIL; + return VERIFY_ERROR; } - if (!VerifyHap::HapOutPutCertChain(pkcs7Context.certChain[0], + if (!HapOutPutCertChain(pkcs7Context.certChain[0], options->GetString(Options::OUT_CERT_CHAIN))) { SIGNATURE_TOOLS_LOGE("out put cert chain failed"); - return OUT_PUT_FILE_FAIL; + return IO_ERROR; } - if (!VerifyHap::HapOutPutPkcs7(pkcs7Context.p7, options->GetString(Options::OUT_PROFILE))) { - SIGNATURE_TOOLS_LOGE("out put p7b failed"); - return OUT_PUT_FILE_FAIL; - } - return VERIFY_SUCCESS; + + if (!outputOptionalBlocks(options->GetString(ParamConstants::PARAM_VERIFY_PROFILE_FILE), + options->GetString(ParamConstants::PARAM_VERIFY_PROOF_FILE), + options->GetString(ParamConstants::PARAM_VERIFY_PROPERTY_FILE), + hapSignInfo.optionBlocks)) { + SIGNATURE_TOOLS_LOGE("output Optional Blocks failed"); + return IO_ERROR; + } + return RET_OK; } bool VerifyHap::CheckCodeSign(const std::string& hapFilePath, @@ -292,194 +335,6 @@ bool VerifyHap::VerifyAppPkcs7(Pkcs7Context& pkcs7Context, const ByteBuffer& hap return true; } -bool VerifyHap::VerifyAppSourceAndParseProfile(Pkcs7Context& pkcs7Context, - const ByteBuffer& hapProfileBlock, - HapVerifyResult& hapVerifyV1Result, - bool& profileNeadWriteCrl) -{ - std::string certSubject; - if (!VerifyCertOpensslUtils::GetSubjectFromX509(pkcs7Context.certChain[0][0], certSubject)) { - SIGNATURE_TOOLS_LOGE("Get info of sign cert failed"); - return false; - } - SIGNATURE_TOOLS_LOGD("App signature subject: %s, issuer: %s", - certSubject.c_str(), pkcs7Context.certIssuer.c_str()); - if (!NeedParseJson(hapProfileBlock)) return true; - Pkcs7Context profileContext; - std::string profile; - if (!ProfileVerifyUtils::ParseProfile(profileContext, pkcs7Context, hapProfileBlock, profile)) { - SIGNATURE_TOOLS_LOGE("Parse profile pkcs7 failed"); - return false; - } - if (!VerifyProfileSignature(pkcs7Context, profileContext)) { - SIGNATURE_TOOLS_LOGE("VerifyProfileSignature failed"); - return false; - } - /* - * If app source is not trusted, verify profile. - * If profile is debug, check whether app signed cert is same as the debug cert in profile. - * If profile is release, do not allow installation of this app. - */ - bool isCallParseAndVerify = false; - ProfileInfo provisionInfo; - if (pkcs7Context.matchResult.matchState == DO_NOT_MATCH) { - if (!ProfileVerifyUtils::VerifyProfile(profileContext)) { - SIGNATURE_TOOLS_LOGE("profile verify failed"); - return false; - } - AppProvisionVerifyResult profileRet = ParseAndVerify(profile, provisionInfo); - if (profileRet != PROVISION_OK) { - SIGNATURE_TOOLS_LOGE("profile parsing failed, error: %d", static_cast(profileRet)); - return false; - } - if (!VerifyProfileInfo(pkcs7Context, profileContext, provisionInfo)) { - SIGNATURE_TOOLS_LOGE("VerifyProfileInfo failed"); - return false; - } - isCallParseAndVerify = true; - } - if (!ParseAndVerifyProfileIfNeed(profile, provisionInfo, isCallParseAndVerify)) { - return false; - } - if (!GenerateAppId(provisionInfo) || !GenerateFingerprint(provisionInfo)) { - SIGNATURE_TOOLS_LOGE("Generate appId or generate fingerprint failed"); - return false; - } - SetOrganization(provisionInfo); - SetProfileBlockData(pkcs7Context, hapProfileBlock, provisionInfo); - hapVerifyV1Result.SetProvisionInfo(provisionInfo); - profileNeadWriteCrl = profileContext.needWriteCrl; - return true; -} - -bool VerifyHap::NeedParseJson(const ByteBuffer& buffer) -{ - std::string profileArray_(buffer.GetBufferPtr(), buffer.GetCapacity()); - json obj = json::parse(profileArray_, nullptr, false); - if (!obj.is_discarded() && obj.is_structured()) { - return false; - } - return true; -} - -bool VerifyHap::VerifyProfileSignature(const Pkcs7Context& pkcs7Context, Pkcs7Context& profileContext) -{ - if (pkcs7Context.matchResult.matchState == MATCH_WITH_SIGN && - pkcs7Context.matchResult.source == APP_THIRD_PARTY_PRELOAD) { - if (!ProfileVerifyUtils::VerifyProfile(profileContext)) { - SIGNATURE_TOOLS_LOGE("profile verify failed"); - return false; - } - } - return true; -} - -bool VerifyHap::GenerateAppId(ProfileInfo& provisionInfo) -{ - std::string& certInProfile = provisionInfo.bundleInfo.distributionCertificate; - if (provisionInfo.bundleInfo.distributionCertificate.empty()) { - certInProfile = provisionInfo.bundleInfo.developmentCertificate; - SIGNATURE_TOOLS_LOGD("use development Certificate"); - } - std::string publicKey; - if (!VerifyCertOpensslUtils::GetPublickeyBase64FromPemCert(certInProfile, publicKey)) { - return false; - } - provisionInfo.appId = publicKey; - SIGNATURE_TOOLS_LOGD("provisionInfo.appId: %s", provisionInfo.appId.c_str()); - return true; -} - -bool VerifyHap::GenerateFingerprint(ProfileInfo& provisionInfo) -{ - std::string& certInProfile = provisionInfo.bundleInfo.distributionCertificate; - if (provisionInfo.bundleInfo.distributionCertificate.empty()) { - certInProfile = provisionInfo.bundleInfo.developmentCertificate; - SIGNATURE_TOOLS_LOGD("use development Certificate"); - } - std::string fingerprint; - if (!VerifyCertOpensslUtils::GetFingerprintBase64FromPemCert(certInProfile, fingerprint)) { - SIGNATURE_TOOLS_LOGE("Generate fingerprint from pem certificate failed"); - return false; - } - provisionInfo.fingerprint = fingerprint; - SIGNATURE_TOOLS_LOGD("fingerprint is : %s", fingerprint.c_str()); - return true; -} - -void VerifyHap::SetProfileBlockData(const Pkcs7Context& pkcs7Context, const ByteBuffer& hapProfileBlock, - ProfileInfo& provisionInfo) -{ - if (pkcs7Context.matchResult.matchState == MATCH_WITH_SIGN && - pkcs7Context.matchResult.source == APP_GALLARY) { - SIGNATURE_TOOLS_LOGD("profile is from app gallary and unnecessary to set profile block"); - return; - } - provisionInfo.profileBlockLength = hapProfileBlock.GetCapacity(); - SIGNATURE_TOOLS_LOGD("profile block data length is %d", provisionInfo.profileBlockLength); - if (provisionInfo.profileBlockLength == 0) { - SIGNATURE_TOOLS_LOGE("invalid profile block"); - return; - } - provisionInfo.profileBlock = std::make_unique(provisionInfo.profileBlockLength); - - if (memcpy_s(provisionInfo.profileBlock.get(), provisionInfo.profileBlockLength, - hapProfileBlock.GetBufferPtr(), - provisionInfo.profileBlockLength) != 0) { - SIGNATURE_TOOLS_LOGE("memcpy failed"); - } -} - -bool VerifyHap::VerifyProfileInfo(const Pkcs7Context& pkcs7Context, const Pkcs7Context& profileContext, - ProfileInfo& provisionInfo) -{ - std::string& certInProfile = provisionInfo.bundleInfo.developmentCertificate; - if (provisionInfo.type == ProvisionType::RELEASE) { - if (!IsAppDistributedTypeAllowInstall(provisionInfo.distributionType, provisionInfo)) { - SIGNATURE_TOOLS_LOGE("untrusted source app with release profile distributionType: %d", - static_cast(provisionInfo.distributionType)); - return false; - } - certInProfile = provisionInfo.bundleInfo.distributionCertificate; - SIGNATURE_TOOLS_LOGD("allow install app with release profile distributionType: %d", - static_cast(provisionInfo.distributionType)); - } - SIGNATURE_TOOLS_LOGD("provisionInfo.type: %d", static_cast(provisionInfo.type)); - return true; -} - -bool VerifyHap::IsAppDistributedTypeAllowInstall(const AppDistType& type, - const ProfileInfo& provisionInfo) const -{ - switch (type) { - case AppDistType::CROWDTESTING: - case AppDistType::APP_GALLERY: - case AppDistType::ENTERPRISE_MDM: - case AppDistType::OS_INTEGRATION: - case AppDistType::ENTERPRISE: - case AppDistType::ENTERPRISE_NORMAL: - return true; - case AppDistType::NONE_TYPE: - return false; - default: - return false; - } -} - -bool VerifyHap::ParseAndVerifyProfileIfNeed(const std::string& profile, - ProfileInfo& provisionInfo, bool isCallParseAndVerify) -{ - if (isCallParseAndVerify) { - return isCallParseAndVerify; - } - AppProvisionVerifyResult profileRet = ParseAndVerify(profile, provisionInfo); - if (profileRet != PROVISION_OK) { - SIGNATURE_TOOLS_LOGE("profile parse failed, error: %d", static_cast(profileRet)); - return false; - } - return true; -} - bool VerifyHap::GetDigestAndAlgorithm(Pkcs7Context& digest) { /* @@ -524,61 +379,14 @@ bool VerifyHap::GetDigestAndAlgorithm(Pkcs7Context& digest) return true; } -void VerifyHap::SetOrganization(ProfileInfo& provisionInfo) -{ - std::string& certInProfile = provisionInfo.bundleInfo.distributionCertificate; - if (provisionInfo.bundleInfo.distributionCertificate.empty()) { - SIGNATURE_TOOLS_LOGE("distributionCertificate is empty"); - return; - } - std::string organization; - if (!VerifyCertOpensslUtils::GetOrganizationFromPemCert(certInProfile, organization)) { - SIGNATURE_TOOLS_LOGE("Generate organization from pem certificate failed"); - return; - } - provisionInfo.organization = organization; -} - -int32_t VerifyHap::VerifyElfProfile(std::vector& profileData, HapVerifyResult& hapVerifyV1Result, - Options* options, Pkcs7Context& pkcs7Context) -{ - const unsigned char* pkcs7Block = reinterpret_cast(profileData.data()); - uint32_t pkcs7Len = static_cast(profileData.size()); - if (!VerifyHapOpensslUtils::ParsePkcs7Package(pkcs7Block, pkcs7Len, pkcs7Context)) { - SIGNATURE_TOOLS_LOGE("parse pkcs7 failed"); - return VERIFY_APP_PKCS7_FAIL; - } - if (!VerifyHapOpensslUtils::GetCertChains(pkcs7Context.p7, pkcs7Context)) { - SIGNATURE_TOOLS_LOGE("GetCertChains from pkcs7 failed"); - return VERIFY_APP_PKCS7_FAIL; - } - if (!VerifyHapOpensslUtils::VerifyPkcs7(pkcs7Context)) { - SIGNATURE_TOOLS_LOGE("verify signature failed"); - return VERIFY_APP_PKCS7_FAIL; - } - std::vector elfPublicKeys; - if (!VerifyHapOpensslUtils::GetPublickeys(pkcs7Context.certChain[0], elfPublicKeys)) { - SIGNATURE_TOOLS_LOGE("Get publicKeys failed"); - return GET_PUBLICKEY_FAIL; - } - hapVerifyV1Result.SetPublicKey(elfPublicKeys); - std::vector elfCertSignatures; - if (!VerifyHapOpensslUtils::GetSignatures(pkcs7Context.certChain[0], elfCertSignatures)) { - SIGNATURE_TOOLS_LOGE("Get sianatures failed"); - return GET_SIGNATURE_FAIL; - } - hapVerifyV1Result.SetSignature(elfCertSignatures); - return VERIFY_SUCCESS; -} - -int32_t VerifyHap::WriteVerifyOutput(Pkcs7Context& pkcs7Context, std::vector profile, Options* options) +int32_t VerifyHap::WriteVerifyOutput(Pkcs7Context& pkcs7Context, std::vector& profile, Options* options) { if (pkcs7Context.certChain.size() > 0) { bool flag = VerifyHap::HapOutPutCertChain(pkcs7Context.certChain[0], options->GetString(Options::OUT_CERT_CHAIN)); if (!flag) { SIGNATURE_TOOLS_LOGE("out put cert chain failed"); - return OUT_PUT_FILE_FAIL; + return IO_ERROR; } } if (pkcs7Context.p7 == nullptr) { @@ -586,16 +394,16 @@ int32_t VerifyHap::WriteVerifyOutput(Pkcs7Context& pkcs7Context, std::vectorGetString(Options::OUT_PROFILE)) < 0; if (writeFlag) { SIGNATURE_TOOLS_LOGE("p7b write to file falied!\n"); - return OUT_PUT_FILE_FAIL; + return IO_ERROR; } - return VERIFY_SUCCESS; + return RET_OK; } bool pkcs7flag = VerifyHap::HapOutPutPkcs7(pkcs7Context.p7, options->GetString(Options::OUT_PROFILE)); if (!pkcs7flag) { SIGNATURE_TOOLS_LOGE("out put p7b failed"); - return OUT_PUT_FILE_FAIL; + return IO_ERROR; } - return VERIFY_SUCCESS; + return RET_OK; } } // namespace SignatureTools } // namespace OHOS \ No newline at end of file diff --git a/hapsigntool_cpp/profile/include/pkcs7_data.h b/hapsigntool_cpp/profile/include/pkcs7_data.h index 2e5128e1..43eda51a 100644 --- a/hapsigntool_cpp/profile/include/pkcs7_data.h +++ b/hapsigntool_cpp/profile/include/pkcs7_data.h @@ -70,8 +70,8 @@ public: * @param attrs It is only used when you need to add an ownerID, and you don't need to process it by default * @return 0 :success <0 :error */ - int Sign(const std::string& content, std::shared_ptr signer, const std::string& sigAlg, std::string& ret, - std::vector attrs = std::vector()); + int Sign(const std::string& content, const std::shared_ptr& signer, const std::string& sigAlg, + std::string& ret, std::vector attrs = std::vector()); /* d2i deserialize */ int Parse(const std::string& p7bBytes); int Parse(const std::vector& p7bBytes); @@ -96,7 +96,7 @@ public: private: int Parse(const unsigned char** in, long len); - int InitPkcs7(const std::string& content, std::shared_ptr signer, + int InitPkcs7(const std::string& content, const std::shared_ptr& signer, const std::string& sigAlg, std::vector attrs); /* Verify Signature Value The certificate chain is not verified here */ int VerifySign(const std::string& content)const; diff --git a/hapsigntool_cpp/profile/include/profile_sign_tool.h b/hapsigntool_cpp/profile/include/profile_sign_tool.h index 8c5b870f..d5d0908b 100644 --- a/hapsigntool_cpp/profile/include/profile_sign_tool.h +++ b/hapsigntool_cpp/profile/include/profile_sign_tool.h @@ -53,7 +53,7 @@ public: * @return 0:success <0:error */ static int SignProfile(const std::string& content, - std::shared_ptr signer, const std::string& sigAlg, std::string& ret); + const std::shared_ptr& signer, const std::string& sigAlg, std::string& ret); }; } // namespace SignatureTools } // namespace OHOS diff --git a/hapsigntool_cpp/profile/include/profile_verify.h b/hapsigntool_cpp/profile/include/profile_verify.h index 52416967..b1e6b34f 100644 --- a/hapsigntool_cpp/profile/include/profile_verify.h +++ b/hapsigntool_cpp/profile/include/profile_verify.h @@ -50,7 +50,6 @@ DLL_EXPORT AppProvisionVerifyResult ParseProvision(const std::string& appProvisi * @return AppProvisionVerifyResult parse result. */ DLL_EXPORT AppProvisionVerifyResult ParseProfile(const std::string& appProvision, ProfileInfo& info); -DLL_EXPORT void SetRdDevice(bool isRdDevice); } // namespace SignatureTools } // namespace OHOS #endif // SIGNATRUETOOLS_PROFILE_VERIFY_H diff --git a/hapsigntool_cpp/profile/src/pkcs7_data.cpp b/hapsigntool_cpp/profile/src/pkcs7_data.cpp index 08eb9cfb..a069c227 100644 --- a/hapsigntool_cpp/profile/src/pkcs7_data.cpp +++ b/hapsigntool_cpp/profile/src/pkcs7_data.cpp @@ -112,7 +112,7 @@ PKCS7Data::~PKCS7Data() m_p7 = NULL; } -int PKCS7Data::Sign(const std::string& content, std::shared_ptr signer, +int PKCS7Data::Sign(const std::string& content, const std::shared_ptr& signer, const std::string& sigAlg, std::string& ret, std::vector attrs) { int result = RET_OK; @@ -188,13 +188,15 @@ int PKCS7Data::GetContent(std::string& originalRawData) const BIO_free_all(oriBio); return RET_OK; } + static void PKCS7AddCrls(PKCS7* p7, STACK_OF(X509_CRL)* crls) { for (int i = 0; i < sk_X509_CRL_num(crls); i++) { PKCS7_add_crl(p7, sk_X509_CRL_value(crls, i)); } } -int PKCS7Data::InitPkcs7(const std::string& content, std::shared_ptr signer, + +int PKCS7Data::InitPkcs7(const std::string& content, const std::shared_ptr& signer, const std::string& sigAlg, std::vector attrs) { STACK_OF(X509)* certs = NULL; diff --git a/hapsigntool_cpp/profile/src/profile_sign_tool.cpp b/hapsigntool_cpp/profile/src/profile_sign_tool.cpp index 04453833..95923687 100644 --- a/hapsigntool_cpp/profile/src/profile_sign_tool.cpp +++ b/hapsigntool_cpp/profile/src/profile_sign_tool.cpp @@ -65,7 +65,7 @@ int ProfileSignTool::GenerateP7b(LocalizationAdapter& adapter, const std::string * @param ret signed data * @return 0:success <0:error */ -int ProfileSignTool::SignProfile(const std::string& content, std::shared_ptr signer, +int ProfileSignTool::SignProfile(const std::string& content, const std::shared_ptr& signer, const std::string& sigAlg, std::string& ret) { PKCS7Data p7Data; diff --git a/hapsigntool_cpp/profile/src/profile_verify.cpp b/hapsigntool_cpp/profile/src/profile_verify.cpp index 02071679..4abe9bd6 100644 --- a/hapsigntool_cpp/profile/src/profile_verify.cpp +++ b/hapsigntool_cpp/profile/src/profile_verify.cpp @@ -65,7 +65,7 @@ const string KEY_PACKAGE_NAME = "package-name"; const string KEY_PACKAGE_CERT = "package-cert"; const string KEY_APP_IDENTIFIER = "app-identifier"; const string GENERIC_BUNDLE_NAME = ".*"; -const int32_t VERSION_CODE_TWO = 2; + inline void GetStringIfExist(const json& obj, const string& key, string& out) { if (obj.find(key.c_str()) != obj.end() && obj[key.c_str()].is_string()) { @@ -109,7 +109,7 @@ const std::map distTypeMap = { {VALUE_DIST_TYPE_OS_INTEGRATION, AppDistType::OS_INTEGRATION}, {VALUE_DIST_TYPE_CROWDTESTING, AppDistType::CROWDTESTING} }; -static bool g_isRdDevice = false; + void ParseType(const json& obj, ProfileInfo& out) { string type; @@ -256,53 +256,16 @@ static AppProvisionVerifyResult CheckProfileValidType(ProfileInfo& info) AppProvisionVerifyResult ParseProvision(const string& appProvision, ProfileInfo& info) { - AppProvisionVerifyResult result = PROVISION_OK; if (ParseProfile(appProvision, info) != PROVISION_OK) { return PROVISION_INVALID; } - result = ReturnIfIntIsNonPositive(info.versionCode, "Tag version code is empty."); - if (result != PROVISION_OK) { - return PROVISION_INVALID; - } - result = ReturnIfStringIsEmpty(info.versionName, "Tag version name is empty."); - if (result != PROVISION_OK) { - return PROVISION_INVALID; - } - result = ReturnIfStringIsEmpty(info.uuid, "Tag uuid is empty."); - if (result != PROVISION_OK) { - return PROVISION_INVALID; - } - result = ReturnIfStringIsEmpty(info.bundleInfo.developerId, "Tag developer-id is empty."); - if (result != PROVISION_OK) { - return PROVISION_INVALID; - } if (CheckProfileValidType(info) != PROVISION_OK) { return PROVISION_INVALID; } - - if (ReturnIfStringIsEmpty(info.bundleInfo.bundleName, "Tag bundle-name is empty.") != PROVISION_OK) { - return PROVISION_INVALID; - } - if (info.bundleInfo.bundleName == GENERIC_BUNDLE_NAME) { - SIGNATURE_TOOLS_LOGD("generic package name: %s, is used.", - GENERIC_BUNDLE_NAME.c_str()); - } - if (info.versionCode >= VERSION_CODE_TWO) { - if (ReturnIfStringIsEmpty(info.bundleInfo.apl, "Tag apl is empty.") != PROVISION_OK) { - return PROVISION_INVALID; - } - } - if (ReturnIfStringIsEmpty(info.bundleInfo.appFeature, "Tag app-feature is empty.") != PROVISION_OK) { - return PROVISION_INVALID; - } return PROVISION_OK; } -void SetRdDevice(bool isRdDevice) -{ - g_isRdDevice = isRdDevice; -} AppProvisionVerifyResult ParseAndVerify(const string& appProvision, ProfileInfo& info) { SIGNATURE_TOOLS_LOGD("Enter HarmonyAppProvision Verify"); diff --git a/hapsigntool_cpp/utils/include/hap_signer_block_utils.h b/hapsigntool_cpp/utils/include/hap_signer_block_utils.h index 7c64d216..131f12cc 100644 --- a/hapsigntool_cpp/utils/include/hap_signer_block_utils.h +++ b/hapsigntool_cpp/utils/include/hap_signer_block_utils.h @@ -21,7 +21,6 @@ #include "export_define.h" #include "byte_buffer.h" #include "random_access_file.h" -#include "hap_verify_result.h" #include "digest_parameter.h" #include "pkcs7_context.h" #include "signature_info.h" diff --git a/hapsigntool_cpp/utils/include/signature_info.h b/hapsigntool_cpp/utils/include/signature_info.h index d8dd10b5..1b1fd528 100644 --- a/hapsigntool_cpp/utils/include/signature_info.h +++ b/hapsigntool_cpp/utils/include/signature_info.h @@ -16,12 +16,14 @@ #define SIGNERTOOLS_SIGNATURE_INFO_H #include - #include "byte_buffer.h" -#include "hap_verify_result.h" namespace OHOS { namespace SignatureTools { +struct OptionalBlock { + int32_t optionalType = 0; + ByteBuffer optionalBlockValue; +}; struct SignatureInfo { ByteBuffer hapSignatureBlock; int64_t hapSigningBlockOffset; diff --git a/hapsigntool_cpp/utils/include/verify_cert_openssl_utils.h b/hapsigntool_cpp/utils/include/verify_cert_openssl_utils.h index 6581ed96..276b0b8c 100644 --- a/hapsigntool_cpp/utils/include/verify_cert_openssl_utils.h +++ b/hapsigntool_cpp/utils/include/verify_cert_openssl_utils.h @@ -32,22 +32,11 @@ public: VerifyCertOpensslUtils() = delete; DLL_EXPORT static bool VerifyCrl(CertChain& certsChain, STACK_OF(X509_CRL)* crls, Pkcs7Context& pkcs7Context); - DLL_EXPORT static bool CompareX509Cert(const X509* certA, const std::string& base64Cert); - DLL_EXPORT static void WriteX509CrlToStream(std::ofstream& crlFile, X509_CRL* crl); - DLL_EXPORT static bool GetPublickeyBase64FromPemCert(const std::string& certStr, std::string& publicKey); - DLL_EXPORT static bool GetFingerprintBase64FromPemCert(const std::string& certStr, - std::string& fingerprint); + DLL_EXPORT static bool X509NameCompare(const X509_NAME* a, const X509_NAME* b); - DLL_EXPORT static bool GetPublickeyBase64(const X509* cert, std::string& publicKey); - DLL_EXPORT static int32_t CalculateLenAfterBase64Encode(int32_t len); - DLL_EXPORT static bool GetOrganizationFromPemCert(const std::string& certStr, std::string& organization); DLL_EXPORT static X509* FindCertOfIssuer(X509* cert, CertSign& certVisitSign); DLL_EXPORT static std::string GetDnToString(X509_NAME* name); DLL_EXPORT static void GetTextFromX509Name(X509_NAME* name, int32_t nId, std::string& text); - DLL_EXPORT static X509* GetX509CertFromPemString(const std::string& pemString); - DLL_EXPORT static X509* GetX509CertFromBase64String(const std::string& base64String); - DLL_EXPORT static X509_CRL* GetX509CrlFromDerBuffer(const ByteBuffer& crlBuffer, - int32_t offset, int32_t len); DLL_EXPORT static X509_CRL* GetCrlBySignedCertIssuer(STACK_OF(X509_CRL)* crls, const X509* cert); DLL_EXPORT static bool CheckSignTimeInValidPeriod(const ASN1_TYPE* signTime, const ASN1_TIME* notBefore, const ASN1_TIME* notAfter); @@ -59,11 +48,8 @@ public: DLL_EXPORT static bool CheckAsn1TypeIsValid(const ASN1_TYPE* asn1Type); DLL_EXPORT static bool GetSubjectFromX509(const X509* cert, std::string& subject); DLL_EXPORT static bool GetIssuerFromX509(const X509* cert, std::string& issuer); - DLL_EXPORT static bool GetSerialNumberFromX509(const X509* cert, int64_t& certNumber); - DLL_EXPORT static bool GetIssuerFromX509Crl(const X509_CRL* crl, std::string& issuer); DLL_EXPORT static bool VerifyCertChainPeriodOfValidity(CertChain& certsChain, const ASN1_TYPE* signTime); - private: static const int32_t OPENSSL_READ_CRL_LEN_EACH_TIME; static const int32_t BASE64_ENCODE_LEN_OF_EACH_GROUP_DATA; diff --git a/hapsigntool_cpp/utils/include/verify_hap_openssl_utils.h b/hapsigntool_cpp/utils/include/verify_hap_openssl_utils.h index 2960dfb8..43ecccda 100644 --- a/hapsigntool_cpp/utils/include/verify_hap_openssl_utils.h +++ b/hapsigntool_cpp/utils/include/verify_hap_openssl_utils.h @@ -17,16 +17,16 @@ #include #include +#include "pkcs7_context.h" +#include "signature_info.h" #include "export_define.h" #include "byte_buffer.h" -#include "hap_verify_result.h" #include "openssl/evp.h" #include "openssl/ossl_typ.h" #include "openssl/pkcs7.h" #include "openssl/safestack.h" #include "digest_parameter.h" #include "verify_cert_openssl_utils.h" -#include "pkcs7_context.h" namespace OHOS { namespace SignatureTools { @@ -46,11 +46,10 @@ public: DLL_EXPORT static bool ParsePkcs7Package(const unsigned char packageData[], uint32_t packageLen, Pkcs7Context& pkcs7Context); DLL_EXPORT static bool GetCertChains(PKCS7* p7, Pkcs7Context& pkcs7Context); + + DLL_EXPORT static bool GetCrlStack(PKCS7* p7, STACK_OF(X509_CRL)* x509Crl); DLL_EXPORT static bool VerifyPkcs7(Pkcs7Context& pkcs7Context); - DLL_EXPORT static bool GetPublickeys(const CertChain& signCertChain, - std::vector& SignatureVec); - DLL_EXPORT static bool GetSignatures(const CertChain& signCertChain, - std::vector& SignatureVec); + static int32_t GetDigest(const ByteBuffer& chunk, const std::vector& optionalBlocks, const DigestParameter& digestParameter, unsigned char(&out)[EVP_MAX_MD_SIZE]); static bool DigestInit(const DigestParameter& digestParameter); @@ -59,15 +58,13 @@ public: static int32_t GetDigest(const DigestParameter& digestParameter, unsigned char(&out)[EVP_MAX_MD_SIZE]); static int32_t GetDigestAlgorithmOutputSizeBytes(int32_t nId); DLL_EXPORT static int32_t GetDigestAlgorithmId(int32_t signAlgorithm); + static std::string GetDigestAlgorithmString(int32_t signAlgorithm); static void GetOpensslErrorMessage(); private: DLL_EXPORT static bool VerifyPkcs7SignedData(Pkcs7Context& pkcs7Context); DLL_EXPORT static bool VerifySignInfo(STACK_OF(PKCS7_SIGNER_INFO)* signerInfoStack, BIO* p7Bio, int32_t signInfoNum, Pkcs7Context& pkcs7Context); - DLL_EXPORT static bool GetPublickeyFromCertificate(const X509* ptrX509, - std::vector& publicKeyVec); - DLL_EXPORT static bool GetDerCert(X509* ptrX509, std::vector& SignatureVec); static bool VerifyCertChain(CertChain& certsChain, PKCS7* p7, PKCS7_SIGNER_INFO* signInfo, Pkcs7Context& pkcs7Context, CertSign& certVisitSign); static bool GetContentInfo(const PKCS7* p7ContentInfo, ByteBuffer& content); diff --git a/hapsigntool_cpp/utils/src/hap_signer_block_utils.cpp b/hapsigntool_cpp/utils/src/hap_signer_block_utils.cpp index c5600efc..c150e4fe 100644 --- a/hapsigntool_cpp/utils/src/hap_signer_block_utils.cpp +++ b/hapsigntool_cpp/utils/src/hap_signer_block_utils.cpp @@ -18,6 +18,7 @@ #include #include +#include "signature_info.h" #include "algorithm" #include "openssl/evp.h" #include "securec.h" @@ -470,6 +471,9 @@ bool HapSignerBlockUtils::VerifyHapIntegrity( SIGNATURE_TOOLS_LOGE("digest of contents verify failed, alg %d", nId); return false; } + PrintMsg(std::string("Digest verify result: ") + "success" + ", DigestAlgorithm: " + + VerifyHapOpensslUtils::GetDigestAlgorithmString(digestInfo.digestAlgorithm)); + return true; } diff --git a/hapsigntool_cpp/utils/src/verify_cert_openssl_utils.cpp b/hapsigntool_cpp/utils/src/verify_cert_openssl_utils.cpp index 24a5bbc5..2a70499d 100644 --- a/hapsigntool_cpp/utils/src/verify_cert_openssl_utils.cpp +++ b/hapsigntool_cpp/utils/src/verify_cert_openssl_utils.cpp @@ -31,235 +31,6 @@ const int32_t VerifyCertOpensslUtils::OPENSSL_READ_CRL_MAX_TIME = 1048576; // 10 const int32_t VerifyCertOpensslUtils::OPENSSL_READ_CRL_LEN_EACH_TIME = 1024; const int32_t VerifyCertOpensslUtils::BASE64_ENCODE_LEN_OF_EACH_GROUP_DATA = 4; const int32_t VerifyCertOpensslUtils::BASE64_ENCODE_PACKET_LEN = 3; -constexpr int32_t BUFF_SIZE = 3; - -X509* VerifyCertOpensslUtils::GetX509CertFromPemString(const std::string& pemString) -{ - BIO* pemBio = BIO_new(BIO_s_mem()); - if (pemBio == nullptr) { - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - SIGNATURE_TOOLS_LOGE("BIO_new failed"); - return nullptr; - } - int32_t strLen = static_cast(pemString.size()); - if (BIO_write(pemBio, pemString.c_str(), strLen) != strLen) { - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - SIGNATURE_TOOLS_LOGE("BIO_write failed"); - BIO_free_all(pemBio); - return nullptr; - } - X509* cert = PEM_read_bio_X509(pemBio, nullptr, nullptr, nullptr); - BIO_free_all(pemBio); - return cert; -} - -X509* VerifyCertOpensslUtils::GetX509CertFromBase64String(const std::string& base64String) -{ - std::unique_ptr decodeBuffer = std::make_unique(base64String.size()); - const unsigned char* input = reinterpret_cast(base64String.c_str()); - int32_t len = EVP_DecodeBlock(decodeBuffer.get(), input, base64String.size()); - if (len <= 0) { - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - SIGNATURE_TOOLS_LOGE("base64Decode failed, len: %d", len); - return nullptr; - } - const unsigned char* derBits = decodeBuffer.get(); - X509* cert = d2i_X509(nullptr, &derBits, len); - return cert; -} - -bool VerifyCertOpensslUtils::GetPublickeyBase64FromPemCert(const std::string& certStr, - std::string& publicKey) -{ - X509* cert = GetX509CertFromPemString(certStr); - if (cert == nullptr) { - SIGNATURE_TOOLS_LOGE("GetX509CertFromPemString failed"); - return false; - } - if (!GetPublickeyBase64(cert, publicKey)) { - SIGNATURE_TOOLS_LOGE("X509_get_pubkey failed"); - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - X509_free(cert); - return false; - } - X509_free(cert); - return true; -} - -bool VerifyCertOpensslUtils::GetFingerprintBase64FromPemCert(const std::string& certStr, - std::string& fingerprint) -{ - SIGNATURE_TOOLS_LOGD("GetFingerprintBase64FromPemCert begin"); - X509* cert = GetX509CertFromPemString(certStr); - if (cert == nullptr) { - SIGNATURE_TOOLS_LOGE("GetX509CertFromPemString failed"); - return false; - } - int32_t certLen = i2d_X509(cert, nullptr); - if (certLen <= 0) { - SIGNATURE_TOOLS_LOGE("certLen %d, i2d_X509 failed", certLen); - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - X509_free(cert); - return false; - } - std::unique_ptr derCertificate = std::make_unique(certLen); - unsigned char* derCertificateBackup = derCertificate.get(); - if (i2d_X509(cert, &derCertificateBackup) <= 0) { - SIGNATURE_TOOLS_LOGE("i2d_X509 failed"); - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - X509_free(cert); - return false; - } - SHA256_CTX sha256; - SHA256_Init(&sha256); - SHA256_Update(&sha256, derCertificate.get(), certLen); - unsigned char hash[SHA256_DIGEST_LENGTH]; - SHA256_Final(hash, &sha256); - char buff[BUFF_SIZE] = { 0 }; - for (int32_t index = 0; index < SHA256_DIGEST_LENGTH; ++index) { - if (sprintf_s(buff, sizeof(buff), "%02X", hash[index]) < 0) { - fingerprint.clear(); - SIGNATURE_TOOLS_LOGE("transforms hash string to hexadecimal string failed"); - X509_free(cert); - return false; - } - fingerprint += buff; - } - X509_free(cert); - SIGNATURE_TOOLS_LOGD("GetFingerprintBase64FromPemCert end %s", fingerprint.c_str()); - return true; -} - -bool VerifyCertOpensslUtils::GetPublickeyBase64(const X509* cert, std::string& publicKey) -{ - EVP_PKEY* pkey = X509_get0_pubkey(cert); - if (pkey == nullptr) { - SIGNATURE_TOOLS_LOGE("X509_get0_pubkey failed"); - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - return false; - } - int32_t keyLen = i2d_PublicKey(pkey, nullptr); - if (keyLen <= 0) { - SIGNATURE_TOOLS_LOGE("keyLen %d, i2d_PublicKey failed", keyLen); - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - return false; - } - std::unique_ptr derPublicKey = std::make_unique(keyLen); - int32_t base64KeyLen = CalculateLenAfterBase64Encode(keyLen); - std::unique_ptr base64PublicKey = std::make_unique(base64KeyLen); - unsigned char* derCertificateBackup = derPublicKey.get(); - if (i2d_PublicKey(pkey, &derCertificateBackup) <= 0) { - SIGNATURE_TOOLS_LOGE("i2d_PublicKey failed"); - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - return false; - } - int32_t outLen = EVP_EncodeBlock(base64PublicKey.get(), derPublicKey.get(), keyLen); - publicKey = std::string(reinterpret_cast(base64PublicKey.get()), outLen); - return true; -} - -bool VerifyCertOpensslUtils::GetOrganizationFromPemCert(const std::string& certStr, - std::string& organization) -{ - SIGNATURE_TOOLS_LOGD("GetFingerprintBase64FromPemCert begin"); - X509* cert = GetX509CertFromPemString(certStr); - if (cert == nullptr) { - SIGNATURE_TOOLS_LOGE("GetX509CertFromPemString failed"); - return false; - } - X509_NAME* name = X509_get_subject_name(cert); - GetTextFromX509Name(name, NID_organizationName, organization); - X509_free(cert); - return true; -} -/* -* The length after Base64 encoding is 4/3 of the length before encoding, -* and openssl function will add '\0' to the encoded string. -* So len_after_encode = len_before_encode * 4/3 + 1 -*/ -int32_t VerifyCertOpensslUtils::CalculateLenAfterBase64Encode(int32_t len) -{ - return (len + BASE64_ENCODE_PACKET_LEN - 1) / BASE64_ENCODE_PACKET_LEN - * BASE64_ENCODE_LEN_OF_EACH_GROUP_DATA + 1; -} -bool VerifyCertOpensslUtils::CompareX509Cert(const X509* certA, const std::string& base64Cert) -{ - if (certA == nullptr) { - SIGNATURE_TOOLS_LOGE("certA is nullptr"); - return false; - } - X509* certB = GetX509CertFromPemString(base64Cert); - if (certB == nullptr) { - SIGNATURE_TOOLS_LOGE("generate certB failed"); - return false; - } - bool ret = (X509_cmp(certA, certB) == 0); - X509_free(certB); - return ret; -} - -X509_CRL* VerifyCertOpensslUtils::GetX509CrlFromDerBuffer(const ByteBuffer& crlBuffer, - int32_t offset, int32_t len) -{ - if (crlBuffer.GetBufferPtr() == nullptr) { - SIGNATURE_TOOLS_LOGE("invalid input, crlbuffer is null"); - return nullptr; - } - if ((len <= 0) || (offset < 0) || (crlBuffer.GetCapacity() - len < offset)) { - SIGNATURE_TOOLS_LOGE("invalid input, offset: %d, len: %d", offset, len); - return nullptr; - } - BIO* derBio = BIO_new(BIO_s_mem()); - if (derBio == nullptr) { - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - SIGNATURE_TOOLS_LOGE("BIO_new failed"); - return nullptr; - } - if (BIO_write(derBio, crlBuffer.GetBufferPtr() + offset, len) != len) { - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - SIGNATURE_TOOLS_LOGE("BIO_write failed"); - BIO_free_all(derBio); - return nullptr; - } - X509_CRL* crl = d2i_X509_CRL_bio(derBio, nullptr); - BIO_free_all(derBio); - return crl; -} - -void VerifyCertOpensslUtils::WriteX509CrlToStream(std::ofstream& crlFile, X509_CRL* crl) -{ - if (!crlFile.is_open()) { - SIGNATURE_TOOLS_LOGE("fill is not open"); - return; - } - BIO* derBio = BIO_new(BIO_s_mem()); - if (derBio == nullptr) { - SIGNATURE_TOOLS_LOGE("BIO_new failed"); - return; - } - if (crl == nullptr || i2d_X509_CRL_bio(derBio, crl) == 0) { - BIO_free_all(derBio); - SIGNATURE_TOOLS_LOGE("i2d_X509_CRL_bio failed"); - return; - } - int32_t totalLen = 0; - int64_t posStart = crlFile.tellp(); - crlFile.seekp(posStart + sizeof(totalLen)); - char buf[OPENSSL_READ_CRL_LEN_EACH_TIME]; - int32_t readLen = BIO_read(derBio, buf, sizeof(buf)); - int32_t readTime = 0; - while (readLen > 0 && (++readTime < OPENSSL_READ_CRL_MAX_TIME)) { - crlFile.write(buf, readLen); - totalLen += readLen; - readLen = BIO_read(derBio, buf, sizeof(buf)); - } - BIO_free_all(derBio); - int64_t posEnd = crlFile.tellp(); - crlFile.seekp(posStart); - /* write crl data len */ - crlFile.write(reinterpret_cast(&totalLen), sizeof(totalLen)); - crlFile.seekp(posEnd); -} void VerifyCertOpensslUtils::GenerateCertSignFromCertStack(STACK_OF(X509)* stackCerts, CertSign& certVisitSign) { @@ -491,33 +262,6 @@ bool VerifyCertOpensslUtils::GetIssuerFromX509(const X509* cert, std::string& is return true; } -bool VerifyCertOpensslUtils::GetSerialNumberFromX509(const X509* cert, int64_t& certNumber) -{ - if (cert == nullptr) { - SIGNATURE_TOOLS_LOGE("cert is nullptr"); - return false; - } - const ASN1_INTEGER* certSN = X509_get0_serialNumber(cert); - certNumber = ASN1_INTEGER_get(certSN); - SIGNATURE_TOOLS_LOGD("cert number = %" PRId64, certNumber); - return true; -} - -bool VerifyCertOpensslUtils::GetIssuerFromX509Crl(const X509_CRL* crl, std::string& issuer) -{ - if (crl == nullptr) { - SIGNATURE_TOOLS_LOGE("clr is nullptr"); - return false; - } - X509_NAME* name = X509_CRL_get_issuer(crl); - if (name == nullptr) { - SIGNATURE_TOOLS_LOGE("crl issuer nullptr"); - return false; - } - issuer = GetDnToString(name); - return true; -} - std::string VerifyCertOpensslUtils::GetDnToString(X509_NAME* x509Name) { if (x509Name == nullptr) { diff --git a/hapsigntool_cpp/utils/src/verify_hap_openssl_utils.cpp b/hapsigntool_cpp/utils/src/verify_hap_openssl_utils.cpp index dedc3c4b..3c99e2a1 100644 --- a/hapsigntool_cpp/utils/src/verify_hap_openssl_utils.cpp +++ b/hapsigntool_cpp/utils/src/verify_hap_openssl_utils.cpp @@ -24,6 +24,7 @@ #include "openssl/x509.h" #include "openssl/pem.h" #include "constant.h" +#include "signature_info.h" namespace OHOS { namespace SignatureTools { @@ -132,6 +133,15 @@ bool VerifyHapOpensslUtils::CheckPkcs7SignedDataIsValid(const PKCS7* p7) return true; } +bool VerifyHapOpensslUtils::GetCrlStack(PKCS7* p7, STACK_OF(X509_CRL)* x509Crl) +{ + if (!CheckPkcs7SignedDataIsValid(p7)) { + return false; + } + x509Crl = p7->d.sign->crl; + return true; +} + bool VerifyHapOpensslUtils::VerifyPkcs7(Pkcs7Context& pkcs7Context) { if (!CheckPkcs7SignedDataIsValid(pkcs7Context.p7)) { @@ -210,71 +220,6 @@ bool VerifyHapOpensslUtils::VerifySignInfo(STACK_OF(PKCS7_SIGNER_INFO)* signerIn return true; } -bool VerifyHapOpensslUtils::GetPublickeys(const CertChain& signCertChain, - std::vector& SignatureVec) -{ - for (uint32_t i = 0; i < signCertChain.size(); i++) { - if (!GetPublickeyFromCertificate(signCertChain[i], SignatureVec)) { - SIGNATURE_TOOLS_LOGE("%ust Get Publickey failed", i); - return false; - } - } - return !SignatureVec.empty(); -} - -bool VerifyHapOpensslUtils::GetSignatures(const CertChain& signCertChain, - std::vector& SignatureVec) -{ - for (uint32_t i = 0; i < signCertChain.size(); i++) { - if (!GetDerCert(signCertChain[i], SignatureVec)) { - SIGNATURE_TOOLS_LOGE("%ust GetDerCert failed", i); - return false; - } - } - return !SignatureVec.empty(); -} - -bool VerifyHapOpensslUtils::GetDerCert(X509* ptrX509, std::vector& SignatureVec) -{ - if (ptrX509 == nullptr) { - return false; - } - int32_t certLen = i2d_X509(ptrX509, nullptr); - if (certLen <= 0) { - SIGNATURE_TOOLS_LOGE("certLen %d, i2d_X509 failed", certLen); - GetOpensslErrorMessage(); - return false; - } - std::unique_ptr derCertificate = std::make_unique(certLen); - int32_t base64CertLen = VerifyCertOpensslUtils::CalculateLenAfterBase64Encode(certLen); - std::unique_ptr base64Certificate = std::make_unique(base64CertLen); - unsigned char* derCertificateBackup = derCertificate.get(); - if (i2d_X509(ptrX509, &derCertificateBackup) <= 0) { - SIGNATURE_TOOLS_LOGE("i2d_X509 failed"); - GetOpensslErrorMessage(); - return false; - } - /* base64 encode */ - int32_t len = EVP_EncodeBlock(base64Certificate.get(), derCertificate.get(), certLen); - SignatureVec.emplace_back(std::string(reinterpret_cast(base64Certificate.get()), len)); - return true; -} - -bool VerifyHapOpensslUtils::GetPublickeyFromCertificate(const X509* ptrX509, - std::vector& publicKeyVec) -{ - if (ptrX509 == nullptr) { - return false; - } - std::string publicKey; - if (!VerifyCertOpensslUtils::GetPublickeyBase64(ptrX509, publicKey)) { - SIGNATURE_TOOLS_LOGE("GetPublickeyBase64 Failed"); - return false; - } - publicKeyVec.emplace_back(publicKey); - return true; -} - bool VerifyHapOpensslUtils::GetContentInfo(const PKCS7* p7ContentInfo, ByteBuffer& content) { if ((p7ContentInfo == nullptr) || !PKCS7_type_is_data(p7ContentInfo)) { @@ -432,5 +377,20 @@ int32_t VerifyHapOpensslUtils::GetDigestAlgorithmId(int32_t signAlgorithm) return NID_undef; } } + +std::string VerifyHapOpensslUtils::GetDigestAlgorithmString(int32_t signAlgorithm) +{ + switch (signAlgorithm) { + case ALGORITHM_SHA256_WITH_ECDSA: + return "SHA-256"; + case ALGORITHM_SHA384_WITH_ECDSA: + return "SHA-384"; + case ALGORITHM_SHA512_WITH_ECDSA: + return "SHA-512"; + default: + SIGNATURE_TOOLS_LOGE("signAlgorithm: %d error", signAlgorithm); + return ""; + } +} } // namespace SignatureTools } // namespace OHOS \ No newline at end of file -- Gitee From 4efe3f110570e0b7975c182607ff4077b722deb2 Mon Sep 17 00:00:00 2001 From: zhanzeyi Date: Thu, 18 Jul 2024 17:28:22 +0800 Subject: [PATCH 4/8] fix code check Signed-off-by: zhanzeyi --- .../api/src/sign_tool_service_impl.cpp | 4 ++-- hapsigntool_cpp/cmd/src/params.cpp | 3 ++- hapsigntool_cpp/cmd/src/params_run_tool.cpp | 3 ++- .../hap/entity/src/hw_block_head.cpp | 3 ++- .../hap/provider/include/sign_provider.h | 2 +- hapsigntool_cpp/hap/sign/include/sign_elf.h | 3 ++- hapsigntool_cpp/hap/sign/src/sign_elf.cpp | 6 +++-- hapsigntool_cpp/hap/verify/src/verify_hap.cpp | 7 +++--- .../utils/include/signature_tools_log.h | 24 +++++++++++-------- 9 files changed, 33 insertions(+), 22 deletions(-) diff --git a/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp b/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp index a1d2030b..fe0dfa1f 100644 --- a/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp +++ b/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp @@ -375,8 +375,8 @@ bool SignToolServiceImpl::GenerateAppCert(Options* options) goto err; } x509CertificatePtr = CertTools::GenerateEndCert(csrPtr, issuerKeyPairPtr, *adapter, - APP_SIGNING_CAPABILITY, - sizeof(APP_SIGNING_CAPABILITY)); // get app x509 cert + APP_SIGNING_CAPABILITY, + sizeof(APP_SIGNING_CAPABILITY)); // get app x509 cert if (!x509CertificatePtr) { PrintErrorNumberMsg("CERTIFICATE_ERROR", CERTIFICATE_ERROR, "generate app cert failed"); goto err; diff --git a/hapsigntool_cpp/cmd/src/params.cpp b/hapsigntool_cpp/cmd/src/params.cpp index fdbc479a..7dfd4891 100644 --- a/hapsigntool_cpp/cmd/src/params.cpp +++ b/hapsigntool_cpp/cmd/src/params.cpp @@ -20,7 +20,8 @@ namespace SignatureTools { Params::Params() : options(new Options) { } -Params::~Params() { +Params::~Params() +{ if (options) { delete options; options = NULL; diff --git a/hapsigntool_cpp/cmd/src/params_run_tool.cpp b/hapsigntool_cpp/cmd/src/params_run_tool.cpp index 23da1233..86812b57 100644 --- a/hapsigntool_cpp/cmd/src/params_run_tool.cpp +++ b/hapsigntool_cpp/cmd/src/params_run_tool.cpp @@ -185,7 +185,8 @@ bool ParamsRunTool::RunCa(Options* params, SignToolServiceImpl& api) return false; } - if (!CmdUtil::UpdateParamForCheckOutFile(params, {Options::OUT_FILE, Options::KEY_STORE_FILE, Options::ISSUER_KEY_STORE_FILE})) { + if (!CmdUtil::UpdateParamForCheckOutFile(params, {Options::OUT_FILE, Options::KEY_STORE_FILE, + Options::ISSUER_KEY_STORE_FILE})) { return false; } diff --git a/hapsigntool_cpp/hap/entity/src/hw_block_head.cpp b/hapsigntool_cpp/hap/entity/src/hw_block_head.cpp index 6084bad3..753179f1 100644 --- a/hapsigntool_cpp/hap/entity/src/hw_block_head.cpp +++ b/hapsigntool_cpp/hap/entity/src/hw_block_head.cpp @@ -45,7 +45,8 @@ std::string HwBlockHead::GetBlockHead(const char type, const char tag, const sho return std::string(tmpVec.begin(), tmpVec.end()); } -std::vector HwBlockHead::GetBlockHeadLittleEndian(const char type, const char tag, const int length, const int offset) +std::vector HwBlockHead::GetBlockHeadLittleEndian(const char type, const char tag, + const int length, const int offset) { ByteBuffer bf = ByteBuffer(HwBlockHead::ELF_BLOCK_LEN); bf.PutByte(type); diff --git a/hapsigntool_cpp/hap/provider/include/sign_provider.h b/hapsigntool_cpp/hap/provider/include/sign_provider.h index 80bd3f33..7721a8eb 100644 --- a/hapsigntool_cpp/hap/provider/include/sign_provider.h +++ b/hapsigntool_cpp/hap/provider/include/sign_provider.h @@ -106,7 +106,7 @@ private: bool InitSigerConfig(SignerConfig& signerConfig, STACK_OF(X509)* publicCerts, Options* options); - bool DoAfterSign(bool isPathOverlap,const std::string& tmpOutputFile, const std::string& inputFilePath); + bool DoAfterSign(bool isPathOverlap, const std::string& tmpOutputFile, const std::string& inputFilePath); bool CreateSignerConfigs(STACK_OF(X509)* certificates, const std::optional& crl, Options* options, SignerConfig&); diff --git a/hapsigntool_cpp/hap/sign/include/sign_elf.h b/hapsigntool_cpp/hap/sign/include/sign_elf.h index a65ac8fd..b14f248a 100644 --- a/hapsigntool_cpp/hap/sign/include/sign_elf.h +++ b/hapsigntool_cpp/hap/sign/include/sign_elf.h @@ -54,7 +54,8 @@ private: static bool GenerateCodeSignByte(SignerConfig& signerConfig, const std::map &signParams, const std::string &inputFile, const int blockNum, const long binFileLen, SignBlockData** codeSign); - static bool WriteSignHeadDataToOutputFile(const std::string &inputFile, const std::string &outputFile, const int blockNum); + static bool WriteSignHeadDataToOutputFile(const std::string &inputFile, const std::string &outputFile, + const int blockNum); static bool IsLongOverflowInteger(const int64_t num); static bool IsLongOverflowShort(const int64_t num); }; diff --git a/hapsigntool_cpp/hap/sign/src/sign_elf.cpp b/hapsigntool_cpp/hap/sign/src/sign_elf.cpp index cc00f4eb..608fc3bd 100644 --- a/hapsigntool_cpp/hap/sign/src/sign_elf.cpp +++ b/hapsigntool_cpp/hap/sign/src/sign_elf.cpp @@ -143,7 +143,8 @@ bool SignElf::WriteBlockDataToFile(SignerConfig& signerConfig, return WriteSignedElf(inputFile, signDataList, outputFile); } -bool SignElf::WriteSignedElf(const std::string &inputFile, std::list& signBlockList, std::string &outputFile) +bool SignElf::WriteSignedElf(const std::string &inputFile, std::list& signBlockList, + std::string &outputFile) { std::ifstream fileInputStream(inputFile, std::ios::binary); std::ofstream fileOutputStream(outputFile, std::ios::binary); @@ -240,7 +241,8 @@ SignBlockData SignElf::GenerateProfileSignByte(std::string profileFile, std::str } bool SignElf::GenerateCodeSignByte(SignerConfig& signerConfig, const std::map &signParams, - const std::string &inputFile, const int blockNum, const long binFileLen, SignBlockData** codeSign) + const std::string &inputFile, const int blockNum, const long binFileLen, + SignBlockData** codeSign) { if (signParams.at(ParamConstants::PARAM_SIGN_CODE) == CODESIGN_OFF) { PrintErrorNumberMsg("SIGN_ERROR", SIGN_ERROR, "[SignElf] check pamams signCode = 0 error."); diff --git a/hapsigntool_cpp/hap/verify/src/verify_hap.cpp b/hapsigntool_cpp/hap/verify/src/verify_hap.cpp index 498b8c66..ef3859f8 100644 --- a/hapsigntool_cpp/hap/verify/src/verify_hap.cpp +++ b/hapsigntool_cpp/hap/verify/src/verify_hap.cpp @@ -78,18 +78,19 @@ bool VerifyHap::HapOutPutPkcs7(PKCS7* p7, const std::string& outPutPath) } bool VerifyHap::outputOptionalBlocks(const std::string& outputProfileFile, const std::string& outputProofFile, - const std::string& outputPropertyFile, const std::vector& optionBlocks) + const std::string& outputPropertyFile, + const std::vector& optionBlocks) { for (auto& optionBlock : optionBlocks) { if (optionBlock.optionalType == HapUtils::HAP_PROFILE_BLOCK_ID) { if (!writeOptionalBytesToFile(optionBlock, outputProfileFile)) { return false; } - } else if(optionBlock.optionalType == HapUtils::HAP_PROPERTY_BLOCK_ID) { + } else if (optionBlock.optionalType == HapUtils::HAP_PROPERTY_BLOCK_ID) { if (!writeOptionalBytesToFile(optionBlock, outputPropertyFile)) { return false; } - } else if(optionBlock.optionalType == HapUtils::HAP_PROOF_OF_ROTATION_BLOCK_ID) { + } else if (optionBlock.optionalType == HapUtils::HAP_PROOF_OF_ROTATION_BLOCK_ID) { if (!writeOptionalBytesToFile(optionBlock, outputPropertyFile)) { return false; } diff --git a/hapsigntool_cpp/utils/include/signature_tools_log.h b/hapsigntool_cpp/utils/include/signature_tools_log.h index 5ec9fc8f..e023a7df 100644 --- a/hapsigntool_cpp/utils/include/signature_tools_log.h +++ b/hapsigntool_cpp/utils/include/signature_tools_log.h @@ -27,6 +27,10 @@ namespace OHOS { namespace SignatureTools { +static const char POINT = '.'; +static const char PLACEHOLDER = '0'; +static const int PLACEHOLDERLEN = 3; +static const int SCALE = 1000; #define SIGNATURE_LOG(level, fmt, ...) \ printf("[%s] [%s] [%s] [%d] " fmt "\n", level, __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__) \ @@ -46,16 +50,16 @@ namespace SignatureTools { inline std::string GetSystemTime() { - std::string timeBuffer; - std::stringstream ss; - auto now = std::chrono::system_clock::now(); - std::time_t nowTime = std::chrono::system_clock::to_time_t(now); - std::tm* localTime = std::localtime(&nowTime); - auto ms = std::chrono::duration_cast(now.time_since_epoch()) % 1000; - ss << std::put_time(localTime, "%m-%d %H:%M:%S"); - ss << '.' << std::setfill('0') << std::setw(3) << ms.count(); - timeBuffer = ss.str(); - return timeBuffer; + std::string timeBuffer; + std::stringstream ss; + auto now = std::chrono::system_clock::now(); + std::time_t nowTime = std::chrono::system_clock::to_time_t(now); + std::tm* localTime = std::localtime(&nowTime); + auto ms = std::chrono::duration_cast(now.time_since_epoch()) % SCALE; + ss << std::put_time(localTime, "%m-%d %H:%M:%S"); + ss << POINT << std::setfill(PLACEHOLDER) << std::setw(PLACEHOLDERLEN) << ms.count(); + timeBuffer = ss.str(); + return timeBuffer; } /* -- Gitee From 249cf0840edaab0831059a331cbd9a0c3242108f Mon Sep 17 00:00:00 2001 From: zhanzeyi Date: Fri, 19 Jul 2024 09:36:06 +0800 Subject: [PATCH 5/8] fix pwd clear Signed-off-by: zhanzeyi --- .../hap/provider/src/remote_sign_provider.cpp | 13 +++++++++++-- hapsigntool_cpp/hap/provider/src/sign_provider.cpp | 10 ---------- hapsigntool_cpp/signer/src/signer_factory.cpp | 9 +++++---- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/hapsigntool_cpp/hap/provider/src/remote_sign_provider.cpp b/hapsigntool_cpp/hap/provider/src/remote_sign_provider.cpp index ec55e0f6..db812a49 100644 --- a/hapsigntool_cpp/hap/provider/src/remote_sign_provider.cpp +++ b/hapsigntool_cpp/hap/provider/src/remote_sign_provider.cpp @@ -32,6 +32,7 @@ bool RemoteSignProvider::CheckParams(Options* options) SIGNATURE_TOOLS_LOGE("SignProvider::Parameter check failed !"); return false; } + // The following code is for reference only. std::vector paramFileds; paramFileds.emplace_back(ParamConstants::PARAM_REMOTE_SERVER); paramFileds.emplace_back(ParamConstants::PARAM_REMOTE_USERNAME); @@ -39,8 +40,16 @@ bool RemoteSignProvider::CheckParams(Options* options) paramFileds.emplace_back(ParamConstants::PARAM_REMOTE_ONLINEAUTHMODE); paramFileds.emplace_back(ParamConstants::PARAM_REMOTE_SIGNERPLUGIN); std::unordered_set paramSet = Params::InitParamField(paramFileds); - if (!this->SetSignParams(options, paramSet)) { - return false; + for (auto it = options->begin(); it != options->end(); it++) { + if (paramSet.find(it->first) != paramSet.end()) { + size_t size = it->first.size(); + std::string str = it->first.substr(size - 3); + if (str == "Pwd") { + signParams.insert(std::make_pair(it->first, "")); + } else { + signParams.insert(std::make_pair(it->first, options->GetString(it->first))); + } + } } for (const auto& param : paramFileds) { if (signParams.find(param) == signParams.end()) { diff --git a/hapsigntool_cpp/hap/provider/src/sign_provider.cpp b/hapsigntool_cpp/hap/provider/src/sign_provider.cpp index 4ee1047a..14ea2eb5 100644 --- a/hapsigntool_cpp/hap/provider/src/sign_provider.cpp +++ b/hapsigntool_cpp/hap/provider/src/sign_provider.cpp @@ -570,19 +570,9 @@ bool SignProvider::SetSignParams(Options* options, std::unordered_setfirst.substr(size - 3); if (str != "Pwd") { this->signParams.insert(std::make_pair(it->first, options->GetString(it->first))); - continue; } - - char* passWord = options->GetChars(it->first); - if (passWord == nullptr) { - SIGNATURE_TOOLS_LOGE("Get password error"); - return false; - } - std::string strPwd = passWord; - this->signParams.insert(std::make_pair(it->first, strPwd)); } } - return true; } diff --git a/hapsigntool_cpp/signer/src/signer_factory.cpp b/hapsigntool_cpp/signer/src/signer_factory.cpp index b8e57e29..eeedb350 100644 --- a/hapsigntool_cpp/signer/src/signer_factory.cpp +++ b/hapsigntool_cpp/signer/src/signer_factory.cpp @@ -48,7 +48,7 @@ std::shared_ptr SignerFactory::LoadRemoteSigner(LocalizationAdapter& ada std::string signerPlugin = adapter.GetOptions()->GetString(ParamConstants::PARAM_REMOTE_SIGNERPLUGIN); std::string onlineAuthMode = adapter.GetOptions()->GetString(ParamConstants::PARAM_REMOTE_ONLINEAUTHMODE); std::string username = adapter.GetOptions()->GetString(ParamConstants::PARAM_REMOTE_USERNAME); - std::string userPwd = adapter.GetOptions()->GetChars(ParamConstants::PARAM_REMOTE_USERPWD); + char* userPwd = adapter.GetOptions()->GetChars(ParamConstants::PARAM_REMOTE_USERPWD); // open so RemoteSignProvider::handle = dlopen(signerPlugin.c_str(), RTLD_NOW | RTLD_GLOBAL); @@ -72,14 +72,15 @@ std::shared_ptr SignerFactory::LoadRemoteSigner(LocalizationAdapter& ada RemoteSignerParamType signServerType{signServer.c_str(), signServer.size()}; RemoteSignerParamType onlineAuthModeType{onlineAuthMode.c_str(), onlineAuthMode.size()}; RemoteSignerParamType usernameType{username.c_str(), username.size()}; - RemoteSignerParamType userPwdType{userPwd.c_str(), userPwd.size()}; + RemoteSignerParamType userPwdType{userPwd, strlen(userPwd)}; Signer* signer = remoteSignerCreator(keyAliasType, signServerType, onlineAuthModeType, usernameType, userPwdType); - userPwd.clear(); + for (size_t i = 0; i < strlen(userPwd); i++) { + userPwd[i] = 0; + } std::shared_ptr remoteSigner(signer); - return remoteSigner; } } // namespace SignatureTools -- Gitee From a544b170e27510a8ba570b77ae136e2d1f13c0a6 Mon Sep 17 00:00:00 2001 From: zhanzeyi Date: Fri, 19 Jul 2024 10:49:31 +0800 Subject: [PATCH 6/8] fix code check Signed-off-by: zhanzeyi --- hapsigntool_cpp/BUILD.gn | 1 - hapsigntool_cpp/api/src/cert_tools.cpp | 3 ++- hapsigntool_cpp/api/src/sign_tool_service_impl.cpp | 4 ++-- hapsigntool_cpp/codesigning/sign/src/code_signing.cpp | 3 ++- hapsigntool_cpp/hap/entity/include/hw_block_head.h | 3 ++- .../hap/entity/include/signature_algorithm_helper.h | 3 ++- hapsigntool_cpp/hap/provider/include/sign_provider.h | 3 ++- hapsigntool_cpp/hap/sign/src/sign_elf.cpp | 6 ++++-- 8 files changed, 16 insertions(+), 10 deletions(-) diff --git a/hapsigntool_cpp/BUILD.gn b/hapsigntool_cpp/BUILD.gn index b8be05be..5de4fa79 100644 --- a/hapsigntool_cpp/BUILD.gn +++ b/hapsigntool_cpp/BUILD.gn @@ -83,7 +83,6 @@ ohos_executable("hap-sign-tool") { include_dirs = signature_tools_main_include sources = signature_tools_main_src - defines = [ "SIGNATURE_LOG_DEBUG" ] deps = [ "//third_party/bzip2:libbz2", diff --git a/hapsigntool_cpp/api/src/cert_tools.cpp b/hapsigntool_cpp/api/src/cert_tools.cpp index 24c32321..3dea1613 100644 --- a/hapsigntool_cpp/api/src/cert_tools.cpp +++ b/hapsigntool_cpp/api/src/cert_tools.cpp @@ -870,7 +870,8 @@ bool CertTools::PrintCertChainToCmd(std::vector& certChain) uint64_t content = X509_FLAG_NO_EXTENSIONS | X509_FLAG_NO_ATTRIBUTES | X509_FLAG_NO_HEADER | X509_FLAG_NO_SIGDUMP; int num = 0; for (auto& cert : certChain) { - PrintMsg("+++++++++++++++++++++++++++++++++certificate #" + std::to_string(num) + "+++++++++++++++++++++++++++++++++++++"); + PrintMsg("+++++++++++++++++++++++++++++++++certificate #" + std::to_string(num) + + "+++++++++++++++++++++++++++++++++++++"); if (!X509_print_ex(outFd, cert, format, content)) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("print x509 cert to cmd failed"); diff --git a/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp b/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp index fe0dfa1f..a717ea09 100644 --- a/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp +++ b/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp @@ -387,8 +387,8 @@ bool SignToolServiceImpl::GenerateAppCert(Options* options) if (!GetAndOutPutCert(*adapter, x509CertificatePtr)) { goto err; } - - adapter->AppAndProfileAssetsRealse({issuerKeyPairPtr, keyPairPtr}, {csrPtr}, {x509CertificatePtr}); // realse heap memory + // realse heap memory + adapter->AppAndProfileAssetsRealse({issuerKeyPairPtr, keyPairPtr}, {csrPtr}, {x509CertificatePtr}); return true; err: diff --git a/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp b/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp index 6b50dd6f..82b0682d 100644 --- a/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp +++ b/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp @@ -128,7 +128,8 @@ int64_t CodeSigning::GetTimestamp() } bool CodeSigning::SignFile(std::istream& inputStream, int64_t fileSize, bool storeTree, - int64_t fsvTreeOffset, const std::string &ownerID, std::pair>& ret) + int64_t fsvTreeOffset, const std::string &ownerID, + std::pair>& ret) { std::unique_ptr fsVerityGenerator = std::make_unique(); diff --git a/hapsigntool_cpp/hap/entity/include/hw_block_head.h b/hapsigntool_cpp/hap/entity/include/hw_block_head.h index b82103b7..f78f1300 100644 --- a/hapsigntool_cpp/hap/entity/include/hw_block_head.h +++ b/hapsigntool_cpp/hap/entity/include/hw_block_head.h @@ -34,7 +34,8 @@ public: static int GetBlockLen(); static int GetElfBlockLen(); static std::string GetBlockHead(const char type, const char tag, const short length, const int offset); - static std::vector GetBlockHeadLittleEndian(const char type, const char tag, const int length, const int offset); + static std::vector GetBlockHeadLittleEndian(const char type, const char tag, + const int length, const int offset); }; } // namespace SignatureTools } // namespace OHOS diff --git a/hapsigntool_cpp/hap/entity/include/signature_algorithm_helper.h b/hapsigntool_cpp/hap/entity/include/signature_algorithm_helper.h index 359bf41a..3d3b3214 100644 --- a/hapsigntool_cpp/hap/entity/include/signature_algorithm_helper.h +++ b/hapsigntool_cpp/hap/entity/include/signature_algorithm_helper.h @@ -37,7 +37,8 @@ public: SignatureAlgorithmHelper(); SignatureAlgorithmHelper(const SignatureAlgorithmHelper& other); - SignatureAlgorithmHelper(const SignatureAlgorithmId &id_, const std::string &keyAlg_, const ContentDigestAlgorithm& digestAlg_, + SignatureAlgorithmHelper(const SignatureAlgorithmId &id_, const std::string &keyAlg_, + const ContentDigestAlgorithm& digestAlg_, const std::pair& sigParams_); SignatureAlgorithmHelper& operator=(const SignatureAlgorithmHelper& other); ~SignatureAlgorithmHelper(); diff --git a/hapsigntool_cpp/hap/provider/include/sign_provider.h b/hapsigntool_cpp/hap/provider/include/sign_provider.h index 7721a8eb..3cb1feeb 100644 --- a/hapsigntool_cpp/hap/provider/include/sign_provider.h +++ b/hapsigntool_cpp/hap/provider/include/sign_provider.h @@ -100,7 +100,8 @@ private: fileIOTuple PrepareIOStreams(const std::string& inputPath, const std::string& outputPath, bool& ret); bool InitZipOutput(std::shared_ptr outputHap, std::shared_ptr zip, - std::shared_ptr, std::shared_ptrtmpOutput, const std::string& path); + std::shared_ptr, std::shared_ptrtmpOutput, + const std::string& path); bool PrintErrorLog(const std::string& log, const int& errorCode, std::string path = ""); diff --git a/hapsigntool_cpp/hap/sign/src/sign_elf.cpp b/hapsigntool_cpp/hap/sign/src/sign_elf.cpp index 608fc3bd..0f175c9a 100644 --- a/hapsigntool_cpp/hap/sign/src/sign_elf.cpp +++ b/hapsigntool_cpp/hap/sign/src/sign_elf.cpp @@ -102,7 +102,8 @@ bool SignElf::AlignFileBy4kBytes(const std::string& inputFile, std::string& tmpF } bool SignElf::WriteBlockDataToFile(SignerConfig& signerConfig, - const std::string &inputFile, std::string& outputFile, const std::string& profileSigned, + const std::string &inputFile, std::string& outputFile, + const std::string& profileSigned, const std::map& signParams) { std::string proFile; @@ -266,7 +267,8 @@ bool SignElf::GenerateCodeSignByte(SignerConfig& signerConfig, const std::map Date: Fri, 19 Jul 2024 11:27:02 +0800 Subject: [PATCH 7/8] fix code check Signed-off-by: zhanzeyi --- hapsigntool_cpp/BUILD.gn | 1 - hapsigntool_cpp/cmd/src/cmd_util.cpp | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/hapsigntool_cpp/BUILD.gn b/hapsigntool_cpp/BUILD.gn index 5de4fa79..9711a538 100644 --- a/hapsigntool_cpp/BUILD.gn +++ b/hapsigntool_cpp/BUILD.gn @@ -83,7 +83,6 @@ ohos_executable("hap-sign-tool") { include_dirs = signature_tools_main_include sources = signature_tools_main_src - deps = [ "//third_party/bzip2:libbz2", "//third_party/openssl:libcrypto_shared", diff --git a/hapsigntool_cpp/cmd/src/cmd_util.cpp b/hapsigntool_cpp/cmd/src/cmd_util.cpp index 7766e7c1..ba1a461e 100644 --- a/hapsigntool_cpp/cmd/src/cmd_util.cpp +++ b/hapsigntool_cpp/cmd/src/cmd_util.cpp @@ -195,7 +195,7 @@ bool CmdUtil::UpdateParamForCheckOutFile(Options* options, const std::initialize //Purpose: To prevent the user output path from passing an empty string. eg " " std::string tmpOutFilePath = outFilePath; tmpOutFilePath.erase(std::remove_if(tmpOutFilePath.begin(), - tmpOutFilePath.end(), ::isspace), tmpOutFilePath.end()); + tmpOutFilePath.end(), ::isspace), tmpOutFilePath.end()); if (parentPath.empty() && !tmpOutFilePath.empty()) { parentPath = "./"; -- Gitee From 1b633410bceda75c6918510f5c2847d69187aedd Mon Sep 17 00:00:00 2001 From: zhanzeyi Date: Fri, 19 Jul 2024 11:43:11 +0800 Subject: [PATCH 8/8] fix Signed-off-by: zhanzeyi --- hapsigntool_cpp/cmd/src/cmd_util.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/hapsigntool_cpp/cmd/src/cmd_util.cpp b/hapsigntool_cpp/cmd/src/cmd_util.cpp index ba1a461e..627fb3a8 100644 --- a/hapsigntool_cpp/cmd/src/cmd_util.cpp +++ b/hapsigntool_cpp/cmd/src/cmd_util.cpp @@ -194,9 +194,8 @@ bool CmdUtil::UpdateParamForCheckOutFile(Options* options, const std::initialize //Purpose: To prevent the user output path from passing an empty string. eg " " std::string tmpOutFilePath = outFilePath; - tmpOutFilePath.erase(std::remove_if(tmpOutFilePath.begin(), - tmpOutFilePath.end(), ::isspace), tmpOutFilePath.end()); - + tmpOutFilePath.erase(std::remove_if(tmpOutFilePath.begin(), tmpOutFilePath.end(), ::isspace), + tmpOutFilePath.end()); if (parentPath.empty() && !tmpOutFilePath.empty()) { parentPath = "./"; } -- Gitee