1 /*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "cert_utils.h"
17
18 #include <cstring>
19 #include <string>
20
21 #include "log.h"
22
23 namespace OHOS {
24 namespace Security {
25 namespace CodeSign {
26 static const uint32_t CERT_DATA_SIZE = 8192;
27 static const uint32_t CERT_COUNT = 4;
28
ConstructDataToCertChain(struct HksCertChain ** certChain)29 bool ConstructDataToCertChain(struct HksCertChain **certChain)
30 {
31 *certChain = static_cast<struct HksCertChain *>(malloc(sizeof(struct HksCertChain)));
32 if (*certChain == nullptr) {
33 LOG_ERROR(LABEL, "malloc fail");
34 return false;
35 }
36 (*certChain)->certsCount = CERT_COUNT;
37
38 (*certChain)->certs = static_cast<struct HksBlob *>(malloc(sizeof(struct HksBlob) *
39 ((*certChain)->certsCount)));
40 if ((*certChain)->certs == nullptr) {
41 free(*certChain);
42 *certChain = nullptr;
43 return false;
44 }
45 for (uint32_t i = 0; i < (*certChain)->certsCount; i++) {
46 (*certChain)->certs[i].size = CERT_DATA_SIZE;
47 (*certChain)->certs[i].data = static_cast<uint8_t *>(malloc((*certChain)->certs[i].size));
48 if ((*certChain)->certs[i].data == nullptr) {
49 LOG_ERROR(LABEL, "malloc fail");
50 FreeCertChain(certChain, i);
51 return false;
52 }
53 }
54 return true;
55 }
56
FreeCertChain(struct HksCertChain ** certChain,const uint32_t pos)57 void FreeCertChain(struct HksCertChain **certChain, const uint32_t pos)
58 {
59 if (*certChain == nullptr) {
60 return;
61 }
62 if ((*certChain)->certs == nullptr) {
63 free(*certChain);
64 *certChain = nullptr;
65 return;
66 }
67 for (uint32_t j = 0; j < pos; j++) {
68 if ((*certChain)->certs[j].data != nullptr) {
69 free((*certChain)->certs[j].data);
70 (*certChain)->certs[j].data = nullptr;
71 }
72 }
73 free((*certChain)->certs);
74 (*certChain)->certs = nullptr;
75 free(*certChain);
76 *certChain = nullptr;
77 }
78 }
79 }
80 }