• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "openssl_utils.h"
17 
18 #include "log.h"
19 
20 namespace OHOS {
21 namespace Security {
22 namespace CodeSign {
GetOpensslErrorMessage()23 void GetOpensslErrorMessage()
24 {
25     unsigned long retOpenssl;
26     char errOpenssl[OPENSSL_ERR_MESSAGE_MAX_LEN];
27     while ((retOpenssl = ERR_get_error()) != 0) {
28         // error string is written no more than OPENSSL_ERR_MESSAGE_MAX_LEN in errOpenssl
29         ERR_error_string_n(retOpenssl, errOpenssl, OPENSSL_ERR_MESSAGE_MAX_LEN);
30         LOG_ERROR(LABEL, "openssl err: %{public}lu, message: %{public}s", retOpenssl, errOpenssl);
31     }
32 }
33 
LoadCertFromBuffer(const uint8_t * buffer,const uint32_t size)34 X509 *LoadCertFromBuffer(const uint8_t *buffer, const uint32_t size)
35 {
36     BIO *mem = BIO_new_mem_buf(buffer, size);
37     if (mem == nullptr) {
38         LOG_ERROR(LABEL, "Fail to create bio for cert.");
39         return nullptr;
40     }
41     X509 *cert = d2i_X509_bio(mem, nullptr);
42     if (cert == nullptr) {
43         ERR_LOG_WITH_OPEN_SSL_MSG("Certificate is invalid.");
44     }
45     BIO_free(mem);
46     return cert;
47 }
48 
STACK_OF(X509)49 STACK_OF(X509) *MakeStackOfCerts(const std::vector<ByteBuffer> &certChain)
50 {
51     STACK_OF(X509)* certs = sk_X509_new_null();
52     if (certs == nullptr) {
53         return nullptr;
54     }
55     for (const ByteBuffer &cert: certChain) {
56         X509 *tmp = LoadCertFromBuffer(cert.GetBuffer(), cert.GetSize());
57         if ((tmp == nullptr) || (!sk_X509_push(certs, tmp))) {
58             // including each cert in certs and stack of certs
59             sk_X509_pop_free(certs, X509_free);
60             certs = nullptr;
61             break;
62         }
63     }
64     return certs;
65 }
66 }
67 }
68 }
69