From 8b771573b66f171929fe3d30b41c5a8a19b7095b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E6=97=8B=E9=A3=8Elc?= Date: Thu, 14 Nov 2024 20:07:08 +0800 Subject: [PATCH 1/7] =?UTF-8?q?C++=E7=AD=BE=E5=90=8D=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=E9=9D=99=E6=80=81=E5=91=8A=E8=AD=A6=E6=B8=85=E7=90=86=E5=92=8C?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=AE=89=E5=85=A8=E6=A3=80=E8=A7=86=20Signed?= =?UTF-8?q?-off-by:=20liuchang=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hapsigntool_cpp/api/include/cert_tools.h | 1 + hapsigntool_cpp/api/src/cert_tools.cpp | 42 +++++++++++++++---- .../api/src/sign_tool_service_impl.cpp | 6 ++- hapsigntool_cpp/cmd/src/params_trust_list.cpp | 15 ++++--- .../datastructure/src/code_sign_block.cpp | 2 +- .../src/code_sign_block_header.cpp | 11 +++-- .../src/fs_verity_info_segment.cpp | 3 +- .../datastructure/src/sign_info.cpp | 6 +-- .../fsverity/include/thread_pool.h | 2 +- .../fsverity/src/fs_verity_generator.cpp | 2 +- .../fsverity/src/merkle_tree_builder.cpp | 23 +++++----- .../codesigning/sign/include/code_signing.h | 2 +- .../codesigning/sign/src/code_signing.cpp | 10 +++-- .../sign/src/verify_code_signature.cpp | 18 ++++---- .../codesigning/utils/src/fs_digest_utils.cpp | 2 +- .../common/include/digest_common.h | 6 +-- hapsigntool_cpp/common/src/byte_buffer.cpp | 6 ++- .../common/src/localization_adapter.cpp | 5 +++ .../hap/provider/src/sign_provider.cpp | 2 +- hapsigntool_cpp/hap/sign/src/sign_bin.cpp | 1 - hapsigntool_cpp/hap/sign/src/sign_hap.cpp | 11 ++++- .../hap/utils/src/dynamic_lib_handle.cpp | 2 +- hapsigntool_cpp/hap/verify/src/verify_elf.cpp | 2 +- hapsigntool_cpp/hap/verify/src/verify_hap.cpp | 7 ++-- hapsigntool_cpp/profile/src/pkcs7_data.cpp | 4 +- .../profile/src/profile_sign_tool.cpp | 7 +--- .../profile/src/profile_verify.cpp | 2 +- hapsigntool_cpp/signer/src/signer_factory.cpp | 6 --- hapsigntool_cpp/utils/src/cert_dn_utils.cpp | 2 +- .../utils/src/hap_signer_block_utils.cpp | 3 +- .../utils/src/key_store_helper.cpp | 11 +++-- hapsigntool_cpp/utils/src/string_utils.cpp | 13 ++---- .../zip/src/random_access_file_input.cpp | 6 +-- .../zip/src/random_access_file_output.cpp | 2 +- hapsigntool_cpp/zip/src/zip_entry_data.cpp | 6 +-- hapsigntool_cpp/zip/src/zip_signer.cpp | 2 +- .../generateca012_fuzzer.cpp | 1 - .../processcmd022_fuzzer.cpp | 4 +- .../processcmd023_fuzzer.cpp | 5 +-- .../processcmd024_fuzzer.cpp | 26 ++++-------- .../profile001_fuzzer/profile001_fuzzer.cpp | 1 - 41 files changed, 154 insertions(+), 134 deletions(-) diff --git a/hapsigntool_cpp/api/include/cert_tools.h b/hapsigntool_cpp/api/include/cert_tools.h index c0b05b60..51c81d42 100644 --- a/hapsigntool_cpp/api/include/cert_tools.h +++ b/hapsigntool_cpp/api/include/cert_tools.h @@ -64,6 +64,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 UpdateConstraint(Options* options); static bool String2Bool(Options* options, const std::string& option); CertTools() = default; ~CertTools() = default; diff --git a/hapsigntool_cpp/api/src/cert_tools.cpp b/hapsigntool_cpp/api/src/cert_tools.cpp index 4a003f89..a89dc606 100644 --- a/hapsigntool_cpp/api/src/cert_tools.cpp +++ b/hapsigntool_cpp/api/src/cert_tools.cpp @@ -14,6 +14,7 @@ */ #include #include +#include #include #include #include @@ -72,10 +73,10 @@ bool CertTools::SaveCertTofile(const std::string& filename, X509* cert) return true; } -static bool UpdateConstraint(Options* options) +bool CertTools::UpdateConstraint(Options* options) { if (options->count(Options::BASIC_CONSTRAINTS)) { - if (!CertTools::String2Bool(options, Options::BASIC_CONSTRAINTS)) { + if (!String2Bool(options, Options::BASIC_CONSTRAINTS)) { return false; } } else { @@ -83,7 +84,7 @@ static bool UpdateConstraint(Options* options) } if (options->count(Options::BASIC_CONSTRAINTS_CRITICAL)) { - if (!CertTools::String2Bool(options, Options::BASIC_CONSTRAINTS_CRITICAL)) { + if (!String2Bool(options, Options::BASIC_CONSTRAINTS_CRITICAL)) { return false; } } else { @@ -91,7 +92,7 @@ static bool UpdateConstraint(Options* options) } if (options->count(Options::BASIC_CONSTRAINTS_CA)) { - if (!CertTools::String2Bool(options, Options::BASIC_CONSTRAINTS_CA)) { + if (!String2Bool(options, Options::BASIC_CONSTRAINTS_CA)) { return false; } } else { @@ -223,6 +224,10 @@ X509* CertTools::SignCsrGenerateCert(X509_REQ* rootcsr, X509_REQ* subcsr, { bool result = false; X509* cert = X509_new(); + if (cert == NULL) { + SIGNATURE_TOOLS_LOGE("create X509 cert failed"); + return nullptr; + } int validity = options->GetInt(Options::VALIDITY); result = (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || !SetCertSerialNum(cert)); @@ -273,6 +278,10 @@ X509* CertTools::GenerateRootCertificate(EVP_PKEY* keyPair, X509_REQ* certReq, O { bool result = false; X509* cert = X509_new(); + if (cert == NULL) { + SIGNATURE_TOOLS_LOGE("create X509 cert failed"); + return nullptr; + } int validity = options->GetInt(Options::VALIDITY); std::string signAlg = options->GetString(Options::SIGN_ALG); result = (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || @@ -353,9 +362,8 @@ bool CertTools::SetKeyUsage(X509* cert, Options* options) bool keyUsageCritical = options->GetBool(Options::KEY_USAGE_CRITICAL); int crit = keyUsageCritical > 0 ? 1 : 0; std::vector vecs = StringUtils::SplitString(keyUsage.c_str(), ','); - for (auto &vec : vecs) { - key |= externDic[vec]; - } + key = std::accumulate(vecs.begin(), vecs.end(), key, [&](long key, const std::string& vec) { + return key | externDic[vec]; }); if (keyUsageInt == NULL || !ASN1_INTEGER_set(keyUsageInt, key)) { SIGNATURE_TOOLS_LOGE("failed to set asn1_integer"); ASN1_INTEGER_free(keyUsageInt); @@ -447,6 +455,9 @@ X509* CertTools::GenerateCert(EVP_PKEY* keyPair, X509_REQ* certReq, Options* opt } X509* cert = X509_new(); + if (cert == NULL) { + goto err; + } result = (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || !SetCertSerialNum(cert) || !SetKeyIdentifierExt(cert)); @@ -549,6 +560,13 @@ X509* CertTools::ReadfileToX509(const std::string& filename) } X509* cert = X509_new(); + if (cert == NULL) { + VerifyHapOpensslUtils::GetOpensslErrorMessage(); + SIGNATURE_TOOLS_LOGE("create X509 cert failed"); + X509_free(cert); + BIO_free(certBio); + return nullptr; + } if (!PEM_read_bio_X509(certBio, &cert, NULL, NULL)) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("PEM_read_bio_X509 failed"); @@ -765,7 +783,7 @@ bool CertTools::SetAuthorizeKeyIdentifierExt(X509* cert) bool CertTools::SetSignCapacityExt(X509* cert, const char signCapacity[], int capacityLen) { ASN1_OCTET_STRING* certSignCapacityData = ASN1_OCTET_STRING_new(); - if (!ASN1_OCTET_STRING_set(certSignCapacityData, (const unsigned char*)signCapacity, capacityLen)) { + if (!ASN1_OCTET_STRING_set(certSignCapacityData, reinterpret_cast(signCapacity), capacityLen)) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("failed to set pubkey digst into ASN1 object"); ASN1_OCTET_STRING_free(certSignCapacityData); @@ -836,6 +854,14 @@ X509* CertTools::GenerateEndCert(X509_REQ* csr, EVP_PKEY* issuerKeyPair, int validity = adapter.options->GetInt(adapter.options->VALIDITY); std::string signAlg = adapter.options->GetString(adapter.options->SIGN_ALG); + if(cert == NULL) { + SIGNATURE_TOOLS_LOGE("create X509 cert failed"); + goto err; + } + if(issuerReq == NULL) { + SIGNATURE_TOOLS_LOGE("create X509 req failed"); + goto err; + } result = (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || !SetCertSerialNum(cert)); if (result) { goto err; diff --git a/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp b/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp index e38dff4c..dec920de 100644 --- a/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp +++ b/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp @@ -71,7 +71,6 @@ 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* certPtr = nullptr; X509_REQ* csr = nullptr; bool result = false; @@ -231,6 +230,7 @@ bool SignToolServiceImpl::GenerateCert(Options* options) err: if (result == false) SIGNATURE_TOOLS_LOGE("generate cert failed!"); + adapter->ResetPwd(); X509_free(cert); X509_REQ_free(csr); EVP_PKEY_free(rootKeyPair); @@ -393,6 +393,7 @@ bool SignToolServiceImpl::GenerateAppCert(Options* options) err: adapter->AppAndProfileAssetsRealse({issuerKeyPairPtr, keyPairPtr}, {csrPtr}, {x509CertificatePtr}); + adapter->ResetPwd(); return false; } @@ -437,6 +438,7 @@ bool SignToolServiceImpl::GenerateProfileCert(Options* options) err: adapter->AppAndProfileAssetsRealse({issuerKeyPair, keyPair}, {csr}, {x509Certificate}); + adapter->ResetPwd(); return false; } @@ -446,8 +448,8 @@ bool SignToolServiceImpl::GetAndOutPutCert(LocalizationAdapter& adapter, X509* c bool successflag = false; X509* subCaCert = nullptr; X509* rootCaCert = nullptr; - std::vector certificates; if (adapter.IsOutFormChain()) { + std::vector certificates; certificates.emplace_back(cert); // add entity cert successflag = (!(subCaCert = adapter.GetSubCaCertFile()) || !(rootCaCert = adapter.GetCaCertFile())); diff --git a/hapsigntool_cpp/cmd/src/params_trust_list.cpp b/hapsigntool_cpp/cmd/src/params_trust_list.cpp index 1a3c3785..1e830b08 100644 --- a/hapsigntool_cpp/cmd/src/params_trust_list.cpp +++ b/hapsigntool_cpp/cmd/src/params_trust_list.cpp @@ -13,6 +13,8 @@ * limitations under the License. */ +#include + #include "params_trust_list.h" #include "constant.h" #include "params.h" @@ -68,14 +70,11 @@ void ParamsTrustList::ReadHelpParam(std::istringstream& fd) if (params.empty()) { continue; } - for (const auto& it : commands) { - if (it == params) { - cmdStandBy = params; - isExists = true; - break; - } - } - if (!isExists) { + isExists = std::any_of(commands.begin(), commands.end(), + [params](const std::string& cmd) {return cmd == params; }); + if (isExists) { + cmdStandBy = params; + } else { PutTrustMap(cmdStandBy, params); } } diff --git a/hapsigntool_cpp/codesigning/datastructure/src/code_sign_block.cpp b/hapsigntool_cpp/codesigning/datastructure/src/code_sign_block.cpp index fd2ed72e..9604134f 100644 --- a/hapsigntool_cpp/codesigning/datastructure/src/code_sign_block.cpp +++ b/hapsigntool_cpp/codesigning/datastructure/src/code_sign_block.cpp @@ -186,7 +186,7 @@ void CodeSignBlock::GenerateCodeSignBlockByte(int64_t fsvTreeOffset, std::vector + nativeLibInfoSegment.Size(); Extension* ext = hapInfoSegment.GetSignInfo().GetExtensionByType(MerkleTreeExtension::MERKLE_TREE_INLINED); if (ext != nullptr) { - MerkleTreeExtension* merkleTreeExtension = (MerkleTreeExtension*)(ext); + MerkleTreeExtension* merkleTreeExtension = static_cast(ext); merkleTreeExtension->SetMerkleTreeOffset(fsvTreeOffset); } codeSignBlockHeader.SetBlockSize(csbSize); 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 ce55ec5d..d7809d40 100644 --- a/hapsigntool_cpp/codesigning/datastructure/src/code_sign_block_header.cpp +++ b/hapsigntool_cpp/codesigning/datastructure/src/code_sign_block_header.cpp @@ -71,7 +71,7 @@ void CodeSignBlockHeader::ToByteArray(std::vector& ret) bf.PutInt32(blockSize); bf.PutInt32(segmentNum); bf.PutInt32(flags); - bf.PutData((const char*)reserved.data(), reserved.size()); + bf.PutData(reinterpret_cast(reserved.data()), reserved.size()); ret = std::vector(bf.GetBufferPtr(), bf.GetBufferPtr() + bf.GetPosition()); } @@ -83,7 +83,7 @@ CodeSignBlockHeader* CodeSignBlockHeader::FromByteArray(const std::vector(bytes.data()), bytes.size()); bf.Flip(); int64_t inMagic; bool flag = bf.GetInt64(inMagic); @@ -117,7 +117,12 @@ CodeSignBlockHeader* CodeSignBlockHeader::FromByteArray(const std::vector inReserved(RESERVED_BYTE_ARRAY_LENGTH); bf.GetByte(inReserved.data(), RESERVED_BYTE_ARRAY_LENGTH); - CodeSignBlockHeader::Builder* tempVar = new CodeSignBlockHeader::Builder(); + CodeSignBlockHeader::Builder* tempVar = new(std::nothrow) CodeSignBlockHeader::Builder(); + if(tempVar == nullptr) { + PrintErrorNumberMsg("VERIFY_ERROR", VERIFY_ERROR, + "create CodeSignBlockHeader::Builder failed"); + return nullptr; + } CodeSignBlockHeader* codeSignBlockHeader = tempVar->SetMagic(inMagic)->SetVersion(inVersion)-> SetBlockSize(inBlockSize)->SetSegmentNum(inSegmentNum)-> SetFlags(inFlags)->SetReserved(inReserved)->Build(); 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 cb29cc69..138ad11d 100644 --- a/hapsigntool_cpp/codesigning/datastructure/src/fs_verity_info_segment.cpp +++ b/hapsigntool_cpp/codesigning/datastructure/src/fs_verity_info_segment.cpp @@ -71,7 +71,7 @@ FsVerityInfoSegment FsVerityInfoSegment::FromByteArray(const std::vector } ByteBuffer bf(bytes.size()); - bf.PutData((const char*)bytes.data(), bytes.size()); + bf.PutData(reinterpret_cast(bytes.data()), bytes.size()); bf.SetPosition(0); int inMagic; bf.GetInt32(inMagic); @@ -105,7 +105,6 @@ FsVerityInfoSegment FsVerityInfoSegment::FromByteArray(const std::vector return FsVerityInfoSegment(); } - std::vector inReservedBytes(RESERVED_BYTE_ARRAY_LENGTH); char reverseArr[RESERVED_BYTE_ARRAY_LENGTH]; bf.GetData(reverseArr, RESERVED_BYTE_ARRAY_LENGTH); std::vector reverseData(reverseArr, reverseArr + RESERVED_BYTE_ARRAY_LENGTH); diff --git a/hapsigntool_cpp/codesigning/datastructure/src/sign_info.cpp b/hapsigntool_cpp/codesigning/datastructure/src/sign_info.cpp index ae675af1..7fa5a96f 100644 --- a/hapsigntool_cpp/codesigning/datastructure/src/sign_info.cpp +++ b/hapsigntool_cpp/codesigning/datastructure/src/sign_info.cpp @@ -89,7 +89,7 @@ SignInfo::SignInfo(const SignInfo& other) this->signature = other.signature; this->zeroPadding = other.zeroPadding; for (MerkleTreeExtension* ext : other.extensionList) { - MerkleTreeExtension* extTmp = new MerkleTreeExtension(*(MerkleTreeExtension*)(ext)); + MerkleTreeExtension* extTmp = new MerkleTreeExtension(*ext); this->extensionList.push_back(extTmp); } } @@ -108,8 +108,8 @@ SignInfo& SignInfo::operator=(const SignInfo& other) this->extensionOffset = other.extensionOffset; this->signature = other.signature; this->zeroPadding = other.zeroPadding; - for (Extension* ext : other.extensionList) { - MerkleTreeExtension* extTmp = new MerkleTreeExtension(*(MerkleTreeExtension*)(ext)); + for (MerkleTreeExtension* ext : other.extensionList) { + MerkleTreeExtension* extTmp = new MerkleTreeExtension(*ext); this->extensionList.push_back(extTmp); } return *this; diff --git a/hapsigntool_cpp/codesigning/fsverity/include/thread_pool.h b/hapsigntool_cpp/codesigning/fsverity/include/thread_pool.h index 67f13054..5de49d85 100644 --- a/hapsigntool_cpp/codesigning/fsverity/include/thread_pool.h +++ b/hapsigntool_cpp/codesigning/fsverity/include/thread_pool.h @@ -66,7 +66,7 @@ public: { std::unique_lock lock(m_queueMutex); while (m_stop == false && m_tasks.size() >= TASK_NUM) { - m_conditionMax.wait(lock); + m_conditionMax.wait(lock, [this] { return m_stop || m_tasks.size() < TASK_NUM; }); } m_tasks.emplace([task] () { (*task)(); }); m_condition.notify_one(); diff --git a/hapsigntool_cpp/codesigning/fsverity/src/fs_verity_generator.cpp b/hapsigntool_cpp/codesigning/fsverity/src/fs_verity_generator.cpp index a2f24027..0a205d24 100644 --- a/hapsigntool_cpp/codesigning/fsverity/src/fs_verity_generator.cpp +++ b/hapsigntool_cpp/codesigning/fsverity/src/fs_verity_generator.cpp @@ -30,9 +30,9 @@ MerkleTree* FsVerityGenerator::GenerateMerkleTree(std::istream& inputStream, lon bool FsVerityGenerator::GenerateFsVerityDigest(std::istream& inputStream, long size, long fsvTreeOffset) { - std::vector emptyVector; MerkleTree* merkleTree = nullptr; if (size == 0) { + std::vector emptyVector; merkleTree = new MerkleTree(emptyVector, emptyVector, FS_SHA256); } else { merkleTree = GenerateMerkleTree(inputStream, size, FS_SHA256); diff --git a/hapsigntool_cpp/codesigning/fsverity/src/merkle_tree_builder.cpp b/hapsigntool_cpp/codesigning/fsverity/src/merkle_tree_builder.cpp index 2e04776f..6705c429 100644 --- a/hapsigntool_cpp/codesigning/fsverity/src/merkle_tree_builder.cpp +++ b/hapsigntool_cpp/codesigning/fsverity/src/merkle_tree_builder.cpp @@ -247,25 +247,25 @@ MerkleTree* MerkleTreeBuilder::GetMerkleTree(ByteBuffer* dataBuffer, long inputD std::vector tree; if (inputDataSize < FSVERITY_HASH_PAGE_SIZE) { ByteBuffer* fsVerityHashPageBuffer = Slice(dataBuffer, 0, digestSize); - rootHash = std::vector(digestSize); - fsVerityHashPageBuffer->GetByte((int8_t*)rootHash.data(), digestSize); if (fsVerityHashPageBuffer != nullptr) { + rootHash = std::vector(digestSize); + fsVerityHashPageBuffer->GetByte(rootHash.data(), digestSize); delete fsVerityHashPageBuffer; fsVerityHashPageBuffer = nullptr; } } else { tree = std::vector(dataBuffer->GetBufferPtr(), dataBuffer->GetBufferPtr() + dataBuffer->GetCapacity()); ByteBuffer* fsVerityHashPageBuffer = Slice(dataBuffer, 0, FSVERITY_HASH_PAGE_SIZE); - std::vector fsVerityHashPage(FSVERITY_HASH_PAGE_SIZE); - fsVerityHashPageBuffer->GetData(0, fsVerityHashPage.data(), FSVERITY_HASH_PAGE_SIZE); - DigestUtils digestUtils(HASH_SHA256); - std::string fsVerityHashPageStr(fsVerityHashPage.begin(), fsVerityHashPage.end()); - digestUtils.AddData(fsVerityHashPageStr); - std::string result = digestUtils.Result(DigestUtils::Type::BINARY); - for (int i = 0; i < static_cast(result.size()); i++) { - rootHash.push_back(result[i]); - } if (fsVerityHashPageBuffer != nullptr) { + std::vector fsVerityHashPage(FSVERITY_HASH_PAGE_SIZE); + fsVerityHashPageBuffer->GetData(0, fsVerityHashPage.data(), FSVERITY_HASH_PAGE_SIZE); + DigestUtils digestUtils(HASH_SHA256); + std::string fsVerityHashPageStr(fsVerityHashPage.begin(), fsVerityHashPage.end()); + digestUtils.AddData(fsVerityHashPageStr); + std::string result = digestUtils.Result(DigestUtils::Type::BINARY); + for (int i = 0; i < static_cast(result.size()); i++) { + rootHash.push_back(result[i]); + } delete fsVerityHashPageBuffer; fsVerityHashPageBuffer = nullptr; } @@ -279,7 +279,6 @@ void MerkleTreeBuilder::DataRoundupChunkSize(ByteBuffer* data, long originalData long fullChunkSize = GetFullChunkSize(originalDataSize, CHUNK_SIZE, digestSize); int diffValue = (int)(fullChunkSize % CHUNK_SIZE); if (diffValue > 0) { - std::vector padding(CHUNK_SIZE - diffValue); data->SetPosition(data->GetPosition() + (CHUNK_SIZE - diffValue)); } } diff --git a/hapsigntool_cpp/codesigning/sign/include/code_signing.h b/hapsigntool_cpp/codesigning/sign/include/code_signing.h index 9cf04dd8..ae008d0a 100644 --- a/hapsigntool_cpp/codesigning/sign/include/code_signing.h +++ b/hapsigntool_cpp/codesigning/sign/include/code_signing.h @@ -58,7 +58,7 @@ public: public: static bool IsNativeFile(const std::string& input); - uint32_t ComputeDataSize(ZipSigner& zip); + int64_t ComputeDataSize(ZipSigner& zip); int64_t GetTimestamp(); bool SignNativeLibs(const std::string &input, std::string &ownerID); void UpdateCodeSignBlock(); diff --git a/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp b/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp index 467aacf2..b30f8593 100644 --- a/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp +++ b/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp @@ -54,10 +54,11 @@ bool CodeSigning::GetCodeSignBlock(const std::string &input, int64_t offset, SIGNATURE_TOOLS_LOGE("only support format is [hap, hqf, hsp, app]"); return false; } - uint32_t dataSize = ComputeDataSize(zip); - if (dataSize < 0) { + int64_t dataSizeInt64 = ComputeDataSize(zip); + if (dataSizeInt64 < 0) { return false; } + uint32_t dataSize = static_cast(dataSizeInt64); m_timestamp = GetTimestamp(); int64_t fsvTreeOffset = m_codeSignBlock.ComputeMerkleTreeOffset(offset); std::unique_ptr fsVerityInfoSegment = @@ -96,7 +97,7 @@ bool CodeSigning::GetCodeSignBlock(const std::string &input, int64_t offset, return true; } -uint32_t CodeSigning::ComputeDataSize(ZipSigner& zip) +int64_t CodeSigning::ComputeDataSize(ZipSigner& zip) { uint32_t dataSize = 0L; for (const auto& entry : zip.GetZipEntries()) { @@ -120,7 +121,8 @@ uint32_t CodeSigning::ComputeDataSize(ZipSigner& zip) "Invalid dataSize, the dataSize must be an integer multiple of 4096"); return -1; } - return dataSize; + int64_t dataSizeInt64 = static_cast(dataSize); + return dataSizeInt64; } int64_t CodeSigning::GetTimestamp() diff --git a/hapsigntool_cpp/codesigning/sign/src/verify_code_signature.cpp b/hapsigntool_cpp/codesigning/sign/src/verify_code_signature.cpp index 9f76a8f5..fd38f0f3 100644 --- a/hapsigntool_cpp/codesigning/sign/src/verify_code_signature.cpp +++ b/hapsigntool_cpp/codesigning/sign/src/verify_code_signature.cpp @@ -131,7 +131,7 @@ bool VerifyCodeSignature::VerifyCodeSign(std::string file, std::pair(ext); } else { std::shared_ptr merkleTreeExt(mte); } @@ -292,16 +292,14 @@ bool VerifyCodeSignature::ParseMerkleTree(CodeSignBlock& csb, int32_t readOffset SIGNATURE_TOOLS_LOGE("Missing merkleTreeExtension in verifycation"); return false; } - MerkleTreeExtension* mte = (MerkleTreeExtension*)(extension); - if (mte) { - bool merkleTreeFlag = computedTreeOffset != mte->GetMerkleTreeOffset() || - merkleTreeBytes.size() != mte->GetMerkleTreeSize(); - if (merkleTreeFlag) { - PrintErrorNumberMsg("VERIFY_ERROR", VERIFY_ERROR, "Invalid merkle tree offset or tree size"); - return false; - } - csb.AddOneMerkleTree(CodeSigning::HAP_SIGNATURE_ENTRY_NAME, *(std::vector *) &merkleTreeBytes); + MerkleTreeExtension* mte = static_cast(extension); + bool merkleTreeFlag = computedTreeOffset != mte->GetMerkleTreeOffset() || + merkleTreeBytes.size() != mte->GetMerkleTreeSize(); + if (merkleTreeFlag) { + PrintErrorNumberMsg("VERIFY_ERROR", VERIFY_ERROR, "Invalid merkle tree offset or tree size"); + return false; } + csb.AddOneMerkleTree(CodeSigning::HAP_SIGNATURE_ENTRY_NAME, *(std::vector *) &merkleTreeBytes); return true; } diff --git a/hapsigntool_cpp/codesigning/utils/src/fs_digest_utils.cpp b/hapsigntool_cpp/codesigning/utils/src/fs_digest_utils.cpp index 73631cba..903a14ae 100644 --- a/hapsigntool_cpp/codesigning/utils/src/fs_digest_utils.cpp +++ b/hapsigntool_cpp/codesigning/utils/src/fs_digest_utils.cpp @@ -43,8 +43,8 @@ std::string DigestUtils::Result(DigestUtils::Type type) printf("Failed to Calculate Hash Relsult\n"); } int temporaryVariableFirst = 2; - int temporaryVariableSecond = 3; if (type == Type::HEX) { + int temporaryVariableSecond = 3; char* res = new char[len * temporaryVariableFirst + 1]; for (unsigned int i = 0; i < len; i++) { snprintf_s(&res[i * temporaryVariableFirst], temporaryVariableSecond, diff --git a/hapsigntool_cpp/common/include/digest_common.h b/hapsigntool_cpp/common/include/digest_common.h index f0d6b1f7..b024ed44 100644 --- a/hapsigntool_cpp/common/include/digest_common.h +++ b/hapsigntool_cpp/common/include/digest_common.h @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef SIGNATRUETOOLS_DIGEST_UTILS_H -#define SIGNATRUETOOLS_DIGEST_UTILS_H +#ifndef SIGNATRUETOOLS_DIGESTCOMMON_H +#define SIGNATRUETOOLS_DIGESTCOMMON_H #include #include @@ -61,4 +61,4 @@ private: }; } // namespace SignatureTools } // namespace OHOS -#endif // SIGNATRUETOOLS_VERIFY_OPENSSL_UTILS_H +#endif // SIGNATRUETOOLS_DIGESTCOMMON_H diff --git a/hapsigntool_cpp/common/src/byte_buffer.cpp b/hapsigntool_cpp/common/src/byte_buffer.cpp index 146c4f31..984409d6 100644 --- a/hapsigntool_cpp/common/src/byte_buffer.cpp +++ b/hapsigntool_cpp/common/src/byte_buffer.cpp @@ -27,7 +27,7 @@ const int32_t ByteBuffer::HEX_PRINT_LENGTH = 3; template std::shared_ptr make_shared_array(size_t size) { - if (size <= 0) { + if (size == 0) { return NULL; } T* buffer = new (std::nothrow)T[size]; @@ -514,6 +514,10 @@ ByteBuffer& ByteBuffer::Slice() return *this; } int32_t newCapacity = limit - position; + if(newCapacity < 0) { + SIGNATURE_TOOLS_LOGE("newCapacity %d is too small", newCapacity); + return *this; + } auto newBuffer = make_shared_array(newCapacity); if (newBuffer == nullptr) { SIGNATURE_TOOLS_LOGE("make_shared_array failed"); diff --git a/hapsigntool_cpp/common/src/localization_adapter.cpp b/hapsigntool_cpp/common/src/localization_adapter.cpp index c936c370..bd5b173b 100644 --- a/hapsigntool_cpp/common/src/localization_adapter.cpp +++ b/hapsigntool_cpp/common/src/localization_adapter.cpp @@ -17,6 +17,11 @@ #include "localization_adapter.h" #include "constant.h" +#include +#include +#include +#include +#include namespace OHOS { namespace SignatureTools { diff --git a/hapsigntool_cpp/hap/provider/src/sign_provider.cpp b/hapsigntool_cpp/hap/provider/src/sign_provider.cpp index 64327903..18c0593f 100644 --- a/hapsigntool_cpp/hap/provider/src/sign_provider.cpp +++ b/hapsigntool_cpp/hap/provider/src/sign_provider.cpp @@ -646,7 +646,7 @@ bool SignProvider::CheckSignatureAlg() // Remove trailing spaces size_t end = signAlg.find_last_not_of(" "); if (end != std::string::npos) { - signAlg = signAlg.substr(0, end + 1); + signAlg.resize(end + 1); } for (auto it = VALID_SIGN_ALG_NAME.begin(); it != VALID_SIGN_ALG_NAME.end(); it++) { if (StringUtils::CaseCompare(*it, signAlg)) { diff --git a/hapsigntool_cpp/hap/sign/src/sign_bin.cpp b/hapsigntool_cpp/hap/sign/src/sign_bin.cpp index da794d02..3a6a7736 100644 --- a/hapsigntool_cpp/hap/sign/src/sign_bin.cpp +++ b/hapsigntool_cpp/hap/sign/src/sign_bin.cpp @@ -114,7 +114,6 @@ std::vector SignBin::GenerateFileDigest(const std::string& outputFile, SIGNATURE_TOOLS_LOGE("GetFileDigest failed."); return std::vector(); } - std::vector outputChunk; SignContentInfo contentInfo; contentInfo.AddContentHashData(0, SignatureBlockTags::HASH_ROOT_4K, HashUtils::GetHashAlgsId(alg), data.size(), data); diff --git a/hapsigntool_cpp/hap/sign/src/sign_hap.cpp b/hapsigntool_cpp/hap/sign/src/sign_hap.cpp index a9e6a68b..6392b68f 100644 --- a/hapsigntool_cpp/hap/sign/src/sign_hap.cpp +++ b/hapsigntool_cpp/hap/sign/src/sign_hap.cpp @@ -12,6 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include + #include "signature_tools_log.h" #include "signature_algorithm_helper.h" #include "bc_pkcs7_generator.h" @@ -98,6 +100,9 @@ void SignHap::EncodeListOfPairsToByteArray(const DigestParameter& digestParam, for (const auto& pair : nidAndcontentDigests) { encodeSize += INT_SIZE + INT_SIZE + INT_SIZE + pair.second.GetCapacity(); } + encodeSize = std::accumulate(nidAndcontentDigests.begin(), nidAndcontentDigests.end(), encodeSize, + [](int sum, const std::pair& pair) { + return sum + INT_SIZE + INT_SIZE + pair.second.GetCapacity(); }); result.SetCapacity(encodeSize); result.PutInt32(CONTENT_VERSION); // version result.PutInt32(BLOCK_NUMBER); // block number @@ -141,7 +146,9 @@ bool SignHap::GenerateHapSigningBlock(const std::string& hapSignatureSchemeBlock // uint128: magic // uint32: version long optionalBlockSize = 0L; - for (const auto& elem : optionalBlocks) optionalBlockSize += elem.optionalBlockValue.GetCapacity(); + optionalBlockSize = std::accumulate(optionalBlocks.begin(), optionalBlocks.end(), optionalBlockSize, + [](int64_t sum, const auto& elem) { + return sum + elem.optionalBlockValue.GetCapacity(); }); long resultSize = ((OPTIONAL_TYPE_SIZE + OPTIONAL_LENGTH_SIZE + OPTIONAL_OFFSET_SIZE) * (optionalBlocks.size() + 1)) + optionalBlockSize + @@ -184,7 +191,7 @@ bool SignHap::GenerateHapSigningBlock(const std::string& hapSignatureSchemeBlock result.PutInt32(optionalBlocks.size() + 1); // Signing block count result.PutInt64(resultSize); // length of hap signing block std::vector signingBlockMagic = HapUtils::GetHapSigningBlockMagic(compatibleVersion); - result.PutData((const char*)signingBlockMagic.data(), signingBlockMagic.size()); // magic + result.PutData(reinterpret_cast(signingBlockMagic.data()), signingBlockMagic.size()); // magic result.PutInt32(HapUtils::GetHapSigningBlockVersion(compatibleVersion)); // version return true; } diff --git a/hapsigntool_cpp/hap/utils/src/dynamic_lib_handle.cpp b/hapsigntool_cpp/hap/utils/src/dynamic_lib_handle.cpp index 91829321..c5a0e5af 100644 --- a/hapsigntool_cpp/hap/utils/src/dynamic_lib_handle.cpp +++ b/hapsigntool_cpp/hap/utils/src/dynamic_lib_handle.cpp @@ -20,7 +20,7 @@ namespace SignatureTools { void* DynamicLibHandle::handle = nullptr; DynamicLibHandle::~DynamicLibHandle() { - if (handle) { + if (handle != nullptr) { if (dlclose(handle) != 0) { SIGNATURE_TOOLS_LOGE("dlclose() %s", dlerror()); } diff --git a/hapsigntool_cpp/hap/verify/src/verify_elf.cpp b/hapsigntool_cpp/hap/verify/src/verify_elf.cpp index 47938dac..1c9cf8b6 100644 --- a/hapsigntool_cpp/hap/verify/src/verify_elf.cpp +++ b/hapsigntool_cpp/hap/verify/src/verify_elf.cpp @@ -124,7 +124,7 @@ bool VerifyElf::VerifyP7b(std::unordered_map& signBlockMap } VerifyHap hapVerify(false); std::unique_ptr profileBuffer = - std::make_unique((char*)profileByte.data(), profileByte.size()); + std::make_unique(reinterpret_cast(profileByte.data()), profileByte.size()); bool resultFlag = hapVerify.VerifyAppPkcs7(pkcs7Context, *profileBuffer); if (!resultFlag) { SIGNATURE_TOOLS_LOGE("verify elf profile failed on verify elf!"); diff --git a/hapsigntool_cpp/hap/verify/src/verify_hap.cpp b/hapsigntool_cpp/hap/verify/src/verify_hap.cpp index 27ed782c..9ff4dcd5 100644 --- a/hapsigntool_cpp/hap/verify/src/verify_hap.cpp +++ b/hapsigntool_cpp/hap/verify/src/verify_hap.cpp @@ -129,9 +129,10 @@ bool VerifyHap::HapOutPutCertChain(std::vector& certs, const std::string& certStr.emplace_back(StringUtils::x509CertToString(cert)); } std::string outPutCertChainContent; - for (auto& certstr : certStr) { - outPutCertChainContent += certstr; - } + outPutCertChainContent = std::accumulate(certStr.begin(), certStr.end(), std::string(), + [](std::string sum, const std::string& certstr) { + return sum + certstr; }); + if (FileUtils::Write(outPutCertChainContent, outPutPath) < 0) { SIGNATURE_TOOLS_LOGE("certChain write to file falied!\n"); return false; diff --git a/hapsigntool_cpp/profile/src/pkcs7_data.cpp b/hapsigntool_cpp/profile/src/pkcs7_data.cpp index 6f76172c..b5ed3cdc 100644 --- a/hapsigntool_cpp/profile/src/pkcs7_data.cpp +++ b/hapsigntool_cpp/profile/src/pkcs7_data.cpp @@ -521,7 +521,7 @@ int PKCS7Data::Pkcs7SignAttr(PKCS7_SIGNER_INFO* info) unsigned char* sigRet = NULL; int sigLen = 0; - attrLen = ASN1_item_i2d((ASN1_VALUE*)info->auth_attr, &attrBuf, + attrLen = ASN1_item_i2d(reinterpret_cast(info->auth_attr), &attrBuf, ASN1_ITEM_rptr(PKCS7_ATTR_SIGN)); if (!attrBuf) { OPENSSL_free(attrBuf); @@ -683,7 +683,7 @@ static int PKCS7DataFinalSetContent(PKCS7* pkcs7, ASN1_OCTET_STRING* asn1Str, BI BIO_set_flags(ioTmp, BIO_FLAGS_MEM_RDONLY); BIO_set_mem_eof_return(ioTmp, 0); - ASN1_STRING_set0(asn1Str, (unsigned char*)contentData, contentLen); + ASN1_STRING_set0(asn1Str, reinterpret_cast(contentData), contentLen); } } return 1; diff --git a/hapsigntool_cpp/profile/src/profile_sign_tool.cpp b/hapsigntool_cpp/profile/src/profile_sign_tool.cpp index 95923687..3450a934 100644 --- a/hapsigntool_cpp/profile/src/profile_sign_tool.cpp +++ b/hapsigntool_cpp/profile/src/profile_sign_tool.cpp @@ -28,11 +28,6 @@ int ProfileSignTool::GenerateP7b(LocalizationAdapter& adapter, const std::string { std::unique_ptr signerFactory = std::make_unique(); int result = RET_OK; - if (signerFactory == NULL) { - PrintErrorNumberMsg("INVALIDPARAM_ERROR", INVALIDPARAM_ERROR, - "signerFactory is NULL, create signerFactor failed"); - return INVALIDPARAM_ERROR; - } std::shared_ptr signer(signerFactory->GetSigner(adapter)); if (signer == NULL) { SIGNATURE_TOOLS_LOGE("signer is NULL, get signer failed"); @@ -40,7 +35,7 @@ int ProfileSignTool::GenerateP7b(LocalizationAdapter& adapter, const std::string } const std::string sigAlg = adapter.GetSignAlg(); // ret is the generated p7b data - result = SignProfile(content, signer, sigAlg, ret) < 0; + result = SignProfile(content, signer, sigAlg, ret); if (result < 0) { SIGNATURE_TOOLS_LOGE("generate p7b failed"); return SIGN_ERROR; diff --git a/hapsigntool_cpp/profile/src/profile_verify.cpp b/hapsigntool_cpp/profile/src/profile_verify.cpp index 241b2efa..5eae10cb 100644 --- a/hapsigntool_cpp/profile/src/profile_verify.cpp +++ b/hapsigntool_cpp/profile/src/profile_verify.cpp @@ -232,7 +232,7 @@ AppProvisionVerifyResult ReturnIfIntIsNonPositive(int num, const std::string& er return PROVISION_OK; } -static AppProvisionVerifyResult CheckProfileValidType(ProfileInfo& info) +static AppProvisionVerifyResult CheckProfileValidType(const ProfileInfo& info) { if (info.type == ProvisionType::DEBUG) { if (ReturnIfStringIsEmpty(info.bundleInfo.developmentCertificate, diff --git a/hapsigntool_cpp/signer/src/signer_factory.cpp b/hapsigntool_cpp/signer/src/signer_factory.cpp index e953bf8c..0a937947 100644 --- a/hapsigntool_cpp/signer/src/signer_factory.cpp +++ b/hapsigntool_cpp/signer/src/signer_factory.cpp @@ -33,12 +33,6 @@ std::shared_ptr SignerFactory::GetSigner(LocalizationAdapter& adapter)co adapter.ResetPwd(); STACK_OF(X509)*certs = adapter.GetSignCertChain(); std::shared_ptr signer = std::make_shared(keyPair, certs); - if (signer == NULL) { - SIGNATURE_TOOLS_LOGE("signer is NULL, create LocalSigner failed"); - EVP_PKEY_free(keyPair); - sk_X509_pop_free(certs, X509_free); - return NULL; - } return signer; } diff --git a/hapsigntool_cpp/utils/src/cert_dn_utils.cpp b/hapsigntool_cpp/utils/src/cert_dn_utils.cpp index 526b0d8a..d7893d88 100644 --- a/hapsigntool_cpp/utils/src/cert_dn_utils.cpp +++ b/hapsigntool_cpp/utils/src/cert_dn_utils.cpp @@ -70,7 +70,7 @@ X509_NAME* BuildDN(const std::string &nameString, X509_REQ* req) return nullptr; } X509_NAME_add_entry_by_txt(subject, idx->first.c_str(), MBSTRING_ASC, - (const unsigned char*)idx->second.c_str(), -1, -1, 0); + reinterpret_cast(idx->second.c_str()), -1, -1, 0); } return subject; } diff --git a/hapsigntool_cpp/utils/src/hap_signer_block_utils.cpp b/hapsigntool_cpp/utils/src/hap_signer_block_utils.cpp index 51bfad3f..56f13d1f 100644 --- a/hapsigntool_cpp/utils/src/hap_signer_block_utils.cpp +++ b/hapsigntool_cpp/utils/src/hap_signer_block_utils.cpp @@ -343,6 +343,7 @@ bool HapSignerBlockUtils::FindHapSubSigningBlock(RandomAccessFile& hapFile, ByteBuffer hapBlockHead(ZIP_CD_SIZE_OFFSET_IN_EOCD); int64_t ret = hapFile.ReadFileFullyFromOffset(hapBlockHead, readHeadOffset); if (ret < 0) { + SIGNATURE_TOOLS_LOGE("read %dst head error: %" PRId64, i, ret); return false; } HapSubSignBlockHead subSignBlockHead; @@ -587,8 +588,6 @@ int32_t HapSignerBlockUtils::GetChunkCount(int64_t inputSize, int64_t chunkSize) if (chunkSize <= 0 || inputSize > LLONG_MAX - chunkSize) { return 0; } - if (chunkSize == 0) - return 0; int64_t res = (inputSize + chunkSize - 1) / chunkSize; if (res > INT_MAX || res < 0) { return 0; diff --git a/hapsigntool_cpp/utils/src/key_store_helper.cpp b/hapsigntool_cpp/utils/src/key_store_helper.cpp index 4b3ea3ea..c1a723ea 100644 --- a/hapsigntool_cpp/utils/src/key_store_helper.cpp +++ b/hapsigntool_cpp/utils/src/key_store_helper.cpp @@ -167,9 +167,12 @@ bool KeyStoreHelper::InitX509(X509& cert, EVP_PKEY& evpPkey) X509_set_serialNumber(&cert, ai); X509_gmtime_adj(X509_get_notBefore(&cert), 0); X509_gmtime_adj(X509_get_notAfter(&cert), (long)DEFAULT_VALIDITY_DAYS * ONE_DAY_TIME); - if (!X509_NAME_add_entry_by_txt(issuerName, "C", MBSTRING_ASC, (unsigned char*)"US", -1, -1, 0) - || !X509_NAME_add_entry_by_txt(issuerName, "O", MBSTRING_ASC, (unsigned char*)"My Company", -1, -1, 0) - || !X509_NAME_add_entry_by_txt(issuerName, "CN", MBSTRING_ASC, (unsigned char*)"My Issuer", -1, -1, 0)) { + if (!X509_NAME_add_entry_by_txt(issuerName, "C", + MBSTRING_ASC, reinterpret_cast("US"), -1, -1, 0) + || !X509_NAME_add_entry_by_txt(issuerName, "O", + MBSTRING_ASC, reinterpret_cast("My Company"), -1, -1, 0) + || !X509_NAME_add_entry_by_txt(issuerName, "CN", + MBSTRING_ASC, reinterpret_cast("My Issuer"), -1, -1, 0)) { KeyPairFree(bnSerial, issuerName, subjectName, ai, "Failed to initialize the x509 structure.X509_NAME type"); return false; @@ -743,8 +746,8 @@ err: bool KeyStoreHelper::SetX509Alias(int len, X509* x509, unsigned char* data) { - int r; if (len >= 0) { + int r; r = X509_alias_set1(x509, data, len); OPENSSL_free(data); if (!r) { diff --git a/hapsigntool_cpp/utils/src/string_utils.cpp b/hapsigntool_cpp/utils/src/string_utils.cpp index d296ab74..e85d7ef2 100644 --- a/hapsigntool_cpp/utils/src/string_utils.cpp +++ b/hapsigntool_cpp/utils/src/string_utils.cpp @@ -32,11 +32,8 @@ bool StringUtils::ContainsCase(const std::vector &strs, const std:: std::transform(fileSuffix.begin(), fileSuffix.end(), fileSuffix.begin(), [](unsigned char c) { return std::tolower(c); }); - for (const std::string& val : strs) { - if (val == fileSuffix) - return true; - } - return false; + return std::any_of(strs.begin(), strs.end(), [&fileSuffix](const std::string& val) { + return val == fileSuffix; }); } bool StringUtils::CaseCompare(const std::string& str1, const std::string& str2) @@ -72,11 +69,7 @@ std::string StringUtils::FormatLoading(std::string& dealStr) del.insert(position + 1, " "); position++; } - for (auto& ch : del) { - if (ch == slash) { - ch = comma; - } - } + std::replace(del.begin(), del.end(), slash, comma); return del.append("\n"); } std::string StringUtils::Pkcs7ToString(PKCS7* p7) diff --git a/hapsigntool_cpp/zip/src/random_access_file_input.cpp b/hapsigntool_cpp/zip/src/random_access_file_input.cpp index b05817c9..92023ae3 100644 --- a/hapsigntool_cpp/zip/src/random_access_file_input.cpp +++ b/hapsigntool_cpp/zip/src/random_access_file_input.cpp @@ -68,10 +68,10 @@ bool RandomAccessFileInput::CopyTo(int64_t offset, int size, ByteBuffer& buffer) int originalLimit = buffer.GetLimit(); buffer.SetLimit(buffer.GetPosition() + size); - int64_t readSize; while (remaining > 0) { - { - std::mutex tmpMutex; + int64_t readSize; + std::mutex tmpMutex; + { std::scoped_lock lock(tmpMutex); readSize = file.ReadFileFullyFromOffset(buffer, offsetInFile); } diff --git a/hapsigntool_cpp/zip/src/random_access_file_output.cpp b/hapsigntool_cpp/zip/src/random_access_file_output.cpp index 411257a5..da822e27 100644 --- a/hapsigntool_cpp/zip/src/random_access_file_output.cpp +++ b/hapsigntool_cpp/zip/src/random_access_file_output.cpp @@ -44,8 +44,8 @@ bool RandomAccessFileOutput::Write(ByteBuffer& buffer) if (length == 0) { return false; } + std::mutex tmpMutex; { - std::mutex tmpMutex; std::scoped_lock lock(tmpMutex); if (file->WriteToFile(buffer, position, length) < 0) { PrintErrorNumberMsg("IO_ERROR", IO_ERROR, "write from ByteBuffer to RandomAccessFile failed"); diff --git a/hapsigntool_cpp/zip/src/zip_entry_data.cpp b/hapsigntool_cpp/zip/src/zip_entry_data.cpp index 46ae20ec..92af60d2 100644 --- a/hapsigntool_cpp/zip/src/zip_entry_data.cpp +++ b/hapsigntool_cpp/zip/src/zip_entry_data.cpp @@ -31,12 +31,12 @@ ZipEntryData* ZipEntryData::GetZipEntry(std::ifstream& input, uint32_t entryOffs { uint32_t offset = entryOffset; /* read entry header by file and offset. */ - std::string retStr; - if (FileUtils::ReadInputByOffsetAndLength(input, entryOffset, ZipEntryHeader::HEADER_LENGTH, retStr) != 0) { + std::string headStr; + if (FileUtils::ReadInputByOffsetAndLength(input, entryOffset, ZipEntryHeader::HEADER_LENGTH, headStr) != 0) { SIGNATURE_TOOLS_LOGE("read zip entry head failed in file"); return nullptr; } - ZipEntryHeader* entryHeader = ZipEntryHeader::GetZipEntryHeader(retStr); + ZipEntryHeader* entryHeader = ZipEntryHeader::GetZipEntryHeader(headStr); if (!entryHeader) { return nullptr; } diff --git a/hapsigntool_cpp/zip/src/zip_signer.cpp b/hapsigntool_cpp/zip/src/zip_signer.cpp index cc1808e0..7de9d235 100644 --- a/hapsigntool_cpp/zip/src/zip_signer.cpp +++ b/hapsigntool_cpp/zip/src/zip_signer.cpp @@ -157,7 +157,7 @@ bool ZipSigner::GetZipCentralDirectory(std::ifstream& input) std::string ZipSigner::GetSigningBlock(std::ifstream& file) { - uint64_t size = m_cDOffset - m_signingOffset; + int64_t size = static_cast(m_cDOffset) - static_cast(m_signingOffset); if (size < 0) { SIGNATURE_TOOLS_LOGE("signing offset in front of entry end"); return ""; diff --git a/hapsigntool_cpp_test/fuzztest/generate_ca/generateca012_fuzzer/generateca012_fuzzer.cpp b/hapsigntool_cpp_test/fuzztest/generate_ca/generateca012_fuzzer/generateca012_fuzzer.cpp index eeaf9e9b..61d8cc80 100644 --- a/hapsigntool_cpp_test/fuzztest/generate_ca/generateca012_fuzzer/generateca012_fuzzer.cpp +++ b/hapsigntool_cpp_test/fuzztest/generate_ca/generateca012_fuzzer/generateca012_fuzzer.cpp @@ -33,7 +33,6 @@ bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size) if (!data || !size) { return true; } - std::shared_ptr api = std::make_shared(); std::shared_ptr params = std::make_shared(); std::string keyAlias = "oh-app-sign-srv-ca-key-v1"; std::string issuerkeyAlias = "oh-root-ca-key-v1"; diff --git a/hapsigntool_cpp_test/fuzztest/process_cmd/processcmd022_fuzzer/processcmd022_fuzzer.cpp b/hapsigntool_cpp_test/fuzztest/process_cmd/processcmd022_fuzzer/processcmd022_fuzzer.cpp index 2d172712..4f4bb8d4 100644 --- a/hapsigntool_cpp_test/fuzztest/process_cmd/processcmd022_fuzzer/processcmd022_fuzzer.cpp +++ b/hapsigntool_cpp_test/fuzztest/process_cmd/processcmd022_fuzzer/processcmd022_fuzzer.cpp @@ -136,8 +136,8 @@ bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size) int argc = 30; bool ret = false; - ret = ParamsRunTool::ProcessCmd(argv, argc); - ret = GenerateAppCertTest2(); + ParamsRunTool::ProcessCmd(argv, argc); + GenerateAppCertTest2(); ret = GenerateAppCertTest3(); return ret; diff --git a/hapsigntool_cpp_test/fuzztest/process_cmd/processcmd023_fuzzer/processcmd023_fuzzer.cpp b/hapsigntool_cpp_test/fuzztest/process_cmd/processcmd023_fuzzer/processcmd023_fuzzer.cpp index 4c2a5897..eccf98d9 100644 --- a/hapsigntool_cpp_test/fuzztest/process_cmd/processcmd023_fuzzer/processcmd023_fuzzer.cpp +++ b/hapsigntool_cpp_test/fuzztest/process_cmd/processcmd023_fuzzer/processcmd023_fuzzer.cpp @@ -29,7 +29,6 @@ bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size) return true; } X509* cert = X509_new(); - X509* certRet = nullptr; std::vector certChain; std::string inputType = "clientAuthentication"; CmdUtil::VerifyType(inputType); @@ -46,8 +45,8 @@ bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size) X509_free(cert); CertTools certTool; status = certTool.SetSubjectForCert(nullptr, nullptr); - certRet = certTool.GenerateRootCertificate(nullptr, nullptr, &options); - status = FileUtils::WriteInputToOutPut("", ""); + certTool.GenerateRootCertificate(nullptr, nullptr, &options); + FileUtils::WriteInputToOutPut("", ""); FileUtils::DelDir(""); return true; diff --git a/hapsigntool_cpp_test/fuzztest/process_cmd/processcmd024_fuzzer/processcmd024_fuzzer.cpp b/hapsigntool_cpp_test/fuzztest/process_cmd/processcmd024_fuzzer/processcmd024_fuzzer.cpp index 48ab4328..748a4bfa 100644 --- a/hapsigntool_cpp_test/fuzztest/process_cmd/processcmd024_fuzzer/processcmd024_fuzzer.cpp +++ b/hapsigntool_cpp_test/fuzztest/process_cmd/processcmd024_fuzzer/processcmd024_fuzzer.cpp @@ -33,33 +33,25 @@ bool DoSomethingInterestingWithMyAPI(const uint8_t* data, size_t size) Params param; std::string str; - std::string retStr; std::string algName; - bool retBool = false; int algId = 256; std::vector paramFields; std::vector fileBytes; - std::unordered_set unordered; - std::vector vec; int64_t length = 0; SignatureAlgorithmHelper out; - ByteBuffer crlBuffer; - std::ofstream crlFile; CertChain certsChain; Pkcs7Context pkcs7Context; - Options* options = nullptr; - X509_CRL* x509Crl = nullptr; param.SetMethod(str); - retStr = param.GetMethod(); - options = param.GetOptions(); - unordered = param.InitParamField(paramFields); - retBool = param.GetSignatureAlgorithm(str, out); - retStr = HashUtils::GetHashAlgName(algId); - vec = HashUtils::GetDigestFromBytes(fileBytes, length, algName); - retBool = VerifyCertOpensslUtils::VerifyCrl(certsChain, nullptr, pkcs7Context); - x509Crl = VerifyCertOpensslUtils::GetCrlBySignedCertIssuer(nullptr, nullptr); - retBool = VerifyCertOpensslUtils::GetIssuerFromX509(nullptr, str); + param.GetMethod(); + param.GetOptions(); + param.InitParamField(paramFields); + param.GetSignatureAlgorithm(str, out); + algName = HashUtils::GetHashAlgName(algId); + HashUtils::GetDigestFromBytes(fileBytes, length, algName); + VerifyCertOpensslUtils::VerifyCrl(certsChain, nullptr, pkcs7Context); + VerifyCertOpensslUtils::GetCrlBySignedCertIssuer(nullptr, nullptr); + VerifyCertOpensslUtils::GetIssuerFromX509(nullptr, str); return true; } diff --git a/hapsigntool_cpp_test/fuzztest/profile/profile001_fuzzer/profile001_fuzzer.cpp b/hapsigntool_cpp_test/fuzztest/profile/profile001_fuzzer/profile001_fuzzer.cpp index e4e405b2..8407d466 100644 --- a/hapsigntool_cpp_test/fuzztest/profile/profile001_fuzzer/profile001_fuzzer.cpp +++ b/hapsigntool_cpp_test/fuzztest/profile/profile001_fuzzer/profile001_fuzzer.cpp @@ -55,7 +55,6 @@ bool SignProfileTest001(const uint8_t* data, size_t size) bool SignProfileTest002(const uint8_t* data, size_t size) { - std::string content(data, data + size); Options options; std::string mode = SIGN_PROFILE_MODE; std::string keyAlias = SIGN_PROFILE_KEY_ALIAS; -- Gitee From a0ea5ce2e0bc2ac85737cf072f0f089261348685 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E6=97=8B=E9=A3=8Elc?= Date: Fri, 15 Nov 2024 20:26:25 +0800 Subject: [PATCH 2/7] modify Signed-off-by: liuchang --- hapsigntool_cpp/api/src/cert_tools.cpp | 536 ++++++++++-------- .../api/src/sign_tool_service_impl.cpp | 105 ++-- .../codesigning/sign/src/code_signing.cpp | 1 + hapsigntool_cpp/common/src/byte_buffer.cpp | 4 - hapsigntool_cpp/hap/sign/src/sign_hap.cpp | 21 +- hapsigntool_cpp/hap/verify/src/verify_hap.cpp | 5 +- 6 files changed, 363 insertions(+), 309 deletions(-) diff --git a/hapsigntool_cpp/api/src/cert_tools.cpp b/hapsigntool_cpp/api/src/cert_tools.cpp index a89dc606..383bde4d 100644 --- a/hapsigntool_cpp/api/src/cert_tools.cpp +++ b/hapsigntool_cpp/api/src/cert_tools.cpp @@ -177,137 +177,158 @@ bool CertTools::SetBisicConstraintsPathLen(Options* options, X509* cert) bool CertTools::SignForSubCert(X509* cert, X509_REQ* subcsr, X509_REQ* rootcsr, EVP_PKEY* caPrikey, Options* options) { + if (caPrikey == nullptr || rootcsr == nullptr || subcsr == nullptr) { + SIGNATURE_TOOLS_LOGE("Sign failed because of caPrikey, roocsr or subcsr is nullptr"); + VerifyHapOpensslUtils::GetOpensslErrorMessage(); + return false; + } + bool result = false; std::string signAlg = options->GetString(Options::SIGN_ALG); EVP_PKEY* pubKey = X509_REQ_get_pubkey(subcsr); - X509_NAME* issuerName = X509_REQ_get_subject_name(rootcsr); - X509_NAME* subjectName = X509_REQ_get_subject_name(subcsr); - if (pubKey == NULL) { + if (pubKey == nullptr) { SIGNATURE_TOOLS_LOGE("X509_REQ_get_pubkey failed"); - goto err; - } - if (caPrikey == nullptr || rootcsr == nullptr || subcsr == nullptr) { - SIGNATURE_TOOLS_LOGE("Sign failed because of caPrikey, roocsr or subcsr is nullptr"); - goto err; - } - result = (!X509_set_pubkey(cert, pubKey)); - if (result) { - SIGNATURE_TOOLS_LOGE("X509_set_pubkey failed"); - goto err; - } - result = (!X509_set_issuer_name(cert, issuerName)); - if (result) { - SIGNATURE_TOOLS_LOGE("X509_set_issuer_name failed"); - goto err; - } - result = (!X509_set_subject_name(cert, subjectName)); - if (result) { - SIGNATURE_TOOLS_LOGE("X509_set_subject_name failed"); - goto err; + VerifyHapOpensslUtils::GetOpensslErrorMessage(); + return false; } - result = (!SignCert(cert, caPrikey, signAlg)); + X509_NAME* issuerName = X509_REQ_get_subject_name(rootcsr); + X509_NAME* subjectName = X509_REQ_get_subject_name(subcsr); + do { + result = (!X509_set_pubkey(cert, pubKey)); + if (result) { + SIGNATURE_TOOLS_LOGE("X509_set_pubkey failed"); + break; + } + result = (!X509_set_issuer_name(cert, issuerName)); + if (result) { + SIGNATURE_TOOLS_LOGE("X509_set_issuer_name failed"); + break; + } + result = (!X509_set_subject_name(cert, subjectName)); + if (result) { + SIGNATURE_TOOLS_LOGE("X509_set_subject_name failed"); + break; + } + result = (!SignCert(cert, caPrikey, signAlg)); + if (result) { + break; + } + } while (0); + + EVP_PKEY_free(pubKey); if (result) { - goto err; + X509_NAME_free(issuerName); + X509_NAME_free(subjectName); + VerifyHapOpensslUtils::GetOpensslErrorMessage(); + return false; } - EVP_PKEY_free(pubKey); return true; -err: - EVP_PKEY_free(pubKey); - X509_NAME_free(issuerName); - X509_NAME_free(subjectName); - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - return false; } X509* CertTools::SignCsrGenerateCert(X509_REQ* rootcsr, X509_REQ* subcsr, EVP_PKEY* keyPair, Options* options) { - bool result = false; X509* cert = X509_new(); - if (cert == NULL) { - SIGNATURE_TOOLS_LOGE("create X509 cert failed"); + if (cert == nullptr) { + SIGNATURE_TOOLS_LOGE("failed to create X509 cert"); return nullptr; } - int validity = options->GetInt(Options::VALIDITY); - result = (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || - !SetCertSerialNum(cert)); - if (result) { - goto err; - } - result = SetCertValidity(cert, validity); - if (!result) { - goto err; - } - result = (!SetBisicConstraintsPathLen(options, cert) || - !SetKeyIdentifierExt(cert) || - !SetAuthorizeKeyIdentifierExt(cert)|| - !SetKeyUsage(cert, options) || - !SignForSubCert(cert, subcsr, rootcsr, keyPair, options)); + bool result = false; + do { + int validity = options->GetInt(Options::VALIDITY); + result = (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || + !SetCertSerialNum(cert)); + if (result) { + break; + } + result = (!SetCertValidity(cert, validity)); + if (result) { + break; + } + result = (!SetBisicConstraintsPathLen(options, cert) || + !SetKeyIdentifierExt(cert) || + !SetAuthorizeKeyIdentifierExt(cert) || + !SetKeyUsage(cert, options) || + !SignForSubCert(cert, subcsr, rootcsr, keyPair, options)); + if (result) { + break; + } + } while (0); + if (result) { - goto err; + SIGNATURE_TOOLS_LOGE("failed to generate X509 cert by csr"); + X509_free(cert); + return nullptr; } - return cert; -err: - X509_free(cert); - return nullptr; + return cert; } bool CertTools::SetSubjectForCert(X509_REQ* certReq, X509* cert) { - if (certReq == nullptr) { - SIGNATURE_TOOLS_LOGE("set subjcet failed because of certReq is nullptr"); - goto err; - } - - if (X509_set_subject_name(cert, X509_REQ_get_subject_name(certReq)) != 1) { - SIGNATURE_TOOLS_LOGE("X509_set_issuer_name failed"); - goto err; - } + bool result = false; + do { + if (certReq == nullptr) { + SIGNATURE_TOOLS_LOGE("set subjcet failed because of certReq is nullptr"); + break; + } + if (X509_set_subject_name(cert, X509_REQ_get_subject_name(certReq)) != 1) { + SIGNATURE_TOOLS_LOGE("X509_set_issuer_name failed"); + break; + } + if (X509_set_issuer_name(cert, X509_REQ_get_subject_name(certReq)) != 1) { + SIGNATURE_TOOLS_LOGE("X509_set_issuer_name failed"); + break; + } + result = true; + } while (0); - if (X509_set_issuer_name(cert, X509_REQ_get_subject_name(certReq)) != 1) { - SIGNATURE_TOOLS_LOGE("X509_set_issuer_name failed"); - goto err; + if (!result) { + VerifyHapOpensslUtils::GetOpensslErrorMessage(); } - return true; -err: - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - return false; + return result; } + X509* CertTools::GenerateRootCertificate(EVP_PKEY* keyPair, X509_REQ* certReq, Options* options) { bool result = false; X509* cert = X509_new(); - if (cert == NULL) { - SIGNATURE_TOOLS_LOGE("create X509 cert failed"); + if (cert == nullptr) { + SIGNATURE_TOOLS_LOGE("failed to create X509 cert"); return nullptr; } - int validity = options->GetInt(Options::VALIDITY); - std::string signAlg = options->GetString(Options::SIGN_ALG); - result = (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || - !SetCertSerialNum(cert)); - if (result) { - goto err; - } - if (!SetCertValidityStartAndEnd(cert, DEFAULT_START_VALIDITY, validity)) { - goto err; - } - result = (!SetBisicConstraintsPathLen(options, cert) || + do { + int validity = options->GetInt(Options::VALIDITY); + std::string signAlg = options->GetString(Options::SIGN_ALG); + result = (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || + !SetCertSerialNum(cert)); + if (result) { + break; + } + result = (!SetCertValidityStartAndEnd(cert, DEFAULT_START_VALIDITY, validity)); + if (result) { + break; + } + result = (!SetBisicConstraintsPathLen(options, cert) || !SetSubjectForCert(certReq, cert) || !SetCertPublickKey(cert, certReq) || !SetKeyIdentifierExt(cert) || !SetKeyUsage(cert, options)); + if (result) { + break; + } + result = (!SignCert(cert, keyPair, signAlg)); + if (result) { + break; + } + } while (0); + if (result) { - goto err; - } - result = (!SignCert(cert, keyPair, signAlg)); - if (result) { - goto err; + SIGNATURE_TOOLS_LOGE("failed to generate root cert"); + X509_free(cert); + return nullptr; } return cert; -err: - X509_free(cert); - return nullptr; } X509* CertTools::GenerateSubCert(EVP_PKEY* keyPair, X509_REQ* rootcsr, Options* options) @@ -317,28 +338,33 @@ X509* CertTools::GenerateSubCert(EVP_PKEY* keyPair, X509_REQ* rootcsr, Options* X509_REQ* subcsr = nullptr; X509* subCert = nullptr; subKey = adapter->GetAliasKey(false); - if (subKey == nullptr) { - SIGNATURE_TOOLS_LOGE("failed to get the keypair"); - goto err; - } - subcsr = CertTools::GenerateCsr(subKey, options->GetString(Options::SIGN_ALG), - options->GetString(Options::SUBJECT)); - if (subcsr == nullptr) { - SIGNATURE_TOOLS_LOGE("failed to generate csr"); - goto err; - } - subCert = SignCsrGenerateCert(rootcsr, subcsr, keyPair, options); - if (subCert == nullptr) { - SIGNATURE_TOOLS_LOGE("failed to generate the subCert"); - goto err; - } + bool result = false; + do { + if (subKey == nullptr) { + SIGNATURE_TOOLS_LOGE("failed to get the keypair"); + break; + } + subcsr = CertTools::GenerateCsr(subKey, options->GetString(Options::SIGN_ALG), + options->GetString(Options::SUBJECT)); + if (subcsr == nullptr) { + SIGNATURE_TOOLS_LOGE("failed to generate csr"); + break; + } + subCert = SignCsrGenerateCert(rootcsr, subcsr, keyPair, options); + if (subCert == nullptr) { + SIGNATURE_TOOLS_LOGE("failed to generate the subCert"); + break; + } + result = true; + } while (0); + EVP_PKEY_free(subKey); X509_REQ_free(subcsr); + + if (!result) { + return nullptr; + } return subCert; -err: - EVP_PKEY_free(subKey); - X509_REQ_free(subcsr); - return nullptr; } bool CertTools::SetKeyUsage(X509* cert, Options* options) @@ -417,36 +443,39 @@ bool CertTools::SetExpandedInformation(X509* cert, Options* options) bool CertTools::SetPubkeyAndSignCert(X509* cert, X509_REQ* issuercsr, X509_REQ* certReq, EVP_PKEY* keyPair, Options* options) { - if (!X509_set_issuer_name(cert, X509_REQ_get_subject_name(issuercsr))) { - SIGNATURE_TOOLS_LOGE("X509_set_issuer_name failed"); - goto err; - } - - if (!X509_set_subject_name(cert, X509_REQ_get_subject_name(certReq))) { - SIGNATURE_TOOLS_LOGE("X509_set_subject_name failed"); - goto err; - } - if ((options->GetString(Options::SIGN_ALG)) == SIGN_ALG_SHA256) { - if (!X509_sign(cert, keyPair, EVP_sha256())) { - SIGNATURE_TOOLS_LOGE("X509_sign failed"); - goto err; + bool result = false; + do { + if (!X509_set_issuer_name(cert, X509_REQ_get_subject_name(issuercsr))) { + SIGNATURE_TOOLS_LOGE("X509_set_issuer_name failed"); + break; } - } else { - if (!X509_sign(cert, keyPair, EVP_sha384())) { - SIGNATURE_TOOLS_LOGE("X509_sign failed"); - goto err; + if (!X509_set_subject_name(cert, X509_REQ_get_subject_name(certReq))) { + SIGNATURE_TOOLS_LOGE("X509_set_subject_name failed"); + break; } + if ((options->GetString(Options::SIGN_ALG)) == SIGN_ALG_SHA256) { + if (!X509_sign(cert, keyPair, EVP_sha256())) { + SIGNATURE_TOOLS_LOGE("X509_sign failed"); + break; + } + } else { + if (!X509_sign(cert, keyPair, EVP_sha384())) { + SIGNATURE_TOOLS_LOGE("X509_sign failed"); + break; + } + } + result = true; + } while (0); + + if (!result) { + VerifyHapOpensslUtils::GetOpensslErrorMessage(); + return false; } return true; -err: - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - return false; } X509* CertTools::GenerateCert(EVP_PKEY* keyPair, X509_REQ* certReq, Options* options) { - int validity = 0; - bool result = false; X509_REQ* issuercsr = CertTools::GenerateCsr(keyPair, options->GetString(Options::SIGN_ALG), options->GetString(Options::ISSUER)); if (issuercsr == nullptr) { @@ -455,71 +484,86 @@ X509* CertTools::GenerateCert(EVP_PKEY* keyPair, X509_REQ* certReq, Options* opt } X509* cert = X509_new(); - if (cert == NULL) { - goto err; - } - result = (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || - !SetCertSerialNum(cert) || - !SetKeyIdentifierExt(cert)); - if (result) { - goto err; - } - validity = options->GetInt(Options::VALIDITY); - if (!SetCertValidityStartAndEnd(cert, DEFAULT_START_VALIDITY, validity)) { - goto err; + if (cert == nullptr) { + SIGNATURE_TOOLS_LOGE("failed to create X509 cert"); + return nullptr; } + bool result = false; + do { + result = (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || + !SetCertSerialNum(cert) || + !SetKeyIdentifierExt(cert)); + if (result) { + break; + } + int validity = options->GetInt(Options::VALIDITY); + result = (!SetCertValidityStartAndEnd(cert, DEFAULT_START_VALIDITY, validity)); + if (result) { + break; + } + result = (!SetBisicConstraints(options, cert) || + !SetCertPublickKey(cert, certReq) || + !SetExpandedInformation(cert, options) || + !SetPubkeyAndSignCert(cert, issuercsr, certReq, keyPair, options)); + if (result) { + break; + } + } while (0); - result = (!SetBisicConstraints(options, cert) || - !SetCertPublickKey(cert, certReq) || - !SetExpandedInformation(cert, options) || - !SetPubkeyAndSignCert(cert, issuercsr, certReq, keyPair, options)); + X509_REQ_free(issuercsr); if (result) { - goto err; + SIGNATURE_TOOLS_LOGE("failed to generate cert"); + X509_free(cert); + return nullptr; } - X509_REQ_free(issuercsr); return cert; -err: - X509_free(cert); - X509_REQ_free(issuercsr); - return nullptr; } X509_REQ* CertTools::GenerateCsr(EVP_PKEY* evpPkey, std::string signAlgorithm, std::string subject) { X509_NAME* name = nullptr; X509_REQ* req = X509_REQ_new(); - - if (!X509_REQ_set_pubkey(req, evpPkey)) { - SIGNATURE_TOOLS_LOGE("X509_REQ_set_pubkey failed"); - goto err; - } - - name = BuildDN(subject, req); - if (!name) { - SIGNATURE_TOOLS_LOGE("failed to add subject into cert"); - goto err; + if (req == nullptr) { + SIGNATURE_TOOLS_LOGE("X509_REQ_new failed"); + return nullptr; } + bool result = false; + do { + if (!X509_REQ_set_pubkey(req, evpPkey)) { + SIGNATURE_TOOLS_LOGE("X509_REQ_set_pubkey failed"); + break; + } - if (signAlgorithm == SIGN_ALG_SHA256) { - if (!X509_REQ_sign(req, evpPkey, EVP_sha256())) { - SIGNATURE_TOOLS_LOGE("X509_REQ_sign failed"); - goto err; + name = BuildDN(subject, req); + if (!name) { + SIGNATURE_TOOLS_LOGE("failed to add subject into cert"); + break; } - } else if (signAlgorithm == SIGN_ALG_SHA384) { - if (!X509_REQ_sign(req, evpPkey, EVP_sha384())) { - SIGNATURE_TOOLS_LOGE("X509_REQ_sign failed"); - goto err; + + if (signAlgorithm == SIGN_ALG_SHA256) { + if (!X509_REQ_sign(req, evpPkey, EVP_sha256())) { + SIGNATURE_TOOLS_LOGE("X509_REQ_sign failed"); + break; + } + } else if (signAlgorithm == SIGN_ALG_SHA384) { + if (!X509_REQ_sign(req, evpPkey, EVP_sha384())) { + SIGNATURE_TOOLS_LOGE("X509_REQ_sign failed"); + break; + } + } else { + PrintErrorNumberMsg("COMMAND_PARAM_ERROR", COMMAND_PARAM_ERROR, + "Sign algorithm format error! Please check again."); + break; } - } else { - PrintErrorNumberMsg("COMMAND_PARAM_ERROR", COMMAND_PARAM_ERROR, - "Sign algorithm format error! Please check again."); - goto err; + result = true; + } while (0); + + if (!result) { + VerifyHapOpensslUtils::GetOpensslErrorMessage(); + X509_REQ_free(req); + return nullptr; } - return req; -err: - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - X509_REQ_free(req); - return nullptr; + return req; } std::string CertTools::CsrToString(X509_REQ* csr) @@ -562,8 +606,7 @@ X509* CertTools::ReadfileToX509(const std::string& filename) X509* cert = X509_new(); if (cert == NULL) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); - SIGNATURE_TOOLS_LOGE("create X509 cert failed"); - X509_free(cert); + SIGNATURE_TOOLS_LOGE("failed to create X509 cert"); BIO_free(certBio); return nullptr; } @@ -593,29 +636,33 @@ bool CertTools::SetCertSerialNum(X509* cert) { BN_CTX* ctx = BN_CTX_new(); BIGNUM* bignum = BN_new(); - uint8_t serialNumberValue[RANDOM_SERIAL_NUMBER_LENGTH] = {0}; - if (!SerialNumberBuilder(serialNumberValue, sizeof(serialNumberValue))) { - goto err; - } - if (!BN_bin2bn(serialNumberValue, sizeof(serialNumberValue), bignum)) { - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - goto err; - } - if (BN_is_negative(bignum)) { - BN_set_negative(bignum, 0); // Replace negative numbers with positive ones - } - if (!BN_to_ASN1_INTEGER(bignum, X509_get_serialNumber(cert))) { - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - goto err; - } + bool result = false; + do { + uint8_t serialNumberValue[RANDOM_SERIAL_NUMBER_LENGTH] = {0}; + if (!SerialNumberBuilder(serialNumberValue, sizeof(serialNumberValue))) { + break; + } + if (!BN_bin2bn(serialNumberValue, sizeof(serialNumberValue), bignum)) { + VerifyHapOpensslUtils::GetOpensslErrorMessage(); + break; + } + if (BN_is_negative(bignum)) { + BN_set_negative(bignum, 0); // Replace negative numbers with positive ones + } + if (!BN_to_ASN1_INTEGER(bignum, X509_get_serialNumber(cert))) { + VerifyHapOpensslUtils::GetOpensslErrorMessage(); + break; + } + result = true; + } while (0); + BN_CTX_free(ctx); BN_free(bignum); + if (!result) { + SIGNATURE_TOOLS_LOGE("set x509 cert serial number failed"); + return false; + } return true; -err: - SIGNATURE_TOOLS_LOGE("set x509 cert serial number failed"); - BN_CTX_free(ctx); - BN_free(bignum); - return false; } bool CertTools::SetCertIssuerName(X509* cert, X509_NAME* issuer) @@ -847,50 +894,55 @@ X509* CertTools::GenerateEndCert(X509_REQ* csr, EVP_PKEY* issuerKeyPair, const char signCapacity[], int capacityLen) { X509* cert = X509_new(); // in this function, should not release X509cert memory - X509_REQ* issuerReq = nullptr; - bool result = false; - issuerReq = X509_REQ_new(); - std::string issuerStr = adapter.options->GetString(adapter.options->ISSUER); - int validity = adapter.options->GetInt(adapter.options->VALIDITY); - std::string signAlg = adapter.options->GetString(adapter.options->SIGN_ALG); - - if(cert == NULL) { - SIGNATURE_TOOLS_LOGE("create X509 cert failed"); - goto err; - } - if(issuerReq == NULL) { - SIGNATURE_TOOLS_LOGE("create X509 req failed"); - goto err; - } - result = (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || !SetCertSerialNum(cert)); - if (result) { - goto err; - } - result = (!SetCertIssuerName(cert, BuildDN(issuerStr, issuerReq)) || !SetCertSubjectName(cert, csr)); - if (result) { - goto err; - } - result = (!SetCertValidity(cert, validity) || !SetCertPublickKey(cert, csr)); - if (result) { - goto err; + if (cert == nullptr) { + SIGNATURE_TOOLS_LOGE("failed to create X509 cert"); + return nullptr; } - result = (!SetBasicExt(cert) || !SetkeyUsageExt(cert) || !SetKeyUsageEndExt(cert)); - if (result) { - goto err; + X509_REQ* issuerReq = X509_REQ_new(); + if (issuerReq == nullptr) { + SIGNATURE_TOOLS_LOGE("X509_REQ_new failed"); + adapter.AppAndProfileAssetsRealse({}, {}, {cert}); + return nullptr; } - result = (!SetKeyIdentifierExt(cert) || !SetSignCapacityExt(cert, signCapacity, capacityLen)); + bool result = false; + do { + std::string issuerStr = adapter.options->GetString(adapter.options->ISSUER); + int validity = adapter.options->GetInt(adapter.options->VALIDITY); + std::string signAlg = adapter.options->GetString(adapter.options->SIGN_ALG); + + result = (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || !SetCertSerialNum(cert)); + if (result) { + break; + } + result = (!SetCertIssuerName(cert, BuildDN(issuerStr, issuerReq)) || !SetCertSubjectName(cert, csr)); + if (result) { + break; + } + result = (!SetCertValidity(cert, validity) || !SetCertPublickKey(cert, csr)); + if (result) { + break; + } + result = (!SetBasicExt(cert) || !SetkeyUsageExt(cert) || !SetKeyUsageEndExt(cert)); + if (result) { + break; + } + result = (!SetKeyIdentifierExt(cert) || !SetSignCapacityExt(cert, signCapacity, capacityLen)); + if (result) { + break; + } + result = (!SignCert(cert, issuerKeyPair, signAlg)); + if (result) { + break; + } + } while (0); + if (result) { - goto err; - } - if (!SignCert(cert, issuerKeyPair, signAlg)) { - goto err; + SIGNATURE_TOOLS_LOGE("failed to generate end cert"); + adapter.AppAndProfileAssetsRealse({}, {issuerReq}, {cert}); + return nullptr; } - adapter.AppAndProfileAssetsRealse({}, {issuerReq}, {}); return cert; // return x509 assets -err: - adapter.AppAndProfileAssetsRealse({}, {issuerReq}, {cert}); - return nullptr; } } // namespace SignatureTools diff --git a/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp b/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp index dec920de..52d35349 100644 --- a/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp +++ b/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp @@ -44,7 +44,6 @@ bool SignToolServiceImpl::GenerateCA(Options* options) SIGNATURE_TOOLS_LOGE("failed to get subKey!"); return false; } - EVP_PKEY* rootKey = nullptr; if (isEmpty) { if (HandleIssuerKeyAliasEmpty(options) == RET_FAILED) { EVP_PKEY_free(subKey); @@ -53,6 +52,7 @@ bool SignToolServiceImpl::GenerateCA(Options* options) flag = GenerateRootCertToFile(options, subKey); EVP_PKEY_free(subKey); } else { + EVP_PKEY* rootKey = nullptr; if (HandleIsserKeyAliasNotEmpty(options) == RET_FAILED) { EVP_PKEY_free(subKey); return false; @@ -69,69 +69,82 @@ bool SignToolServiceImpl::GenerateCA(Options* options) bool SignToolServiceImpl::GenerateRootCertToFile(Options* options, EVP_PKEY* rootKey) { + if (rootKey == nullptr) { + SIGNATURE_TOOLS_LOGE("generate root cert failed because rootKey is nullptr!"); + return false; + } std::string signAlg = options->GetString(Options::SIGN_ALG); std::string subject = options->GetString(Options::SUBJECT); X509* certPtr = nullptr; X509_REQ* csr = nullptr; bool result = false; - if (rootKey == nullptr) { - goto err; - } - csr = CertTools::GenerateCsr(rootKey, signAlg, subject); - if (!csr) { - goto err; - } - certPtr = CertTools::GenerateRootCertificate(rootKey, csr, options); - if (!certPtr) { - goto err; - } - if (!X509CertVerify(certPtr, rootKey)) { - goto err; - } + do { + csr = CertTools::GenerateCsr(rootKey, signAlg, subject); + if (!csr) { + break; + } + certPtr = CertTools::GenerateRootCertificate(rootKey, csr, options); + if (!certPtr) { + break; + } + if (!X509CertVerify(certPtr, rootKey)) { + break; + } - if (!OutputModeOfCert(certPtr, options)) { - goto err; - } - result = true; -err: - if (result == false) + if (!OutputModeOfCert(certPtr, options)) { + break; + } + result = true; + } while (0); + + if (!result) { SIGNATURE_TOOLS_LOGE("generate root cert failed!"); - X509_free(certPtr); - X509_REQ_free(csr); - return result; + X509_free(certPtr); + X509_REQ_free(csr); + return false; + } + return true; } bool SignToolServiceImpl::GenerateSubCertToFile(Options* options, EVP_PKEY* rootKey) { + if (rootKey == nullptr) { + SIGNATURE_TOOLS_LOGE("generate sub cert failed because rootKey is nullptr!"); + return false; + } std::string signAlg = options->GetString(Options::SIGN_ALG); std::string issuer = options->GetString(Options::ISSUER); X509* cert = nullptr; X509_REQ* csr = nullptr; bool result = false; - if (rootKey == nullptr) { - goto err; - } - csr = CertTools::GenerateCsr(rootKey, signAlg, issuer); - if (!csr) { - goto err; - } - cert = CertTools::GenerateSubCert(rootKey, csr, options); - if (!cert) { - goto err; - } - if (!X509CertVerify(cert, rootKey)) { - goto err; - } - if (!OutputModeOfCert(cert, options)) { - goto err; - } - result = true; -err: - if (result == false) - SIGNATURE_TOOLS_LOGE("generate sub cert failed!"); + do { + if (rootKey == nullptr) { + break; + } + csr = CertTools::GenerateCsr(rootKey, signAlg, issuer); + if (!csr) { + break; + } + cert = CertTools::GenerateSubCert(rootKey, csr, options); + if (!cert) { + break; + } + if (!X509CertVerify(cert, rootKey)) { + break; + } + if (!OutputModeOfCert(cert, options)) { + break; + } + result = true; + } while (0); + X509_free(cert); X509_REQ_free(csr); - return result; + if (!result) { + SIGNATURE_TOOLS_LOGE("generate sub cert failed!"); + return false; + } + return true; } int SignToolServiceImpl::HandleIssuerKeyAliasEmpty(Options* options) diff --git a/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp b/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp index b30f8593..aa4eb373 100644 --- a/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp +++ b/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp @@ -56,6 +56,7 @@ bool CodeSigning::GetCodeSignBlock(const std::string &input, int64_t offset, } int64_t dataSizeInt64 = ComputeDataSize(zip); if (dataSizeInt64 < 0) { + SIGNATURE_TOOLS_LOGE("SignFile Failed because dataSize is invalid"); return false; } uint32_t dataSize = static_cast(dataSizeInt64); diff --git a/hapsigntool_cpp/common/src/byte_buffer.cpp b/hapsigntool_cpp/common/src/byte_buffer.cpp index 984409d6..a24266cc 100644 --- a/hapsigntool_cpp/common/src/byte_buffer.cpp +++ b/hapsigntool_cpp/common/src/byte_buffer.cpp @@ -514,10 +514,6 @@ ByteBuffer& ByteBuffer::Slice() return *this; } int32_t newCapacity = limit - position; - if(newCapacity < 0) { - SIGNATURE_TOOLS_LOGE("newCapacity %d is too small", newCapacity); - return *this; - } auto newBuffer = make_shared_array(newCapacity); if (newBuffer == nullptr) { SIGNATURE_TOOLS_LOGE("make_shared_array failed"); diff --git a/hapsigntool_cpp/hap/sign/src/sign_hap.cpp b/hapsigntool_cpp/hap/sign/src/sign_hap.cpp index 6392b68f..0c24b5b6 100644 --- a/hapsigntool_cpp/hap/sign/src/sign_hap.cpp +++ b/hapsigntool_cpp/hap/sign/src/sign_hap.cpp @@ -95,14 +95,10 @@ void SignHap::EncodeListOfPairsToByteArray(const DigestParameter& digestParam, const std::vector>&nidAndcontentDigests, ByteBuffer& result) { - int encodeSize = 0; - encodeSize += INT_SIZE + INT_SIZE; - for (const auto& pair : nidAndcontentDigests) { - encodeSize += INT_SIZE + INT_SIZE + INT_SIZE + pair.second.GetCapacity(); - } - encodeSize = std::accumulate(nidAndcontentDigests.begin(), nidAndcontentDigests.end(), encodeSize, - [](int sum, const std::pair& pair) { - return sum + INT_SIZE + INT_SIZE + pair.second.GetCapacity(); }); + int encodeSize = INT_SIZE * 2 + INT_SIZE * 3 * nidAndcontentDigests.size(); + encodeSize += std::accumulate(nidAndcontentDigests.begin(), nidAndcontentDigests.end(), 0, + [](int sum, const std::pair& pair) { + return sum + pair.second.GetCapacity(); }); result.SetCapacity(encodeSize); result.PutInt32(CONTENT_VERSION); // version result.PutInt32(BLOCK_NUMBER); // block number @@ -145,14 +141,11 @@ bool SignHap::GenerateHapSigningBlock(const std::string& hapSignatureSchemeBlock // uint64: size // uint128: magic // uint32: version - long optionalBlockSize = 0L; - optionalBlockSize = std::accumulate(optionalBlocks.begin(), optionalBlocks.end(), optionalBlockSize, - [](int64_t sum, const auto& elem) { + long optionalBlockSize = std::accumulate(optionalBlocks.begin(), optionalBlocks.end(), 0L, + [](int64_t sum, const auto& elem) { return sum + elem.optionalBlockValue.GetCapacity(); }); long resultSize = ((OPTIONAL_TYPE_SIZE + OPTIONAL_LENGTH_SIZE + OPTIONAL_OFFSET_SIZE) * - (optionalBlocks.size() + 1)) + - optionalBlockSize + - hapSignatureSchemeBlock.size() + + (optionalBlocks.size() + 1)) + optionalBlockSize + hapSignatureSchemeBlock.size() + BLOCK_COUNT + HapUtils::BLOCK_SIZE + BLOCK_MAGIC + BLOCK_VERSION; if (resultSize > INT_MAX) { SIGNATURE_TOOLS_LOGE("Illegal Argument. HapSigningBlock out of range: %ld", resultSize); diff --git a/hapsigntool_cpp/hap/verify/src/verify_hap.cpp b/hapsigntool_cpp/hap/verify/src/verify_hap.cpp index 9ff4dcd5..09c60202 100644 --- a/hapsigntool_cpp/hap/verify/src/verify_hap.cpp +++ b/hapsigntool_cpp/hap/verify/src/verify_hap.cpp @@ -128,9 +128,8 @@ bool VerifyHap::HapOutPutCertChain(std::vector& certs, const std::string& certStr.emplace_back(StringUtils::SubjectToString(cert)); certStr.emplace_back(StringUtils::x509CertToString(cert)); } - std::string outPutCertChainContent; - outPutCertChainContent = std::accumulate(certStr.begin(), certStr.end(), std::string(), - [](std::string sum, const std::string& certstr) { + std::string outPutCertChainContent = std::accumulate(certStr.begin(), certStr.end(), std::string(), + [](std::string sum, const std::string& certstr) { return sum + certstr; }); if (FileUtils::Write(outPutCertChainContent, outPutPath) < 0) { -- Gitee From 7842bc061e3c6ec06293337ac2f196e566dc58aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E6=97=8B=E9=A3=8Elc?= Date: Sat, 16 Nov 2024 17:18:11 +0800 Subject: [PATCH 3/7] modify Signed-off-by: liuchang --- hapsigntool_cpp/api/src/cert_tools.cpp | 317 ++++++++---------- .../utils/src/key_store_helper.cpp | 3 +- 2 files changed, 138 insertions(+), 182 deletions(-) diff --git a/hapsigntool_cpp/api/src/cert_tools.cpp b/hapsigntool_cpp/api/src/cert_tools.cpp index 383bde4d..16fb4e0d 100644 --- a/hapsigntool_cpp/api/src/cert_tools.cpp +++ b/hapsigntool_cpp/api/src/cert_tools.cpp @@ -134,13 +134,13 @@ bool CertTools::SetBisicConstraints(Options* options, X509* cert) X509V3_set_ctx_nodb(&ctx); X509_EXTENSION* ext = X509V3_EXT_conf_nid(NULL, &ctx, NID_basic_constraints, constraints.c_str()); - if (!X509_EXTENSION_set_critical(ext, critial)) { + if (X509_EXTENSION_set_critical(ext, critial) == 0) { SIGNATURE_TOOLS_LOGE("failed to set critical for extKeyUsage "); X509_EXTENSION_free(ext); VerifyHapOpensslUtils::GetOpensslErrorMessage(); return false; } - if (!X509_add_ext(cert, ext, -1)) { + if (X509_add_ext(cert, ext, -1) == 0) { SIGNATURE_TOOLS_LOGE("X509_add_ext failed"); X509_EXTENSION_free(ext); VerifyHapOpensslUtils::GetOpensslErrorMessage(); @@ -159,13 +159,13 @@ bool CertTools::SetBisicConstraintsPathLen(Options* options, X509* cert) X509V3_CTX ctx; X509V3_set_ctx_nodb(&ctx); X509_EXTENSION* ext = X509V3_EXT_conf_nid(NULL, &ctx, NID_basic_constraints, setOptions.c_str()); - if (!X509_EXTENSION_set_critical(ext, 1)) { + if (X509_EXTENSION_set_critical(ext, 1) == 0) { SIGNATURE_TOOLS_LOGE("failed to set critical for extKeyUsage "); X509_EXTENSION_free(ext); VerifyHapOpensslUtils::GetOpensslErrorMessage(); return false; } - if (!X509_add_ext(cert, ext, -1)) { + if (X509_add_ext(cert, ext, -1) == 0) { SIGNATURE_TOOLS_LOGE("X509_add_ext failed\n"); X509_EXTENSION_free(ext); VerifyHapOpensslUtils::GetOpensslErrorMessage(); @@ -179,11 +179,9 @@ bool CertTools::SignForSubCert(X509* cert, X509_REQ* subcsr, X509_REQ* rootcsr, { if (caPrikey == nullptr || rootcsr == nullptr || subcsr == nullptr) { SIGNATURE_TOOLS_LOGE("Sign failed because of caPrikey, roocsr or subcsr is nullptr"); - VerifyHapOpensslUtils::GetOpensslErrorMessage(); return false; } - bool result = false; std::string signAlg = options->GetString(Options::SIGN_ALG); EVP_PKEY* pubKey = X509_REQ_get_pubkey(subcsr); if (pubKey == nullptr) { @@ -194,35 +192,28 @@ bool CertTools::SignForSubCert(X509* cert, X509_REQ* subcsr, X509_REQ* rootcsr, X509_NAME* issuerName = X509_REQ_get_subject_name(rootcsr); X509_NAME* subjectName = X509_REQ_get_subject_name(subcsr); do { - result = (!X509_set_pubkey(cert, pubKey)); - if (result) { + if (X509_set_pubkey(cert, pubKey) == 0) { SIGNATURE_TOOLS_LOGE("X509_set_pubkey failed"); break; } - result = (!X509_set_issuer_name(cert, issuerName)); - if (result) { + if (X509_set_issuer_name(cert, issuerName) == 0) { SIGNATURE_TOOLS_LOGE("X509_set_issuer_name failed"); break; } - result = (!X509_set_subject_name(cert, subjectName)); - if (result) { + if (X509_set_subject_name(cert, subjectName) == 0) { SIGNATURE_TOOLS_LOGE("X509_set_subject_name failed"); break; } - result = (!SignCert(cert, caPrikey, signAlg)); - if (result) { + if (!SignCert(cert, caPrikey, signAlg)) { break; } + EVP_PKEY_free(pubKey); + return true; } while (0); EVP_PKEY_free(pubKey); - if (result) { - X509_NAME_free(issuerName); - X509_NAME_free(subjectName); - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - return false; - } - return true; + VerifyHapOpensslUtils::GetOpensslErrorMessage(); + return false; } X509* CertTools::SignCsrGenerateCert(X509_REQ* rootcsr, X509_REQ* subcsr, @@ -233,44 +224,41 @@ X509* CertTools::SignCsrGenerateCert(X509_REQ* rootcsr, X509_REQ* subcsr, SIGNATURE_TOOLS_LOGE("failed to create X509 cert"); return nullptr; } - bool result = false; + do { int validity = options->GetInt(Options::VALIDITY); - result = (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || - !SetCertSerialNum(cert)); - if (result) { + if (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || + !SetCertSerialNum(cert)) { + SIGNATURE_TOOLS_LOGE("failed to generate X509 cert cause of set version or serial num failed"); break; } - result = (!SetCertValidity(cert, validity)); - if (result) { + if (!SetCertValidity(cert, validity)) { + SIGNATURE_TOOLS_LOGE("failed to generate X509 cert cause of set validity failed"); break; } - result = (!SetBisicConstraintsPathLen(options, cert) || - !SetKeyIdentifierExt(cert) || - !SetAuthorizeKeyIdentifierExt(cert) || - !SetKeyUsage(cert, options) || - !SignForSubCert(cert, subcsr, rootcsr, keyPair, options)); - if (result) { + if (!SetBisicConstraintsPathLen(options, cert) || + !SetKeyIdentifierExt(cert) || + !SetAuthorizeKeyIdentifierExt(cert) || + !SetKeyUsage(cert, options) || + !SignForSubCert(cert, subcsr, rootcsr, keyPair, options)) { + SIGNATURE_TOOLS_LOGE("failed to generate X509 cert cause of other reasons"); break; } + return cert; } while (0); - if (result) { - SIGNATURE_TOOLS_LOGE("failed to generate X509 cert by csr"); - X509_free(cert); - return nullptr; - } - return cert; + X509_free(cert); + return nullptr; } bool CertTools::SetSubjectForCert(X509_REQ* certReq, X509* cert) { - bool result = false; + if (certReq == nullptr) { + SIGNATURE_TOOLS_LOGE("set subjcet failed because certReq is nullptr"); + return false; + } + do { - if (certReq == nullptr) { - SIGNATURE_TOOLS_LOGE("set subjcet failed because of certReq is nullptr"); - break; - } if (X509_set_subject_name(cert, X509_REQ_get_subject_name(certReq)) != 1) { SIGNATURE_TOOLS_LOGE("X509_set_issuer_name failed"); break; @@ -279,19 +267,15 @@ bool CertTools::SetSubjectForCert(X509_REQ* certReq, X509* cert) SIGNATURE_TOOLS_LOGE("X509_set_issuer_name failed"); break; } - result = true; + return true; } while (0); - if (!result) { - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - } - return result; + VerifyHapOpensslUtils::GetOpensslErrorMessage(); + return false; } - X509* CertTools::GenerateRootCertificate(EVP_PKEY* keyPair, X509_REQ* certReq, Options* options) { - bool result = false; X509* cert = X509_new(); if (cert == nullptr) { SIGNATURE_TOOLS_LOGE("failed to create X509 cert"); @@ -300,35 +284,31 @@ X509* CertTools::GenerateRootCertificate(EVP_PKEY* keyPair, X509_REQ* certReq, O do { int validity = options->GetInt(Options::VALIDITY); std::string signAlg = options->GetString(Options::SIGN_ALG); - result = (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || - !SetCertSerialNum(cert)); - if (result) { + if (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || !SetCertSerialNum(cert)) { + SIGNATURE_TOOLS_LOGE("failed to generate X509 cert cause of set version or serial num failed"); break; } - result = (!SetCertValidityStartAndEnd(cert, DEFAULT_START_VALIDITY, validity)); - if (result) { + if (!SetCertValidityStartAndEnd(cert, DEFAULT_START_VALIDITY, validity)) { + SIGNATURE_TOOLS_LOGE("failed to generate X509 cert cause of set validity failed"); break; } - result = (!SetBisicConstraintsPathLen(options, cert) || - !SetSubjectForCert(certReq, cert) || - !SetCertPublickKey(cert, certReq) || - !SetKeyIdentifierExt(cert) || - !SetKeyUsage(cert, options)); - if (result) { + if (!SetBisicConstraintsPathLen(options, cert) || + !SetSubjectForCert(certReq, cert) || + !SetCertPublickKey(cert, certReq) || + !SetKeyIdentifierExt(cert) || + !SetKeyUsage(cert, options)) { + SIGNATURE_TOOLS_LOGE("failed to generate X509 cert cause of other reasons"); break; } - result = (!SignCert(cert, keyPair, signAlg)); - if (result) { + if (!SignCert(cert, keyPair, signAlg)) { + SIGNATURE_TOOLS_LOGE("failed to generate X509 cert cause of sign failed"); break; } + return cert; } while (0); - if (result) { - SIGNATURE_TOOLS_LOGE("failed to generate root cert"); - X509_free(cert); - return nullptr; - } - return cert; + X509_free(cert); + return nullptr; } X509* CertTools::GenerateSubCert(EVP_PKEY* keyPair, X509_REQ* rootcsr, Options* options) @@ -338,12 +318,12 @@ X509* CertTools::GenerateSubCert(EVP_PKEY* keyPair, X509_REQ* rootcsr, Options* X509_REQ* subcsr = nullptr; X509* subCert = nullptr; subKey = adapter->GetAliasKey(false); - bool result = false; + if (subKey == nullptr) { + SIGNATURE_TOOLS_LOGE("failed to get the keypair"); + return nullptr; + } + do { - if (subKey == nullptr) { - SIGNATURE_TOOLS_LOGE("failed to get the keypair"); - break; - } subcsr = CertTools::GenerateCsr(subKey, options->GetString(Options::SIGN_ALG), options->GetString(Options::SUBJECT)); if (subcsr == nullptr) { @@ -355,16 +335,14 @@ X509* CertTools::GenerateSubCert(EVP_PKEY* keyPair, X509_REQ* rootcsr, Options* SIGNATURE_TOOLS_LOGE("failed to generate the subCert"); break; } - result = true; + EVP_PKEY_free(subKey); + X509_REQ_free(subcsr); + return subCert; } while (0); EVP_PKEY_free(subKey); X509_REQ_free(subcsr); - - if (!result) { - return nullptr; - } - return subCert; + return nullptr; } bool CertTools::SetKeyUsage(X509* cert, Options* options) @@ -374,12 +352,12 @@ bool CertTools::SetKeyUsage(X509* cert, Options* options) long key = 0; if (keyUsage.empty()) { key = X509v3_KU_KEY_CERT_SIGN | X509v3_KU_CRL_SIGN; - if (keyUsageInt == NULL || !ASN1_INTEGER_set(keyUsageInt, key)) { + if (keyUsageInt == NULL || ASN1_INTEGER_set(keyUsageInt, key) == 0) { SIGNATURE_TOOLS_LOGE("failed to set asn1_integer"); ASN1_INTEGER_free(keyUsageInt); return false; } - if (!X509_add1_ext_i2d(cert, NID_key_usage, keyUsageInt, 0, X509V3_ADD_DEFAULT)) { + if (X509_add1_ext_i2d(cert, NID_key_usage, keyUsageInt, 0, X509V3_ADD_DEFAULT) == 0) { SIGNATURE_TOOLS_LOGE("failed to add ext"); ASN1_INTEGER_free(keyUsageInt); return false; @@ -390,12 +368,12 @@ bool CertTools::SetKeyUsage(X509* cert, Options* options) std::vector vecs = StringUtils::SplitString(keyUsage.c_str(), ','); key = std::accumulate(vecs.begin(), vecs.end(), key, [&](long key, const std::string& vec) { return key | externDic[vec]; }); - if (keyUsageInt == NULL || !ASN1_INTEGER_set(keyUsageInt, key)) { + if (keyUsageInt == NULL || ASN1_INTEGER_set(keyUsageInt, key) == 0) { SIGNATURE_TOOLS_LOGE("failed to set asn1_integer"); ASN1_INTEGER_free(keyUsageInt); return false; } - if (!X509_add1_ext_i2d(cert, NID_key_usage, keyUsageInt, crit, X509V3_ADD_DEFAULT)) { + if (X509_add1_ext_i2d(cert, NID_key_usage, keyUsageInt, crit, X509V3_ADD_DEFAULT) == 0) { SIGNATURE_TOOLS_LOGE("failed to add ext"); ASN1_INTEGER_free(keyUsageInt); return false; @@ -413,12 +391,12 @@ bool CertTools::SetkeyUsageExt(X509* cert, Options* options) if (!options->GetString(Options::EXT_KEY_USAGE).empty()) { ext = X509V3_EXT_conf(NULL, NULL, NID_EXT_KEYUSAGE_CONST.c_str(), externKey[options->GetString(Options::EXT_KEY_USAGE)].c_str()); - if (!X509_EXTENSION_set_critical(ext, crit)) { + if (X509_EXTENSION_set_critical(ext, crit) == 0) { SIGNATURE_TOOLS_LOGE("failed to set critical for extKeyUsage "); X509_EXTENSION_free(ext); return false; } - if (!X509_add_ext(cert, ext, -1)) { + if (X509_add_ext(cert, ext, -1) == 0) { SIGNATURE_TOOLS_LOGE("failed to add extension"); X509_EXTENSION_free(ext); return false; @@ -430,10 +408,8 @@ bool CertTools::SetkeyUsageExt(X509* cert, Options* options) bool CertTools::SetExpandedInformation(X509* cert, Options* options) { - bool result = false; - result = (!SetKeyUsage(cert, options) || - !SetkeyUsageExt(cert, options)); - if (result) { + if (!SetKeyUsage(cert, options) || + !SetkeyUsageExt(cert, options)) { SIGNATURE_TOOLS_LOGE("Failed to set expanded information "); return false; } @@ -443,35 +419,31 @@ bool CertTools::SetExpandedInformation(X509* cert, Options* options) bool CertTools::SetPubkeyAndSignCert(X509* cert, X509_REQ* issuercsr, X509_REQ* certReq, EVP_PKEY* keyPair, Options* options) { - bool result = false; do { - if (!X509_set_issuer_name(cert, X509_REQ_get_subject_name(issuercsr))) { + if (X509_set_issuer_name(cert, X509_REQ_get_subject_name(issuercsr)) == 0) { SIGNATURE_TOOLS_LOGE("X509_set_issuer_name failed"); break; } - if (!X509_set_subject_name(cert, X509_REQ_get_subject_name(certReq))) { + if (X509_set_subject_name(cert, X509_REQ_get_subject_name(certReq)) == 0) { SIGNATURE_TOOLS_LOGE("X509_set_subject_name failed"); break; } if ((options->GetString(Options::SIGN_ALG)) == SIGN_ALG_SHA256) { - if (!X509_sign(cert, keyPair, EVP_sha256())) { + if (X509_sign(cert, keyPair, EVP_sha256()) == 0) { SIGNATURE_TOOLS_LOGE("X509_sign failed"); break; } } else { - if (!X509_sign(cert, keyPair, EVP_sha384())) { + if (X509_sign(cert, keyPair, EVP_sha384()) == 0) { SIGNATURE_TOOLS_LOGE("X509_sign failed"); break; } } - result = true; + return true; } while (0); - if (!result) { - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - return false; - } - return true; + VerifyHapOpensslUtils::GetOpensslErrorMessage(); + return false; } X509* CertTools::GenerateCert(EVP_PKEY* keyPair, X509_REQ* certReq, Options* options) @@ -488,35 +460,32 @@ X509* CertTools::GenerateCert(EVP_PKEY* keyPair, X509_REQ* certReq, Options* opt SIGNATURE_TOOLS_LOGE("failed to create X509 cert"); return nullptr; } - bool result = false; do { - result = (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || - !SetCertSerialNum(cert) || - !SetKeyIdentifierExt(cert)); - if (result) { + if (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || + !SetCertSerialNum(cert) || + !SetKeyIdentifierExt(cert)) { + SIGNATURE_TOOLS_LOGE("failed to set cert version, serial number or key identifier"); break; } int validity = options->GetInt(Options::VALIDITY); - result = (!SetCertValidityStartAndEnd(cert, DEFAULT_START_VALIDITY, validity)); - if (result) { + if (!SetCertValidityStartAndEnd(cert, DEFAULT_START_VALIDITY, validity)) { + SIGNATURE_TOOLS_LOGE("failed to set cert validity"); break; } - result = (!SetBisicConstraints(options, cert) || - !SetCertPublickKey(cert, certReq) || - !SetExpandedInformation(cert, options) || - !SetPubkeyAndSignCert(cert, issuercsr, certReq, keyPair, options)); - if (result) { + if (!SetBisicConstraints(options, cert) || + !SetCertPublickKey(cert, certReq) || + !SetExpandedInformation(cert, options) || + !SetPubkeyAndSignCert(cert, issuercsr, certReq, keyPair, options)) { + SIGNATURE_TOOLS_LOGE("failed to generate cert cause of other reasons"); break; } + X509_REQ_free(issuercsr); + return cert; } while (0); X509_REQ_free(issuercsr); - if (result) { - SIGNATURE_TOOLS_LOGE("failed to generate cert"); - X509_free(cert); - return nullptr; - } - return cert; + X509_free(cert); + return nullptr; } X509_REQ* CertTools::GenerateCsr(EVP_PKEY* evpPkey, std::string signAlgorithm, std::string subject) @@ -527,9 +496,8 @@ X509_REQ* CertTools::GenerateCsr(EVP_PKEY* evpPkey, std::string signAlgorithm, s SIGNATURE_TOOLS_LOGE("X509_REQ_new failed"); return nullptr; } - bool result = false; do { - if (!X509_REQ_set_pubkey(req, evpPkey)) { + if (X509_REQ_set_pubkey(req, evpPkey) == 0) { SIGNATURE_TOOLS_LOGE("X509_REQ_set_pubkey failed"); break; } @@ -541,12 +509,12 @@ X509_REQ* CertTools::GenerateCsr(EVP_PKEY* evpPkey, std::string signAlgorithm, s } if (signAlgorithm == SIGN_ALG_SHA256) { - if (!X509_REQ_sign(req, evpPkey, EVP_sha256())) { + if (X509_REQ_sign(req, evpPkey, EVP_sha256()) == 0) { SIGNATURE_TOOLS_LOGE("X509_REQ_sign failed"); break; } } else if (signAlgorithm == SIGN_ALG_SHA384) { - if (!X509_REQ_sign(req, evpPkey, EVP_sha384())) { + if (X509_REQ_sign(req, evpPkey, EVP_sha384()) == 0) { SIGNATURE_TOOLS_LOGE("X509_REQ_sign failed"); break; } @@ -555,15 +523,12 @@ X509_REQ* CertTools::GenerateCsr(EVP_PKEY* evpPkey, std::string signAlgorithm, s "Sign algorithm format error! Please check again."); break; } - result = true; + return req; } while (0); - if (!result) { - VerifyHapOpensslUtils::GetOpensslErrorMessage(); - X509_REQ_free(req); - return nullptr; - } - return req; + VerifyHapOpensslUtils::GetOpensslErrorMessage(); + X509_REQ_free(req); + return nullptr; } std::string CertTools::CsrToString(X509_REQ* csr) @@ -624,7 +589,7 @@ X509* CertTools::ReadfileToX509(const std::string& filename) bool CertTools::SetCertVersion(X509* cert, int versionNum) { - if (!X509_set_version(cert, versionNum)) { + if (X509_set_version(cert, versionNum) == 0) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("set x509 cert version failed"); return false; @@ -634,9 +599,8 @@ bool CertTools::SetCertVersion(X509* cert, int versionNum) bool CertTools::SetCertSerialNum(X509* cert) { - BN_CTX* ctx = BN_CTX_new(); BIGNUM* bignum = BN_new(); - bool result = false; + do { uint8_t serialNumberValue[RANDOM_SERIAL_NUMBER_LENGTH] = {0}; if (!SerialNumberBuilder(serialNumberValue, sizeof(serialNumberValue))) { @@ -653,21 +617,18 @@ bool CertTools::SetCertSerialNum(X509* cert) VerifyHapOpensslUtils::GetOpensslErrorMessage(); break; } - result = true; + BN_free(bignum); + return true; } while (0); - - BN_CTX_free(ctx); + + SIGNATURE_TOOLS_LOGE("set x509 cert serial number failed"); BN_free(bignum); - if (!result) { - SIGNATURE_TOOLS_LOGE("set x509 cert serial number failed"); - return false; - } - return true; + return false; } bool CertTools::SetCertIssuerName(X509* cert, X509_NAME* issuer) { - if (!X509_set_issuer_name(cert, issuer)) { + if (X509_set_issuer_name(cert, issuer) == 0) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("set x509 cert issuer name failed"); return false; @@ -683,7 +644,7 @@ bool CertTools::SetCertSubjectName(X509* cert, X509_REQ* subjectCsr) SIGNATURE_TOOLS_LOGE("get X509 cert subject name failed"); return false; } - if (!X509_set_subject_name(cert, subject)) { + if (X509_set_subject_name(cert, subject) == 0) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("set X509 cert subject name failed"); return false; @@ -693,12 +654,12 @@ bool CertTools::SetCertSubjectName(X509* cert, X509_REQ* subjectCsr) bool CertTools::SetCertValidityStartAndEnd(X509* cert, long vilidityStart, long vilidityEnd) { - if (!X509_gmtime_adj(X509_getm_notBefore(cert), vilidityStart)) { + if (X509_gmtime_adj(X509_getm_notBefore(cert), vilidityStart) == 0) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("set cert vilidity start time failed"); return false; } - if (!X509_gmtime_adj(X509_getm_notAfter(cert), vilidityEnd)) { + if (X509_gmtime_adj(X509_getm_notAfter(cert), vilidityEnd) == 0) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("set cert vilidity end time failed"); return false; @@ -709,12 +670,12 @@ bool CertTools::SetCertValidityStartAndEnd(X509* cert, long vilidityStart, long bool CertTools::SetCertPublickKey(X509* cert, X509_REQ* subjectCsr) { EVP_PKEY* publicKey = X509_REQ_get_pubkey(subjectCsr); - if (!publicKey) { + if (publicKey == nullptr) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("get the pubkey from csr failed"); return false; } - if (!X509_set_pubkey(cert, publicKey)) { + if (X509_set_pubkey(cert, publicKey) == 0) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); EVP_PKEY_free(publicKey); SIGNATURE_TOOLS_LOGE("set public key to cert failed"); @@ -728,7 +689,7 @@ bool CertTools::SetBasicExt(X509* cert) { X509_EXTENSION* basicExtension = X509V3_EXT_conf(NULL, NULL, NID_BASIC_CONST.c_str(), DEFAULT_BASIC_EXTENSION.c_str()); - if (!X509_add_ext(cert, basicExtension, -1)) { + if (X509_add_ext(cert, basicExtension, -1) == 0) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("set basicExtension information failed"); X509_EXTENSION_free(basicExtension); @@ -742,7 +703,7 @@ bool CertTools::SetkeyUsageExt(X509* cert) { X509_EXTENSION* keyUsageExtension = X509V3_EXT_conf(NULL, NULL, NID_KEYUSAGE_CONST.c_str(), DEFAULT_KEYUSAGE_EXTENSION.c_str()); - if (!X509_add_ext(cert, keyUsageExtension, -1)) { + if (X509_add_ext(cert, keyUsageExtension, -1) == 0) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("set keyUsageExtension information failed"); X509_EXTENSION_free(keyUsageExtension); @@ -756,7 +717,7 @@ bool CertTools::SetKeyUsageEndExt(X509* cert) { X509_EXTENSION* keyUsageEndExtension = X509V3_EXT_conf(NULL, NULL, NID_EXT_KEYUSAGE_CONST.c_str(), DEFAULT_EXTEND_KEYUSAGE.c_str()); - if (!X509_add_ext(cert, keyUsageEndExtension, -1)) { + if (X509_add_ext(cert, keyUsageEndExtension, -1) == 0) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("set keyUsageEndExtension information failed"); X509_EXTENSION_free(keyUsageEndExtension); @@ -776,7 +737,7 @@ bool CertTools::SetKeyIdentifierExt(X509* cert) return false; } ASN1_OCTET_STRING* pubKeyDigestData = ASN1_OCTET_STRING_new(); - if (!ASN1_OCTET_STRING_set(pubKeyDigestData, digest, digestLen)) { + if (ASN1_OCTET_STRING_set(pubKeyDigestData, digest, digestLen) == 0) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("set ANS1 pubKeyDigestData failed"); ASN1_OCTET_STRING_free(pubKeyDigestData); @@ -787,7 +748,7 @@ bool CertTools::SetKeyIdentifierExt(X509* cert) /* function OBJ_nid2obj(NID_subject_key_identifier) return value is a global variable, so should not free it */ subKeyIdentifierExtension = X509_EXTENSION_create_by_OBJ(NULL, OBJ_nid2obj(NID_subject_key_identifier), 0, pubKeyDigestData); - if (!X509_add_ext(cert, subKeyIdentifierExtension, -1)) { + if (X509_add_ext(cert, subKeyIdentifierExtension, -1) == 0) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("set subKeyIdentifierExtension information failed"); ASN1_OCTET_STRING_free(pubKeyDigestData); @@ -808,14 +769,14 @@ bool CertTools::SetAuthorizeKeyIdentifierExt(X509* cert) X509_EXTENSION* ext = nullptr; AUTHORITY_KEYID* akid = AUTHORITY_KEYID_new(); akid->keyid = ASN1_OCTET_STRING_new(); - if (!ASN1_OCTET_STRING_set(akid->keyid, key_id, key_id_len)) { + if (ASN1_OCTET_STRING_set(akid->keyid, key_id, key_id_len) == 0) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("set ANS1 pubKeyDigestData failed"); AUTHORITY_KEYID_free(akid); return false; } ext = X509V3_EXT_i2d(NID_authority_key_identifier, 1, akid); - if (!X509_add_ext(cert, ext, -1)) { + if (X509_add_ext(cert, ext, -1) == 0) { SIGNATURE_TOOLS_LOGE("Failed to add AKI extension to certificate"); X509_EXTENSION_free(ext); AUTHORITY_KEYID_free(akid); @@ -830,7 +791,8 @@ bool CertTools::SetAuthorizeKeyIdentifierExt(X509* cert) bool CertTools::SetSignCapacityExt(X509* cert, const char signCapacity[], int capacityLen) { ASN1_OCTET_STRING* certSignCapacityData = ASN1_OCTET_STRING_new(); - if (!ASN1_OCTET_STRING_set(certSignCapacityData, reinterpret_cast(signCapacity), capacityLen)) { + if (ASN1_OCTET_STRING_set(certSignCapacityData, + reinterpret_cast(signCapacity), capacityLen) == 0) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("failed to set pubkey digst into ASN1 object"); ASN1_OCTET_STRING_free(certSignCapacityData); @@ -840,7 +802,7 @@ bool CertTools::SetSignCapacityExt(X509* cert, const char signCapacity[], int ca ASN1_OBJECT* nid = OBJ_txt2obj(X509_EXT_OID.c_str(), 1); X509_EXTENSION* certSignCapacityExt = X509_EXTENSION_create_by_OBJ(NULL, nid, 0, certSignCapacityData); - if (!X509_add_ext(cert, certSignCapacityExt, -1)) { + if (X509_add_ext(cert, certSignCapacityExt, -1) == 0) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("set certSignCapacityExt information failed"); ASN1_OBJECT_free(nid); @@ -864,7 +826,7 @@ bool CertTools::SignCert(X509* cert, EVP_PKEY* privateKey, std::string signAlg) if (signAlg == SIGN_ALG_SHA384) { alg = EVP_sha384(); } - if (!X509_sign(cert, privateKey, alg)) { + if (X509_sign(cert, privateKey, alg) == 0) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("sign X509 cert failed"); return false; @@ -889,8 +851,7 @@ bool CertTools::SerialNumberBuilder(uint8_t* serialNum, int length) return true; } -X509* CertTools::GenerateEndCert(X509_REQ* csr, EVP_PKEY* issuerKeyPair, - LocalizationAdapter& adapter, +X509* CertTools::GenerateEndCert(X509_REQ* csr, EVP_PKEY* issuerKeyPair, LocalizationAdapter& adapter, const char signCapacity[], int capacityLen) { X509* cert = X509_new(); // in this function, should not release X509cert memory @@ -904,45 +865,41 @@ X509* CertTools::GenerateEndCert(X509_REQ* csr, EVP_PKEY* issuerKeyPair, adapter.AppAndProfileAssetsRealse({}, {}, {cert}); return nullptr; } - bool result = false; do { std::string issuerStr = adapter.options->GetString(adapter.options->ISSUER); int validity = adapter.options->GetInt(adapter.options->VALIDITY); std::string signAlg = adapter.options->GetString(adapter.options->SIGN_ALG); - result = (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || !SetCertSerialNum(cert)); - if (result) { + if (!SetCertVersion(cert, DEFAULT_CERT_VERSION) || !SetCertSerialNum(cert)) { + SIGNATURE_TOOLS_LOGE("failed to set cert version or serial number"); break; } - result = (!SetCertIssuerName(cert, BuildDN(issuerStr, issuerReq)) || !SetCertSubjectName(cert, csr)); - if (result) { + if (!SetCertIssuerName(cert, BuildDN(issuerStr, issuerReq)) || !SetCertSubjectName(cert, csr)) { + SIGNATURE_TOOLS_LOGE("failed to set cert issuer or subject name"); break; } - result = (!SetCertValidity(cert, validity) || !SetCertPublickKey(cert, csr)); - if (result) { + if (!SetCertValidity(cert, validity) || !SetCertPublickKey(cert, csr)) { + SIGNATURE_TOOLS_LOGE("failed to set cert validity or public key"); break; } - result = (!SetBasicExt(cert) || !SetkeyUsageExt(cert) || !SetKeyUsageEndExt(cert)); - if (result) { + if (!SetBasicExt(cert) || !SetkeyUsageExt(cert) || !SetKeyUsageEndExt(cert)) { + SIGNATURE_TOOLS_LOGE("failed to set basic ext or key usage ext"); break; } - result = (!SetKeyIdentifierExt(cert) || !SetSignCapacityExt(cert, signCapacity, capacityLen)); - if (result) { + if (!SetKeyIdentifierExt(cert) || !SetSignCapacityExt(cert, signCapacity, capacityLen)) { + SIGNATURE_TOOLS_LOGE("failed to set key identifier ext or sign capacity ext"); break; } - result = (!SignCert(cert, issuerKeyPair, signAlg)); - if (result) { + if (!SignCert(cert, issuerKeyPair, signAlg)) { + SIGNATURE_TOOLS_LOGE("failed to sign cert"); break; } + adapter.AppAndProfileAssetsRealse({}, {issuerReq}, {}); + return cert; // return x509 assets } while (0); - if (result) { - SIGNATURE_TOOLS_LOGE("failed to generate end cert"); - adapter.AppAndProfileAssetsRealse({}, {issuerReq}, {cert}); - return nullptr; - } - adapter.AppAndProfileAssetsRealse({}, {issuerReq}, {}); - return cert; // return x509 assets + adapter.AppAndProfileAssetsRealse({}, {issuerReq}, {cert}); + return nullptr; } } // namespace SignatureTools diff --git a/hapsigntool_cpp/utils/src/key_store_helper.cpp b/hapsigntool_cpp/utils/src/key_store_helper.cpp index c1a723ea..4a988cfe 100644 --- a/hapsigntool_cpp/utils/src/key_store_helper.cpp +++ b/hapsigntool_cpp/utils/src/key_store_helper.cpp @@ -747,8 +747,7 @@ err: bool KeyStoreHelper::SetX509Alias(int len, X509* x509, unsigned char* data) { if (len >= 0) { - int r; - r = X509_alias_set1(x509, data, len); + int r = X509_alias_set1(x509, data, len); OPENSSL_free(data); if (!r) { X509_free(x509); -- Gitee From f2236929ea5be5e34e66a536f918f13514949adb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E6=97=8B=E9=A3=8Elc?= Date: Mon, 18 Nov 2024 11:29:01 +0800 Subject: [PATCH 4/7] modify format issues Signed-off-by: liuchang --- hapsigntool_cpp/api/src/cert_tools.cpp | 26 +++++++++---------- hapsigntool_cpp/cmd/src/params_trust_list.cpp | 2 +- .../src/code_sign_block_header.cpp | 14 ++++------ .../codesigning/sign/src/code_signing.cpp | 5 ++-- hapsigntool_cpp/hap/sign/src/sign_hap.cpp | 6 ++--- hapsigntool_cpp/hap/verify/src/verify_hap.cpp | 4 +-- .../utils/src/hap_signer_block_utils.cpp | 23 ++++------------ .../utils/src/key_store_helper.cpp | 17 ++++-------- hapsigntool_cpp/utils/src/string_utils.cpp | 4 +-- .../zip/src/random_access_file_input.cpp | 2 +- 10 files changed, 36 insertions(+), 67 deletions(-) diff --git a/hapsigntool_cpp/api/src/cert_tools.cpp b/hapsigntool_cpp/api/src/cert_tools.cpp index 16fb4e0d..e6f6186d 100644 --- a/hapsigntool_cpp/api/src/cert_tools.cpp +++ b/hapsigntool_cpp/api/src/cert_tools.cpp @@ -236,14 +236,14 @@ X509* CertTools::SignCsrGenerateCert(X509_REQ* rootcsr, X509_REQ* subcsr, SIGNATURE_TOOLS_LOGE("failed to generate X509 cert cause of set validity failed"); break; } - if (!SetBisicConstraintsPathLen(options, cert) || - !SetKeyIdentifierExt(cert) || - !SetAuthorizeKeyIdentifierExt(cert) || - !SetKeyUsage(cert, options) || + if (!SetBisicConstraintsPathLen(options, cert) || + !SetKeyIdentifierExt(cert) || + !SetAuthorizeKeyIdentifierExt(cert) || + !SetKeyUsage(cert, options) || !SignForSubCert(cert, subcsr, rootcsr, keyPair, options)) { SIGNATURE_TOOLS_LOGE("failed to generate X509 cert cause of other reasons"); break; - } + } return cert; } while (0); @@ -292,9 +292,9 @@ X509* CertTools::GenerateRootCertificate(EVP_PKEY* keyPair, X509_REQ* certReq, O SIGNATURE_TOOLS_LOGE("failed to generate X509 cert cause of set validity failed"); break; } - if (!SetBisicConstraintsPathLen(options, cert) || + if (!SetBisicConstraintsPathLen(options, cert) || !SetSubjectForCert(certReq, cert) || - !SetCertPublickKey(cert, certReq) || + !SetCertPublickKey(cert, certReq) || !SetKeyIdentifierExt(cert) || !SetKeyUsage(cert, options)) { SIGNATURE_TOOLS_LOGE("failed to generate X509 cert cause of other reasons"); @@ -366,8 +366,8 @@ bool CertTools::SetKeyUsage(X509* cert, Options* options) bool keyUsageCritical = options->GetBool(Options::KEY_USAGE_CRITICAL); int crit = keyUsageCritical > 0 ? 1 : 0; std::vector vecs = StringUtils::SplitString(keyUsage.c_str(), ','); - key = std::accumulate(vecs.begin(), vecs.end(), key, [&](long key, const std::string& vec) { - return key | externDic[vec]; }); + key = std::accumulate(vecs.begin(), vecs.end(), key, + [&](long key, const std::string& vec) { return key | externDic[vec]; }); if (keyUsageInt == NULL || ASN1_INTEGER_set(keyUsageInt, key) == 0) { SIGNATURE_TOOLS_LOGE("failed to set asn1_integer"); ASN1_INTEGER_free(keyUsageInt); @@ -478,14 +478,14 @@ X509* CertTools::GenerateCert(EVP_PKEY* keyPair, X509_REQ* certReq, Options* opt !SetPubkeyAndSignCert(cert, issuercsr, certReq, keyPair, options)) { SIGNATURE_TOOLS_LOGE("failed to generate cert cause of other reasons"); break; - } + } X509_REQ_free(issuercsr); return cert; } while (0); X509_REQ_free(issuercsr); X509_free(cert); - return nullptr; + return nullptr; } X509_REQ* CertTools::GenerateCsr(EVP_PKEY* evpPkey, std::string signAlgorithm, std::string subject) @@ -528,7 +528,7 @@ X509_REQ* CertTools::GenerateCsr(EVP_PKEY* evpPkey, std::string signAlgorithm, s VerifyHapOpensslUtils::GetOpensslErrorMessage(); X509_REQ_free(req); - return nullptr; + return nullptr; } std::string CertTools::CsrToString(X509_REQ* csr) @@ -791,7 +791,7 @@ bool CertTools::SetAuthorizeKeyIdentifierExt(X509* cert) bool CertTools::SetSignCapacityExt(X509* cert, const char signCapacity[], int capacityLen) { ASN1_OCTET_STRING* certSignCapacityData = ASN1_OCTET_STRING_new(); - if (ASN1_OCTET_STRING_set(certSignCapacityData, + if (ASN1_OCTET_STRING_set(certSignCapacityData, reinterpret_cast(signCapacity), capacityLen) == 0) { VerifyHapOpensslUtils::GetOpensslErrorMessage(); SIGNATURE_TOOLS_LOGE("failed to set pubkey digst into ASN1 object"); diff --git a/hapsigntool_cpp/cmd/src/params_trust_list.cpp b/hapsigntool_cpp/cmd/src/params_trust_list.cpp index 1e830b08..d6c45dc8 100644 --- a/hapsigntool_cpp/cmd/src/params_trust_list.cpp +++ b/hapsigntool_cpp/cmd/src/params_trust_list.cpp @@ -70,7 +70,7 @@ void ParamsTrustList::ReadHelpParam(std::istringstream& fd) if (params.empty()) { continue; } - isExists = std::any_of(commands.begin(), commands.end(), + isExists = std::any_of(commands.begin(), commands.end(), [params](const std::string& cmd) {return cmd == params; }); if (isExists) { cmdStandBy = params; 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 d7809d40..6f58587d 100644 --- a/hapsigntool_cpp/codesigning/datastructure/src/code_sign_block_header.cpp +++ b/hapsigntool_cpp/codesigning/datastructure/src/code_sign_block_header.cpp @@ -78,16 +78,14 @@ void CodeSignBlockHeader::ToByteArray(std::vector& ret) CodeSignBlockHeader* CodeSignBlockHeader::FromByteArray(const std::vector& bytes) { if (bytes.size() != Size()) { - PrintErrorNumberMsg("VERIFY_ERROR", VERIFY_ERROR, - "The size of code signature block is incorrect."); + PrintErrorNumberMsg("VERIFY_ERROR", VERIFY_ERROR, "The size of code signature block is incorrect."); return nullptr; } ByteBuffer bf(bytes.size()); bf.PutData(reinterpret_cast(bytes.data()), bytes.size()); bf.Flip(); int64_t inMagic; - bool flag = bf.GetInt64(inMagic); - if (!flag || inMagic != MAGIC_NUM) { + if (!bf.GetInt64(inMagic) || inMagic != MAGIC_NUM) { PrintErrorNumberMsg("VERIFY_ERROR", VERIFY_ERROR, "The magic number in the code signature block header is incorrect."); return nullptr; @@ -111,16 +109,14 @@ CodeSignBlockHeader* CodeSignBlockHeader::FromByteArray(const std::vector(FLAG_MERKLE_TREE_INLINED + FLAG_NATIVE_LIB_INCLUDED)) { - PrintErrorNumberMsg("VERIFY_ERROR", VERIFY_ERROR, - "The flag in the code signature block header is incorrect."); + PrintErrorNumberMsg("VERIFY_ERROR", VERIFY_ERROR, "The flag in the code signature block header is incorrect."); return nullptr; } std::vector inReserved(RESERVED_BYTE_ARRAY_LENGTH); bf.GetByte(inReserved.data(), RESERVED_BYTE_ARRAY_LENGTH); CodeSignBlockHeader::Builder* tempVar = new(std::nothrow) CodeSignBlockHeader::Builder(); - if(tempVar == nullptr) { - PrintErrorNumberMsg("VERIFY_ERROR", VERIFY_ERROR, - "create CodeSignBlockHeader::Builder failed"); + if (tempVar == nullptr) { + PrintErrorNumberMsg("VERIFY_ERROR", VERIFY_ERROR, "create CodeSignBlockHeader::Builder failed"); return nullptr; } CodeSignBlockHeader* codeSignBlockHeader = tempVar->SetMagic(inMagic)->SetVersion(inVersion)-> diff --git a/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp b/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp index aa4eb373..be77b266 100644 --- a/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp +++ b/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp @@ -48,9 +48,8 @@ bool CodeSigning::GetCodeSignBlock(const std::string &input, int64_t offset, ZipSigner& zip, std::vector& ret) { SIGNATURE_TOOLS_LOGI("Start to sign code."); - bool formatFlag = std::find(SUPPORT_FILE_FORM.begin(), SUPPORT_FILE_FORM.end(), inForm) - == SUPPORT_FILE_FORM.end(); - if (formatFlag) { + bool flag = std::find(SUPPORT_FILE_FORM.begin(), SUPPORT_FILE_FORM.end(), inForm) == SUPPORT_FILE_FORM.end(); + if (flag) { SIGNATURE_TOOLS_LOGE("only support format is [hap, hqf, hsp, app]"); return false; } diff --git a/hapsigntool_cpp/hap/sign/src/sign_hap.cpp b/hapsigntool_cpp/hap/sign/src/sign_hap.cpp index 0c24b5b6..dcc8afd6 100644 --- a/hapsigntool_cpp/hap/sign/src/sign_hap.cpp +++ b/hapsigntool_cpp/hap/sign/src/sign_hap.cpp @@ -97,8 +97,7 @@ void SignHap::EncodeListOfPairsToByteArray(const DigestParameter& digestParam, { int encodeSize = INT_SIZE * 2 + INT_SIZE * 3 * nidAndcontentDigests.size(); encodeSize += std::accumulate(nidAndcontentDigests.begin(), nidAndcontentDigests.end(), 0, - [](int sum, const std::pair& pair) { - return sum + pair.second.GetCapacity(); }); + [](int sum, const std::pair& pair) { return sum + pair.second.GetCapacity(); }); result.SetCapacity(encodeSize); result.PutInt32(CONTENT_VERSION); // version result.PutInt32(BLOCK_NUMBER); // block number @@ -142,8 +141,7 @@ bool SignHap::GenerateHapSigningBlock(const std::string& hapSignatureSchemeBlock // uint128: magic // uint32: version long optionalBlockSize = std::accumulate(optionalBlocks.begin(), optionalBlocks.end(), 0L, - [](int64_t sum, const auto& elem) { - return sum + elem.optionalBlockValue.GetCapacity(); }); + [](int64_t sum, const auto& elem) { return sum + elem.optionalBlockValue.GetCapacity(); }); long resultSize = ((OPTIONAL_TYPE_SIZE + OPTIONAL_LENGTH_SIZE + OPTIONAL_OFFSET_SIZE) * (optionalBlocks.size() + 1)) + optionalBlockSize + hapSignatureSchemeBlock.size() + BLOCK_COUNT + HapUtils::BLOCK_SIZE + BLOCK_MAGIC + BLOCK_VERSION; diff --git a/hapsigntool_cpp/hap/verify/src/verify_hap.cpp b/hapsigntool_cpp/hap/verify/src/verify_hap.cpp index 09c60202..7a731348 100644 --- a/hapsigntool_cpp/hap/verify/src/verify_hap.cpp +++ b/hapsigntool_cpp/hap/verify/src/verify_hap.cpp @@ -129,9 +129,7 @@ bool VerifyHap::HapOutPutCertChain(std::vector& certs, const std::string& certStr.emplace_back(StringUtils::x509CertToString(cert)); } std::string outPutCertChainContent = std::accumulate(certStr.begin(), certStr.end(), std::string(), - [](std::string sum, const std::string& certstr) { - return sum + certstr; }); - + [](std::string sum, const std::string& certstr) { return sum + certstr; }); if (FileUtils::Write(outPutCertChainContent, outPutPath) < 0) { SIGNATURE_TOOLS_LOGE("certChain write to file falied!\n"); return false; diff --git a/hapsigntool_cpp/utils/src/hap_signer_block_utils.cpp b/hapsigntool_cpp/utils/src/hap_signer_block_utils.cpp index 56f13d1f..63e2f1d3 100644 --- a/hapsigntool_cpp/utils/src/hap_signer_block_utils.cpp +++ b/hapsigntool_cpp/utils/src/hap_signer_block_utils.cpp @@ -330,11 +330,8 @@ bool HapSignerBlockUtils::ParseSubSignBlockHead(HapSubSignBlockHead& subSignBloc * This function reads the head of the HapSubSignBlocks, * and then reads the corresponding data of each block according to the offset provided by the head */ -bool HapSignerBlockUtils::FindHapSubSigningBlock(RandomAccessFile& hapFile, - int32_t blockCount, - int64_t blockArrayLen, - int64_t hapSignBlockOffset, - SignatureInfo& signInfo) +bool HapSignerBlockUtils::FindHapSubSigningBlock(RandomAccessFile& hapFile, int32_t blockCount, int64_t blockArrayLen, + int64_t hapSignBlockOffset, SignatureInfo& signInfo) { int64_t offsetMax = hapSignBlockOffset + blockArrayLen; int64_t readLen = 0; @@ -352,25 +349,18 @@ bool HapSignerBlockUtils::FindHapSubSigningBlock(RandomAccessFile& hapFile, return false; } readLen += sizeof(HapSubSignBlockHead); - readHeadOffset += sizeof(HapSubSignBlockHead); if (readHeadOffset > offsetMax) { SIGNATURE_TOOLS_LOGE("find %dst next head offset error", i); return false; } - int64_t headOffset = static_cast(subSignBlockHead.offset); int64_t headLength = static_cast(subSignBlockHead.length); /* check subSignBlockHead */ - if ((offsetMax - headOffset) < hapSignBlockOffset) { - SIGNATURE_TOOLS_LOGE("Find %dst subblock data offset error", i); - return false; - } - if ((blockArrayLen - headLength) < readLen) { - SIGNATURE_TOOLS_LOGE("no enough data to be read for %dst subblock", i); + if ((offsetMax - headOffset) < hapSignBlockOffset || (blockArrayLen - headLength) < readLen) { + SIGNATURE_TOOLS_LOGE("failed to find data offset or enough data for %dst subblock error", i); return false; } - int64_t dataOffset = hapSignBlockOffset + headOffset; ByteBuffer signBuffer(subSignBlockHead.length); if ((ret = hapFile.ReadFileFullyFromOffset(signBuffer, dataOffset)) < 0) { @@ -378,17 +368,14 @@ bool HapSignerBlockUtils::FindHapSubSigningBlock(RandomAccessFile& hapFile, return false; } readLen += headLength; - if (!ClassifyHapSubSigningBlock(signInfo, signBuffer, subSignBlockHead.type)) { SIGNATURE_TOOLS_LOGE("subSigningBlock error, type is %d", subSignBlockHead.type); return false; } } - /* size of block must be equal to the sum of all subblocks length */ if (readLen != blockArrayLen) { - SIGNATURE_TOOLS_LOGE("Len: %" PRId64 " is not equal blockArrayLen: %" PRId64, - readLen, blockArrayLen); + SIGNATURE_TOOLS_LOGE("Len: %" PRId64 " is not equal blockArrayLen: %" PRId64, readLen, blockArrayLen); return false; } return true; diff --git a/hapsigntool_cpp/utils/src/key_store_helper.cpp b/hapsigntool_cpp/utils/src/key_store_helper.cpp index 4a988cfe..58cb01f7 100644 --- a/hapsigntool_cpp/utils/src/key_store_helper.cpp +++ b/hapsigntool_cpp/utils/src/key_store_helper.cpp @@ -153,31 +153,27 @@ bool KeyStoreHelper::InitX509(X509& cert, EVP_PKEY& evpPkey) const EVP_MD* md = EVP_sha256(); X509_NAME* subjectName = nullptr; if (!bnSerial || !issuerName || !md) { - KeyPairFree(bnSerial, issuerName, subjectName, nullptr, - "Failed to initialize the x509 info."); + KeyPairFree(bnSerial, issuerName, subjectName, nullptr, "Failed to initialize the x509 info."); return false; } ASN1_INTEGER* ai = BN_to_ASN1_INTEGER(bnSerial, NULL); if (ai == NULL || issuerName == NULL) { - KeyPairFree(bnSerial, issuerName, subjectName, ai, - "Failed to initialize the x509 structure."); + KeyPairFree(bnSerial, issuerName, subjectName, ai, "Failed to initialize the x509 structure."); return false; } - X509_set_serialNumber(&cert, ai); X509_gmtime_adj(X509_get_notBefore(&cert), 0); X509_gmtime_adj(X509_get_notAfter(&cert), (long)DEFAULT_VALIDITY_DAYS * ONE_DAY_TIME); - if (!X509_NAME_add_entry_by_txt(issuerName, "C", + if (!X509_NAME_add_entry_by_txt(issuerName, "C", MBSTRING_ASC, reinterpret_cast("US"), -1, -1, 0) - || !X509_NAME_add_entry_by_txt(issuerName, "O", + || !X509_NAME_add_entry_by_txt(issuerName, "O", MBSTRING_ASC, reinterpret_cast("My Company"), -1, -1, 0) - || !X509_NAME_add_entry_by_txt(issuerName, "CN", + || !X509_NAME_add_entry_by_txt(issuerName, "CN", MBSTRING_ASC, reinterpret_cast("My Issuer"), -1, -1, 0)) { KeyPairFree(bnSerial, issuerName, subjectName, ai, "Failed to initialize the x509 structure.X509_NAME type"); return false; } - X509_set_issuer_name(&cert, issuerName); subjectName = X509_NAME_dup(issuerName); if (subjectName == NULL) { @@ -185,21 +181,18 @@ bool KeyStoreHelper::InitX509(X509& cert, EVP_PKEY& evpPkey) "Failed to initialize the x509 structure.X509_NAME type"); return false; } - X509_set_subject_name(&cert, subjectName); if (!X509_set_pubkey(&cert, &evpPkey)) { KeyPairFree(bnSerial, issuerName, subjectName, ai, "Failed to initialize the x509 structure.X509_NAME type"); return false; } - X509_set_version(&cert, DEFAULT_CERT_VERSION); if (!X509_sign(&cert, &evpPkey, md)) { KeyPairFree(bnSerial, issuerName, subjectName, ai, "Failed to initialize the x509 structure.X509_NAME type"); return false; } - KeyPairFree(bnSerial, issuerName, subjectName, ai, ""); return true; } diff --git a/hapsigntool_cpp/utils/src/string_utils.cpp b/hapsigntool_cpp/utils/src/string_utils.cpp index e85d7ef2..662065d7 100644 --- a/hapsigntool_cpp/utils/src/string_utils.cpp +++ b/hapsigntool_cpp/utils/src/string_utils.cpp @@ -31,9 +31,7 @@ bool StringUtils::ContainsCase(const std::vector &strs, const std:: std::string fileSuffix = str; std::transform(fileSuffix.begin(), fileSuffix.end(), fileSuffix.begin(), [](unsigned char c) { return std::tolower(c); }); - - return std::any_of(strs.begin(), strs.end(), [&fileSuffix](const std::string& val) { - return val == fileSuffix; }); + return std::any_of(strs.begin(), strs.end(), [&fileSuffix](const std::string& val) {return val == fileSuffix; }); } bool StringUtils::CaseCompare(const std::string& str1, const std::string& str2) diff --git a/hapsigntool_cpp/zip/src/random_access_file_input.cpp b/hapsigntool_cpp/zip/src/random_access_file_input.cpp index 92023ae3..2d00508c 100644 --- a/hapsigntool_cpp/zip/src/random_access_file_input.cpp +++ b/hapsigntool_cpp/zip/src/random_access_file_input.cpp @@ -71,7 +71,7 @@ bool RandomAccessFileInput::CopyTo(int64_t offset, int size, ByteBuffer& buffer) while (remaining > 0) { int64_t readSize; std::mutex tmpMutex; - { + { std::scoped_lock lock(tmpMutex); readSize = file.ReadFileFullyFromOffset(buffer, offsetInFile); } -- Gitee From 6dc1e297862f0f9c21378f4a13cd4a9a87f7a248 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E6=97=8B=E9=A3=8Elc?= Date: Mon, 18 Nov 2024 16:29:19 +0800 Subject: [PATCH 5/7] modify Signed-off-by: liuchang --- .../codesigning/sign/src/code_signing.cpp | 5 ++--- .../codesigning/sign/src/verify_code_signature.cpp | 14 ++++++++------ 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp b/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp index be77b266..1afff098 100644 --- a/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp +++ b/hapsigntool_cpp/codesigning/sign/src/code_signing.cpp @@ -53,12 +53,11 @@ bool CodeSigning::GetCodeSignBlock(const std::string &input, int64_t offset, SIGNATURE_TOOLS_LOGE("only support format is [hap, hqf, hsp, app]"); return false; } - int64_t dataSizeInt64 = ComputeDataSize(zip); - if (dataSizeInt64 < 0) { + int64_t dataSize = ComputeDataSize(zip); + if (dataSize < 0) { SIGNATURE_TOOLS_LOGE("SignFile Failed because dataSize is invalid"); return false; } - uint32_t dataSize = static_cast(dataSizeInt64); m_timestamp = GetTimestamp(); int64_t fsvTreeOffset = m_codeSignBlock.ComputeMerkleTreeOffset(offset); std::unique_ptr fsVerityInfoSegment = diff --git a/hapsigntool_cpp/codesigning/sign/src/verify_code_signature.cpp b/hapsigntool_cpp/codesigning/sign/src/verify_code_signature.cpp index fd38f0f3..38805242 100644 --- a/hapsigntool_cpp/codesigning/sign/src/verify_code_signature.cpp +++ b/hapsigntool_cpp/codesigning/sign/src/verify_code_signature.cpp @@ -293,13 +293,15 @@ bool VerifyCodeSignature::ParseMerkleTree(CodeSignBlock& csb, int32_t readOffset return false; } MerkleTreeExtension* mte = static_cast(extension); - bool merkleTreeFlag = computedTreeOffset != mte->GetMerkleTreeOffset() || - merkleTreeBytes.size() != mte->GetMerkleTreeSize(); - if (merkleTreeFlag) { - PrintErrorNumberMsg("VERIFY_ERROR", VERIFY_ERROR, "Invalid merkle tree offset or tree size"); - return false; + if (mte != nullptr) { + bool merkleTreeFlag = computedTreeOffset != mte->GetMerkleTreeOffset() || + merkleTreeBytes.size() != mte->GetMerkleTreeSize(); + if (merkleTreeFlag) { + PrintErrorNumberMsg("VERIFY_ERROR", VERIFY_ERROR, "Invalid merkle tree offset or tree size"); + return false; + } + csb.AddOneMerkleTree(CodeSigning::HAP_SIGNATURE_ENTRY_NAME, *(std::vector *) &merkleTreeBytes); } - csb.AddOneMerkleTree(CodeSigning::HAP_SIGNATURE_ENTRY_NAME, *(std::vector *) &merkleTreeBytes); return true; } -- Gitee From 539ebbbbcaf150cf98f77f78ece01a5696d074e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E6=97=8B=E9=A3=8Elc?= Date: Tue, 19 Nov 2024 09:52:43 +0800 Subject: [PATCH 6/7] modify Signed-off-by: liuchang --- .../api/src/sign_tool_service_impl.cpp | 29 ++++++++----------- 1 file changed, 12 insertions(+), 17 deletions(-) diff --git a/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp b/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp index 52d35349..c595576b 100644 --- a/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp +++ b/hapsigntool_cpp/api/src/sign_tool_service_impl.cpp @@ -77,7 +77,6 @@ bool SignToolServiceImpl::GenerateRootCertToFile(Options* options, EVP_PKEY* roo std::string subject = options->GetString(Options::SUBJECT); X509* certPtr = nullptr; X509_REQ* csr = nullptr; - bool result = false; do { csr = CertTools::GenerateCsr(rootKey, signAlg, subject); if (!csr) { @@ -90,20 +89,18 @@ bool SignToolServiceImpl::GenerateRootCertToFile(Options* options, EVP_PKEY* roo if (!X509CertVerify(certPtr, rootKey)) { break; } - if (!OutputModeOfCert(certPtr, options)) { break; } - result = true; - } while (0); - - if (!result) { - SIGNATURE_TOOLS_LOGE("generate root cert failed!"); X509_free(certPtr); X509_REQ_free(csr); - return false; - } - return true; + return true; + } while (0); + + SIGNATURE_TOOLS_LOGE("generate root cert failed!"); + X509_free(certPtr); + X509_REQ_free(csr); + return false; } bool SignToolServiceImpl::GenerateSubCertToFile(Options* options, EVP_PKEY* rootKey) @@ -116,7 +113,6 @@ bool SignToolServiceImpl::GenerateSubCertToFile(Options* options, EVP_PKEY* root std::string issuer = options->GetString(Options::ISSUER); X509* cert = nullptr; X509_REQ* csr = nullptr; - bool result = false; do { if (rootKey == nullptr) { break; @@ -135,16 +131,15 @@ bool SignToolServiceImpl::GenerateSubCertToFile(Options* options, EVP_PKEY* root if (!OutputModeOfCert(cert, options)) { break; } - result = true; + X509_free(cert); + X509_REQ_free(csr); + return true; } while (0); X509_free(cert); X509_REQ_free(csr); - if (!result) { - SIGNATURE_TOOLS_LOGE("generate sub cert failed!"); - return false; - } - return true; + SIGNATURE_TOOLS_LOGE("generate sub cert failed!"); + return false; } int SignToolServiceImpl::HandleIssuerKeyAliasEmpty(Options* options) -- Gitee From 8e5767a07e2a911b297aaf606ed3a1bd8a979e23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E6=97=8B=E9=A3=8Elc?= Date: Tue, 19 Nov 2024 11:47:10 +0800 Subject: [PATCH 7/7] modify make_shared_array max memory Signed-off-by: liuchang --- hapsigntool_cpp/common/src/byte_buffer.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/hapsigntool_cpp/common/src/byte_buffer.cpp b/hapsigntool_cpp/common/src/byte_buffer.cpp index a24266cc..8e4bb061 100644 --- a/hapsigntool_cpp/common/src/byte_buffer.cpp +++ b/hapsigntool_cpp/common/src/byte_buffer.cpp @@ -23,6 +23,7 @@ namespace SignatureTools { const int32_t ByteBuffer::MAX_PRINT_LENGTH = 200; const int32_t ByteBuffer::HEX_PRINT_LENGTH = 3; +const int32_t MAX_MEMORY = 2 * 1024 * 1024 * 1024; template std::shared_ptr make_shared_array(size_t size) @@ -30,6 +31,10 @@ std::shared_ptr make_shared_array(size_t size) if (size == 0) { return NULL; } + if (size > MAX_MEMORY) { + SIGNATURE_TOOLS_LOGE("size %zu is too large", size); + return NULL; + } T* buffer = new (std::nothrow)T[size]; if (!buffer) { SIGNATURE_TOOLS_LOGE("new size failed"); -- Gitee