1 /*
2  * Copyright (c) 2023-2024 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 "x509_certificate_openssl.h"
17 
18 #include <securec.h>
19 #include <openssl/asn1.h>
20 #include <openssl/bio.h>
21 #include <openssl/x509.h>
22 #include <openssl/x509v3.h>
23 #include <openssl/evp.h>
24 #include <openssl/pem.h>
25 
26 #include "config.h"
27 #include "cf_log.h"
28 #include "cf_memory.h"
29 #include "result.h"
30 #include "cf_result.h"
31 #include "utils.h"
32 #include "x509_certificate.h"
33 #include "certificate_openssl_class.h"
34 #include "certificate_openssl_common.h"
35 
36 #define X509_CERT_PUBLIC_KEY_OPENSSL_CLASS "X509CertPublicKeyOpensslClass"
37 #define OID_STR_MAX_LEN 128
38 #define CHAR_TO_BIT_LEN 8
39 #define MAX_DATE_STR_LEN 128
40 #define FLAG_BIT_LEFT_NUM 0x07
41 #define DATETIME_LEN 15
42 #define MIN_PATH_LEN_CONSTRAINT (-2)
43 
44 typedef struct {
45     HcfPubKey base;
46     EVP_PKEY *pubKey;
47 } X509PubKeyOpensslImpl;
48 
49 static CfResult GetSubjectDNX509Openssl(HcfX509CertificateSpi *self, CfBlob *out);
50 static CfResult GetIssuerDNX509Openssl(HcfX509CertificateSpi *self, CfBlob *out);
51 static CfResult GetKeyUsageX509Openssl(HcfX509CertificateSpi *self, CfBlob *boolArr);
52 static CfResult GetSerialNumberX509Openssl(HcfX509CertificateSpi *self, CfBlob *out);
53 static CfResult GetSigAlgOidX509Openssl(HcfX509CertificateSpi *self, CfBlob *out);
54 static CfResult GetSubjectPubKeyAlgOidX509Openssl(HcfX509CertificateSpi *self, CfBlob *out);
55 
GetX509CertClass(void)56 static const char *GetX509CertClass(void)
57 {
58     return X509_CERT_OPENSSL_CLASS;
59 }
60 
DestroyX509Openssl(CfObjectBase * self)61 static void DestroyX509Openssl(CfObjectBase *self)
62 {
63     if (self == NULL) {
64         return;
65     }
66     if (!CfIsClassMatch(self, GetX509CertClass())) {
67         LOGE("Input wrong class type!");
68         return;
69     }
70     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
71     X509_free(realCert->x509);
72     realCert->x509 = NULL;
73     CfFree(realCert);
74 }
75 
GetX509CertPubKeyClass(void)76 static const char *GetX509CertPubKeyClass(void)
77 {
78     return X509_CERT_PUBLIC_KEY_OPENSSL_CLASS;
79 }
80 
DestroyX509PubKeyOpenssl(HcfObjectBase * self)81 static void DestroyX509PubKeyOpenssl(HcfObjectBase *self)
82 {
83     if (self == NULL) {
84         return;
85     }
86     if (!CfIsPubKeyClassMatch(self, GetX509CertPubKeyClass())) {
87         LOGE("Input wrong class type!");
88         return;
89     }
90     X509PubKeyOpensslImpl *impl = (X509PubKeyOpensslImpl *)self;
91     if (impl->pubKey != NULL) {
92         EVP_PKEY_free(impl->pubKey);
93         impl->pubKey = NULL;
94     }
95     CfFree(impl);
96 }
97 
GetPubKeyAlgorithm(HcfKey * self)98 static const char *GetPubKeyAlgorithm(HcfKey *self)
99 {
100     (void)self;
101     LOGD("Not supported!");
102     return NULL;
103 }
104 
GetPubKeyEncoded(HcfKey * self,HcfBlob * returnBlob)105 static HcfResult GetPubKeyEncoded(HcfKey *self, HcfBlob *returnBlob)
106 {
107     if (self == NULL || returnBlob == NULL) {
108         LOGE("Input params is invalid.");
109         return HCF_INVALID_PARAMS;
110     }
111     if (!CfIsPubKeyClassMatch((HcfObjectBase *)self, GetX509CertPubKeyClass())) {
112         LOGE("Input wrong class type!");
113         return HCF_INVALID_PARAMS;
114     }
115     X509PubKeyOpensslImpl *impl = (X509PubKeyOpensslImpl *)self;
116 
117     unsigned char *pkBytes = NULL;
118     int32_t pkLen = i2d_PUBKEY(impl->pubKey, &pkBytes);
119     if (pkLen <= 0) {
120         CfPrintOpensslError();
121         LOGE("Failed to convert internal pubkey to der format!");
122         return HCF_ERR_CRYPTO_OPERATION;
123     }
124 
125     returnBlob->data = (uint8_t *)CfMalloc(pkLen, 0);
126     if (returnBlob->data == NULL) {
127         LOGE("Failed to malloc for sig algorithm params!");
128         OPENSSL_free(pkBytes);
129         return HCF_ERR_MALLOC;
130     }
131     (void)memcpy_s(returnBlob->data, pkLen, pkBytes, pkLen);
132     returnBlob->len = (size_t)pkLen;
133 
134     OPENSSL_free(pkBytes);
135     return HCF_SUCCESS;
136 }
137 
GetPubKeyFormat(HcfKey * self)138 static const char *GetPubKeyFormat(HcfKey *self)
139 {
140     (void)self;
141     LOGD("Not supported!");
142     return NULL;
143 }
144 
VerifyX509Openssl(HcfX509CertificateSpi * self,HcfPubKey * key)145 static CfResult VerifyX509Openssl(HcfX509CertificateSpi *self, HcfPubKey *key)
146 {
147     if ((self == NULL) || (key == NULL)) {
148         LOGE("The input data is null!");
149         return CF_INVALID_PARAMS;
150     }
151     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass()) ||
152         (!CfIsPubKeyClassMatch((HcfObjectBase *)key, GetX509CertPubKeyClass()))) {
153         LOGE("Input wrong class type!");
154         return CF_INVALID_PARAMS;
155     }
156     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
157     X509 *x509 = realCert->x509;
158 
159     X509PubKeyOpensslImpl *keyImpl = (X509PubKeyOpensslImpl *)key;
160     EVP_PKEY *pubKey = keyImpl->pubKey;
161     if (X509_verify(x509, pubKey) != CF_OPENSSL_SUCCESS) {
162         LOGE("Failed to verify x509 cert's signature.");
163         CfPrintOpensslError();
164         return CF_ERR_CRYPTO_OPERATION;
165     }
166     return CF_SUCCESS;
167 }
168 
GetEncodedX509Openssl(HcfX509CertificateSpi * self,CfEncodingBlob * encodedByte)169 static CfResult GetEncodedX509Openssl(HcfX509CertificateSpi *self, CfEncodingBlob *encodedByte)
170 {
171     if ((self == NULL) || (encodedByte == NULL)) {
172         LOGE("The input data is null!");
173         return CF_INVALID_PARAMS;
174     }
175     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
176         LOGE("Input wrong class type!");
177         return CF_INVALID_PARAMS;
178     }
179     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
180     X509 *x509 = realCert->x509;
181 
182     unsigned char *der = NULL;
183     int32_t length = i2d_X509(x509, &der);
184     if (length <= 0 || der == NULL) {
185         LOGE("Failed to convert internal x509 to der format!");
186         CfPrintOpensslError();
187         return CF_ERR_CRYPTO_OPERATION;
188     }
189     encodedByte->data = (uint8_t *)CfMalloc(length, 0);
190     if (encodedByte->data == NULL) {
191         LOGE("Failed to malloc for x509 der data!");
192         OPENSSL_free(der);
193         return CF_ERR_MALLOC;
194     }
195     (void)memcpy_s(encodedByte->data, length, der, length);
196     OPENSSL_free(der);
197     encodedByte->len = length;
198     encodedByte->encodingFormat = CF_FORMAT_DER;
199     return CF_SUCCESS;
200 }
201 
GetPublicKeyX509Openssl(HcfX509CertificateSpi * self,HcfPubKey ** keyOut)202 static CfResult GetPublicKeyX509Openssl(HcfX509CertificateSpi *self, HcfPubKey **keyOut)
203 {
204     if ((self == NULL) || (keyOut == NULL)) {
205         LOGE("The input data is null!");
206         return CF_INVALID_PARAMS;
207     }
208     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
209         LOGE("Input wrong class type!");
210         return CF_INVALID_PARAMS;
211     }
212     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
213     X509 *x509 = realCert->x509;
214 
215     EVP_PKEY *pubKey = X509_get_pubkey(x509);
216     if (pubKey == NULL) {
217         LOGE("Failed to get publick key from x509 cert.");
218         CfPrintOpensslError();
219         return CF_ERR_CRYPTO_OPERATION;
220     }
221     X509PubKeyOpensslImpl *keyImpl = (X509PubKeyOpensslImpl *)CfMalloc(sizeof(X509PubKeyOpensslImpl), 0);
222     if (keyImpl == NULL) {
223         LOGE("Failed to malloc for public key obj!");
224         EVP_PKEY_free(pubKey);
225         return CF_ERR_MALLOC;
226     }
227     keyImpl->pubKey = pubKey;
228     keyImpl->base.base.base.destroy = DestroyX509PubKeyOpenssl;
229     keyImpl->base.base.base.getClass = GetX509CertPubKeyClass;
230     keyImpl->base.base.getEncoded = GetPubKeyEncoded;
231     keyImpl->base.base.getAlgorithm = GetPubKeyAlgorithm;
232     keyImpl->base.base.getFormat = GetPubKeyFormat;
233     *keyOut = (HcfPubKey *)keyImpl;
234     return CF_SUCCESS;
235 }
236 
CompareCertBlobX509Openssl(HcfX509CertificateSpi * self,HcfCertificate * x509Cert,bool * out)237 static CfResult CompareCertBlobX509Openssl(HcfX509CertificateSpi *self, HcfCertificate *x509Cert, bool *out)
238 {
239     CfResult res = CF_SUCCESS;
240     CfEncodingBlob encodedBlobSelf = { NULL, 0, CF_FORMAT_DER };
241     CfEncodingBlob encodedBlobParam = { NULL, 0, CF_FORMAT_DER };
242     if (x509Cert != NULL) {
243         res = x509Cert->getEncoded(x509Cert, &encodedBlobParam);
244         if (res != CF_SUCCESS) {
245             LOGE("x509Cert getEncoded failed!");
246             return res;
247         }
248         res = GetEncodedX509Openssl(self, &encodedBlobSelf);
249         if (res != CF_SUCCESS) {
250             LOGE("x509Cert GetEncodedX509Openssl failed!");
251             CfFree(encodedBlobParam.data);
252             return res;
253         }
254         if ((encodedBlobSelf.len != encodedBlobParam.len) ||
255             (memcmp(encodedBlobSelf.data, encodedBlobParam.data, encodedBlobSelf.len) != 0)) {
256             *out = false;
257         }
258 
259         CfFree(encodedBlobParam.data);
260         CfFree(encodedBlobSelf.data);
261     }
262 
263     return res;
264 }
265 
GetAuKeyIdDNX509Openssl(HcfX509CertificateSpi * self,CfBlob * out)266 static CfResult GetAuKeyIdDNX509Openssl(HcfX509CertificateSpi *self, CfBlob *out)
267 {
268     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
269     X509 *x509 = realCert->x509;
270     AUTHORITY_KEYID *akid = X509_get_ext_d2i(x509, NID_authority_key_identifier, NULL, NULL);
271     if (akid == NULL) {
272         LOGE("Failed to get authority key identifier!");
273         return CF_ERR_CRYPTO_OPERATION;
274     }
275 
276     unsigned char *akidBytes = NULL;
277     int32_t akidLen = i2d_AUTHORITY_KEYID(akid, &akidBytes);
278     if (akidLen <= 0) {
279         AUTHORITY_KEYID_free(akid);
280         CfPrintOpensslError();
281         LOGE("Failed to convert akid to der format!");
282         return CF_ERR_CRYPTO_OPERATION;
283     }
284     CfResult res = DeepCopyDataToBlob(akidBytes, (uint32_t)akidLen, out);
285     AUTHORITY_KEYID_free(akid);
286     OPENSSL_free(akidBytes);
287     return res;
288 }
289 
GetSubKeyIdDNX509Openssl(HcfX509CertificateSpi * self,CfBlob * out)290 static CfResult GetSubKeyIdDNX509Openssl(HcfX509CertificateSpi *self, CfBlob *out)
291 {
292     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
293     X509 *x509 = realCert->x509;
294     ASN1_OCTET_STRING *skid = X509_get_ext_d2i(x509, NID_subject_key_identifier, NULL, NULL);
295     if (skid == NULL) {
296         LOGE("Failed to get subject key identifier!");
297         return CF_ERR_CRYPTO_OPERATION;
298     }
299     unsigned char *skidBytes = NULL;
300     int32_t nLen = i2d_ASN1_OCTET_STRING(skid, &skidBytes);
301     if (nLen <= 0) {
302         ASN1_OCTET_STRING_free(skid);
303         CfPrintOpensslError();
304         LOGE("Failed to convert subject key id to der format!");
305         return CF_ERR_CRYPTO_OPERATION;
306     }
307     CfResult res = DeepCopyDataToBlob(skidBytes, (uint32_t)nLen, out);
308     ASN1_OCTET_STRING_free(skid);
309     OPENSSL_free(skidBytes);
310     return res;
311 }
312 
ConvertName(const CfBlob * blobObj,CfBlob * cfBlobDataParam,X509NameType nameType)313 static CfResult ConvertName(const CfBlob *blobObj, CfBlob *cfBlobDataParam, X509NameType nameType)
314 {
315     switch (nameType) {
316         case NAME_TYPE_SUBJECT:
317         case NAME_TYPE_ISSUER:
318             return ConvertNameDerDataToString(blobObj->data, blobObj->size, cfBlobDataParam);
319         case NAME_TYPE_AUKEYID:
320         case NAME_TYPE_SUBKEYID:
321             return DeepCopyDataToBlob(blobObj->data, blobObj->size, cfBlobDataParam);
322         default:
323             return CF_INVALID_PARAMS;
324     }
325 }
326 
CompareNameObjectX509Openssl(HcfX509CertificateSpi * self,const CfBlob * blobObj,X509NameType nameType,bool * out)327 static CfResult CompareNameObjectX509Openssl(
328     HcfX509CertificateSpi *self, const CfBlob *blobObj, X509NameType nameType, bool *out)
329 {
330     CfResult res = CF_SUCCESS;
331     CfBlob cfBlobDataSelf = { 0 };
332     CfBlob cfBlobDataParam = { 0 };
333 
334     if (blobObj != NULL) {
335         res = ConvertName(blobObj, &cfBlobDataParam, nameType);
336         if (res != CF_SUCCESS) {
337             LOGE("Convert name der data to string failed!");
338             return res;
339         }
340 
341         switch (nameType) {
342             case NAME_TYPE_SUBJECT:
343                 res = GetSubjectDNX509Openssl(self, &cfBlobDataSelf);
344                 break;
345             case NAME_TYPE_ISSUER:
346                 res = GetIssuerDNX509Openssl(self, &cfBlobDataSelf);
347                 break;
348             case NAME_TYPE_AUKEYID:
349                 res = GetAuKeyIdDNX509Openssl(self, &cfBlobDataSelf);
350                 break;
351             case NAME_TYPE_SUBKEYID:
352                 res = GetSubKeyIdDNX509Openssl(self, &cfBlobDataSelf);
353                 break;
354             default:
355                 LOGE("Unknown nameType!");
356                 CfFree(cfBlobDataParam.data);
357                 return CF_INVALID_PARAMS;
358         }
359 
360         if (res != CF_SUCCESS) {
361             LOGE("X509Cert get param object failed!");
362             CfFree(cfBlobDataParam.data);
363             return res;
364         }
365 
366         *out =
367             (cfBlobDataSelf.size == cfBlobDataParam.size) &&
368             (strncmp((const char *)cfBlobDataSelf.data, (const char *)cfBlobDataParam.data, cfBlobDataSelf.size) == 0);
369         CfFree(cfBlobDataSelf.data);
370         CfFree(cfBlobDataParam.data);
371     }
372 
373     return res;
374 }
375 
CheckValidityWithDateX509Openssl(HcfX509CertificateSpi * self,const char * date)376 static CfResult CheckValidityWithDateX509Openssl(HcfX509CertificateSpi *self, const char *date)
377 {
378     if ((self == NULL) || (date == NULL)) {
379         LOGE("The input data is null!");
380         return CF_INVALID_PARAMS;
381     }
382     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
383         LOGE("Input wrong class type!");
384         return CF_INVALID_PARAMS;
385     }
386     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
387     X509 *x509 = realCert->x509;
388 
389     ASN1_TIME *asn1InputDate = ASN1_TIME_new();
390     if (asn1InputDate == NULL) {
391         LOGE("Failed to malloc for asn1 time.");
392         return CF_ERR_MALLOC;
393     }
394     if (ASN1_TIME_set_string(asn1InputDate, date) != CF_OPENSSL_SUCCESS) {
395         LOGE("Failed to set time for asn1 time.");
396         CfPrintOpensslError();
397         ASN1_TIME_free(asn1InputDate);
398         return CF_ERR_CRYPTO_OPERATION;
399     }
400     CfResult res = CompareDateWithCertTime(x509, asn1InputDate);
401     ASN1_TIME_free(asn1InputDate);
402     return res;
403 }
404 
CompareKeyUsageX509Openssl(HcfX509CertificateSpi * self,const CfBlob * keyUsage,bool * out)405 static CfResult CompareKeyUsageX509Openssl(HcfX509CertificateSpi *self, const CfBlob *keyUsage, bool *out)
406 {
407     if (keyUsage == NULL) {
408         return CF_SUCCESS;
409     }
410     if (keyUsage->size == 0 || keyUsage->data == NULL) {
411         LOGE("invalid param!");
412         return CF_INVALID_PARAMS;
413     }
414     CfBlob cfBlobDataSelf = { 0 };
415     CfResult res = GetKeyUsageX509Openssl(self, &cfBlobDataSelf);
416     if ((res != CF_SUCCESS) && (res != CF_ERR_CRYPTO_OPERATION)) {
417         LOGE("x509Cert GetKeyUsageX509Openssl failed!");
418         return res;
419     }
420     /*
421      * Check If the position of the true value in both arrays is the same.
422      * When two array is in different length, it is considered as match success if the values of the over size part are
423      * false.
424      */
425     uint32_t index = 0;
426     for (; index < keyUsage->size && index < cfBlobDataSelf.size; ++index) {
427         if ((keyUsage->data[index] & 0x01) != (cfBlobDataSelf.data[index] & 0x01)) {
428             *out = false;
429             break;
430         }
431     }
432     if (!(*out)) {
433         CfFree(cfBlobDataSelf.data);
434         return CF_SUCCESS;
435     }
436     for (; index < cfBlobDataSelf.size; ++index) {
437         if (cfBlobDataSelf.data[index] != 0) {
438             *out = false;
439             break;
440         }
441     }
442     for (; index < keyUsage->size; ++index) {
443         if (keyUsage->data[index] != 0) {
444             *out = false;
445             break;
446         }
447     }
448     CfFree(cfBlobDataSelf.data);
449     return CF_SUCCESS;
450 }
451 
CompareSerialNumberX509Openssl(HcfX509CertificateSpi * self,const CfBlob * serialNumber,bool * out)452 static CfResult CompareSerialNumberX509Openssl(HcfX509CertificateSpi *self, const CfBlob *serialNumber, bool *out)
453 {
454     CfResult res = CF_SUCCESS;
455     CfBlob cfBlobDataSelf = { 0 };
456 
457     if (serialNumber != NULL) {
458         if (serialNumber->size == 0 || serialNumber->data == NULL) {
459             LOGE("invalid param!");
460             return CF_INVALID_PARAMS;
461         }
462 
463         res = GetSerialNumberX509Openssl(self, &cfBlobDataSelf);
464         if (res != CF_SUCCESS) {
465             LOGE("x509Cert GetSerialNumberX509Openssl failed!");
466             return res;
467         }
468         do {
469             int ret = 0;
470             res = CompareBigNum(&cfBlobDataSelf, serialNumber, &ret);
471             if (res != CF_SUCCESS) {
472                 LOGE("x509Cert CompareBigNum failed!");
473                 break;
474             }
475             if (ret != 0) {
476                 *out = false;
477                 break;
478             }
479         } while (0);
480 
481         CfFree(cfBlobDataSelf.data);
482     }
483 
484     return res;
485 }
486 
GetCertPubKey(HcfX509CertificateSpi * self,CfBlob * outBlob)487 static CfResult GetCertPubKey(HcfX509CertificateSpi *self, CfBlob *outBlob)
488 {
489     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
490     X509 *x509 = realCert->x509;
491     EVP_PKEY *pubKey = X509_get_pubkey(x509);
492     if (pubKey == NULL) {
493         CfPrintOpensslError();
494         LOGE("the x509 cert data is error!");
495         return CF_ERR_CRYPTO_OPERATION;
496     }
497 
498     unsigned char *pubKeyBytes = NULL;
499     int32_t pubKeyLen = i2d_PUBKEY(pubKey, &pubKeyBytes);
500     if (pubKeyLen <= 0) {
501         EVP_PKEY_free(pubKey);
502         CfPrintOpensslError();
503         LOGE("Failed to convert internal pubkey to der format!");
504         return CF_ERR_CRYPTO_OPERATION;
505     }
506 
507     int32_t ret = DeepCopyDataToBlob(pubKeyBytes, (uint32_t)pubKeyLen, outBlob);
508     EVP_PKEY_free(pubKey);
509     OPENSSL_free(pubKeyBytes);
510     return ret;
511 }
512 
ComparePublicKeyX509Openssl(HcfX509CertificateSpi * self,const CfBlob * pubKey,bool * out)513 static CfResult ComparePublicKeyX509Openssl(HcfX509CertificateSpi *self, const CfBlob *pubKey, bool *out)
514 {
515     CfResult res = CF_SUCCESS;
516     CfBlob cfBlobDataSelf = { 0, NULL };
517 
518     if (pubKey != NULL) {
519         if (pubKey->size == 0 || pubKey->data == NULL) {
520             LOGE("invalid param!");
521             return CF_INVALID_PARAMS;
522         }
523         res = GetCertPubKey(self, &cfBlobDataSelf);
524         if (res != CF_SUCCESS) {
525             LOGE("x509Cert GetCertPubKey failed!");
526             return CF_ERR_CRYPTO_OPERATION;
527         }
528 
529         if (cfBlobDataSelf.size != pubKey->size) {
530             *out = false;
531             CfBlobDataFree(&cfBlobDataSelf);
532             return res;
533         }
534         if (memcmp(cfBlobDataSelf.data, pubKey->data, cfBlobDataSelf.size) != 0) {
535             *out = false;
536         }
537         CfBlobDataFree(&cfBlobDataSelf);
538     }
539 
540     return res;
541 }
542 
ComparePublicKeyAlgOidX509Openssl(HcfX509CertificateSpi * self,const CfBlob * publicKeyAlgOid,bool * out)543 static CfResult ComparePublicKeyAlgOidX509Openssl(HcfX509CertificateSpi *self, const CfBlob *publicKeyAlgOid, bool *out)
544 {
545     CfResult res = CF_SUCCESS;
546     CfBlob cfBlobDataSelf = { 0 };
547 
548     if (publicKeyAlgOid != NULL) {
549         if (!CfBlobIsStr(publicKeyAlgOid)) {
550             LOGE("publicKeyAlgOid is not string!");
551             return CF_INVALID_PARAMS;
552         }
553         res = GetSubjectPubKeyAlgOidX509Openssl(self, &cfBlobDataSelf);
554         if (res != CF_SUCCESS) {
555             LOGE("x509Cert ComparePublicKeyAlgOidX509Openssl failed!");
556             return res;
557         }
558 
559         if (cfBlobDataSelf.size != publicKeyAlgOid->size ||
560             strncmp((const char *)cfBlobDataSelf.data, (const char *)publicKeyAlgOid->data, cfBlobDataSelf.size) != 0) {
561             *out = false;
562         }
563         CfFree(cfBlobDataSelf.data);
564     }
565 
566     return res;
567 }
568 
GetVersionX509Openssl(HcfX509CertificateSpi * self)569 static long GetVersionX509Openssl(HcfX509CertificateSpi *self)
570 {
571     if (self == NULL) {
572         LOGE("The input data is null!");
573         return INVALID_VERSION;
574     }
575     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
576         LOGE("Input wrong class type!");
577         return INVALID_VERSION;
578     }
579     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
580     X509 *x509 = realCert->x509;
581     if (x509 == NULL) {
582         LOGE("X509 cert is null!");
583         return INVALID_VERSION;
584     }
585     return X509_get_version(x509) + 1;
586 }
587 
GetSerialNumberX509Openssl(HcfX509CertificateSpi * self,CfBlob * out)588 static CfResult GetSerialNumberX509Openssl(HcfX509CertificateSpi *self, CfBlob *out)
589 {
590     if ((self == NULL) || (out == NULL)) {
591         LOGE("The input data is null!");
592         return CF_INVALID_PARAMS;
593     }
594     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
595         LOGE("Input wrong class type!");
596         return CF_INVALID_PARAMS;
597     }
598 
599     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
600     X509 *x509 = realCert->x509;
601 
602     const ASN1_INTEGER *serial = X509_get0_serialNumber(x509);
603     if (serial == NULL) {
604         LOGE("Failed to get serial number!");
605         return CF_ERR_CRYPTO_OPERATION;
606     }
607 
608     unsigned char *serialNumBytes = NULL;
609     int serialNumLen = i2d_ASN1_INTEGER((ASN1_INTEGER *)serial, &serialNumBytes);
610     if (serialNumLen <= SERIAL_NUMBER_HEDER_SIZE) {
611         CfPrintOpensslError();
612         LOGE("Failed to get serialNumLen!");
613         return CF_ERR_CRYPTO_OPERATION;
614     }
615 
616     CfResult ret = DeepCopyDataToOut((const char *)(serialNumBytes + SERIAL_NUMBER_HEDER_SIZE),
617         (uint32_t)(serialNumLen - SERIAL_NUMBER_HEDER_SIZE), out);
618     OPENSSL_free(serialNumBytes);
619     return ret;
620 }
621 
GetIssuerDNX509Openssl(HcfX509CertificateSpi * self,CfBlob * out)622 static CfResult GetIssuerDNX509Openssl(HcfX509CertificateSpi *self, CfBlob *out)
623 {
624     if ((self == NULL) || (out == NULL)) {
625         LOGE("[Get issuerDN openssl] The input data is null!");
626         return CF_INVALID_PARAMS;
627     }
628     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
629         LOGE("Input wrong class type!");
630         return CF_INVALID_PARAMS;
631     }
632     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
633     X509 *x509 = realCert->x509;
634 
635     X509_NAME *issuerName = X509_get_issuer_name(x509);
636     if (issuerName == NULL) {
637         LOGE("Failed to get x509 issuerName in openssl!");
638         CfPrintOpensslError();
639         return CF_ERR_CRYPTO_OPERATION;
640     }
641     char *issuer = (char *)CfMalloc(HCF_MAX_STR_LEN + 1, 0);
642     if (issuer == NULL) {
643         LOGE("Failed to malloc for issuer buffer!");
644         return CF_ERR_MALLOC;
645     }
646 
647     CfResult res = CF_SUCCESS;
648     do {
649         X509_NAME_oneline(issuerName, issuer, HCF_MAX_STR_LEN);
650         size_t length = strlen(issuer) + 1;
651         if (length == 1) {
652             LOGE("Failed to get oneline issuerName in openssl!");
653             res = CF_ERR_CRYPTO_OPERATION;
654             CfPrintOpensslError();
655             break;
656         }
657         res = DeepCopyDataToOut(issuer, length, out);
658     } while (0);
659     CfFree(issuer);
660     return res;
661 }
662 
GetSubjectDNX509Openssl(HcfX509CertificateSpi * self,CfBlob * out)663 static CfResult GetSubjectDNX509Openssl(HcfX509CertificateSpi *self, CfBlob *out)
664 {
665     if ((self == NULL) || (out == NULL)) {
666         LOGE("[Get subjectDN openssl]The input data is null!");
667         return CF_INVALID_PARAMS;
668     }
669     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
670         LOGE("Input wrong class type!");
671         return CF_INVALID_PARAMS;
672     }
673     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
674     X509 *x509 = realCert->x509;
675 
676     X509_NAME *subjectName = X509_get_subject_name(x509);
677     if (subjectName == NULL) {
678         LOGE("Failed to get x509 subjectName in openssl!");
679         CfPrintOpensslError();
680         return CF_ERR_CRYPTO_OPERATION;
681     }
682     char *subject = (char *)CfMalloc(HCF_MAX_STR_LEN + 1, 0);
683     if (subject == NULL) {
684         LOGE("Failed to malloc for subject buffer!");
685         return CF_ERR_MALLOC;
686     }
687 
688     CfResult res = CF_SUCCESS;
689     do {
690         X509_NAME_oneline(subjectName, subject, HCF_MAX_STR_LEN);
691         size_t length = strlen(subject) + 1;
692         if (length == 1) {
693             LOGE("Failed to get oneline subjectName in openssl!");
694             CfPrintOpensslError();
695             res = CF_ERR_CRYPTO_OPERATION;
696             break;
697         }
698         res = DeepCopyDataToOut(subject, length, out);
699     } while (0);
700     CfFree(subject);
701     return res;
702 }
703 
CopyMemFromBIO(BIO * bio,CfBlob * outBlob)704 static CfResult CopyMemFromBIO(BIO *bio, CfBlob *outBlob)
705 {
706     if (bio == NULL || outBlob == NULL) {
707         LOGE("Invalid input.");
708         return CF_INVALID_PARAMS;
709     }
710     int len = BIO_pending(bio);
711     if (len <= 0) {
712         LOGE("Bio len less than or equal to 0.");
713         return CF_INVALID_PARAMS;
714     }
715     uint8_t *buff = (uint8_t *)CfMalloc(len, 0);
716     if (buff == NULL) {
717         LOGE("Malloc mem for buff fail.");
718         return CF_ERR_MALLOC;
719     }
720     if (BIO_read(bio, buff, len) <= 0) {
721         LOGE("Bio read fail.");
722         CfPrintOpensslError();
723         CfFree(buff);
724         return CF_ERR_CRYPTO_OPERATION;
725     }
726     outBlob->size = len;
727     outBlob->data = buff;
728     return CF_SUCCESS;
729 }
730 
GetSubjectDNX509OpensslEx(HcfX509CertificateSpi * self,CfEncodinigType encodingType,CfBlob * out)731 static CfResult GetSubjectDNX509OpensslEx(HcfX509CertificateSpi *self, CfEncodinigType encodingType, CfBlob *out)
732 {
733     if ((self == NULL) || (out == NULL) || (encodingType != CF_ENCODING_UTF8)) {
734         LOGE("[Get utf8 subjectDN openssl]The input data is null or encodingType is not utf8!");
735         return CF_INVALID_PARAMS;
736     }
737     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
738         LOGE("Input wrong class type!");
739         return CF_INVALID_PARAMS;
740     }
741     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
742     X509 *x509 = realCert->x509;
743 
744     X509_NAME *subjectName = X509_get_subject_name(x509);
745     if (subjectName == NULL) {
746         LOGE("Failed to get x509 subjectName in openssl!");
747         CfPrintOpensslError();
748         return CF_ERR_CRYPTO_OPERATION;
749     }
750     CfResult res = CF_SUCCESS;
751     BIO *bio = BIO_new(BIO_s_mem());
752     if (bio == NULL) {
753         LOGE("BIO new fail.");
754         CfPrintOpensslError();
755         return CF_ERR_CRYPTO_OPERATION;
756     }
757     do {
758         int ret = X509_NAME_print_ex(bio, subjectName, 0, XN_FLAG_SEP_COMMA_PLUS | ASN1_STRFLGS_UTF8_CONVERT);
759         if (ret <= 0) {
760             LOGE("Failed to X509_NAME_print_ex in openssl!");
761             CfPrintOpensslError();
762             res = CF_ERR_CRYPTO_OPERATION;
763             break;
764         }
765         res = CopyMemFromBIO(bio, out);
766         if (res != CF_SUCCESS) {
767             LOGE("CopyMemFromBIO failed!");
768             break;
769         }
770     } while (0);
771     BIO_free(bio);
772     return res;
773 }
774 
GetNotBeforeX509Openssl(HcfX509CertificateSpi * self,CfBlob * outDate)775 static CfResult GetNotBeforeX509Openssl(HcfX509CertificateSpi *self, CfBlob *outDate)
776 {
777     if ((self == NULL) || (outDate == NULL)) {
778         LOGE("Get not before, input is null!");
779         return CF_INVALID_PARAMS;
780     }
781     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
782         LOGE("Get not before, input wrong class type!");
783         return CF_INVALID_PARAMS;
784     }
785     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
786     X509 *x509 = realCert->x509;
787 
788     ASN1_TIME *notBeforeDate = X509_get_notBefore(x509);
789     if (notBeforeDate == NULL) {
790         LOGE("NotBeforeDate is null in x509 cert!");
791         CfPrintOpensslError();
792         return CF_ERR_CRYPTO_OPERATION;
793     }
794     if (ASN1_TIME_normalize(notBeforeDate) != CF_OPENSSL_SUCCESS) {
795         LOGE("Failed to normalize notBeforeDate!");
796         CfPrintOpensslError();
797         return CF_ERR_CRYPTO_OPERATION;
798     }
799     const char *date = (const char *)(notBeforeDate->data);
800     if ((date == NULL) || (strlen(date) > HCF_MAX_STR_LEN)) {
801         LOGE("Failed to get notBeforeDate data!");
802         return CF_ERR_CRYPTO_OPERATION;
803     }
804     uint32_t length = strlen(date) + 1;
805     return DeepCopyDataToOut(date, length, outDate);
806 }
807 
GetNotAfterX509Openssl(HcfX509CertificateSpi * self,CfBlob * outDate)808 static CfResult GetNotAfterX509Openssl(HcfX509CertificateSpi *self, CfBlob *outDate)
809 {
810     if ((self == NULL) || (outDate == NULL)) {
811         LOGE("Get not after, input data is null!");
812         return CF_INVALID_PARAMS;
813     }
814     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
815         LOGE("Get not after, input wrong class type!");
816         return CF_INVALID_PARAMS;
817     }
818     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
819     X509 *x509 = realCert->x509;
820 
821     ASN1_TIME *notAfterDate = X509_get_notAfter(x509);
822     if (notAfterDate == NULL) {
823         LOGE("NotAfterDate is null in x509 cert!");
824         CfPrintOpensslError();
825         return CF_ERR_CRYPTO_OPERATION;
826     }
827     if (ASN1_TIME_normalize(notAfterDate) != CF_OPENSSL_SUCCESS) {
828         LOGE("Failed to normalize notAfterDate!");
829         CfPrintOpensslError();
830         return CF_ERR_CRYPTO_OPERATION;
831     }
832     const char *date = (const char *)(notAfterDate->data);
833     if ((date == NULL) || (strlen(date) > HCF_MAX_STR_LEN)) {
834         LOGE("Failed to get notAfterDate data!");
835         return CF_ERR_CRYPTO_OPERATION;
836     }
837     uint32_t length = strlen(date) + 1;
838     return DeepCopyDataToOut(date, length, outDate);
839 }
840 
GetSignatureX509Openssl(HcfX509CertificateSpi * self,CfBlob * sigOut)841 static CfResult GetSignatureX509Openssl(HcfX509CertificateSpi *self, CfBlob *sigOut)
842 {
843     if ((self == NULL) || (sigOut == NULL)) {
844         LOGE("The input data is null!");
845         return CF_INVALID_PARAMS;
846     }
847     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
848         LOGE("Input wrong class type!");
849         return CF_INVALID_PARAMS;
850     }
851     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
852     X509 *x509 = realCert->x509;
853 
854     const ASN1_BIT_STRING *signature = NULL;
855     X509_get0_signature(&signature, NULL, x509);
856     if ((signature == NULL) || (signature->length == 0) || (signature->length > HCF_MAX_BUFFER_LEN)) {
857         LOGE("Failed to get x509 signature in openssl!");
858         CfPrintOpensslError();
859         return CF_ERR_CRYPTO_OPERATION;
860     }
861     sigOut->data = (uint8_t *)CfMalloc(signature->length, 0);
862     if (sigOut->data == NULL) {
863         LOGE("Failed to malloc for signature data!");
864         return CF_ERR_MALLOC;
865     }
866     (void)memcpy_s(sigOut->data, signature->length, signature->data, signature->length);
867     sigOut->size = signature->length;
868     return CF_SUCCESS;
869 }
870 
GetSigAlgNameX509Openssl(HcfX509CertificateSpi * self,CfBlob * outName)871 static CfResult GetSigAlgNameX509Openssl(HcfX509CertificateSpi *self, CfBlob *outName)
872 {
873     if ((self == NULL) || (outName == NULL)) {
874         LOGE("[GetSigAlgName openssl] The input data is null!");
875         return CF_INVALID_PARAMS;
876     }
877     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
878         LOGE("[GetSigAlgName openssl] Input wrong class type!");
879         return CF_INVALID_PARAMS;
880     }
881     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
882     X509 *x509 = realCert->x509;
883 
884     const X509_ALGOR *alg = NULL;
885     X509_get0_signature(NULL, &alg, x509);
886     const ASN1_OBJECT *oidObj = NULL;
887     X509_ALGOR_get0(&oidObj, NULL, NULL, alg);
888     char oidStr[OID_STR_MAX_LEN] = { 0 };
889     int32_t resLen = OBJ_obj2txt(oidStr, OID_STR_MAX_LEN, oidObj, 1);
890     if ((resLen <= 0) || (resLen >= OID_STR_MAX_LEN)) {
891         LOGE("Failed to convert x509 object to text!");
892         CfPrintOpensslError();
893         return CF_ERR_CRYPTO_OPERATION;
894     }
895     const char *algName = GetAlgorithmName(oidStr);
896     if (algName == NULL) {
897         return CF_ERR_CRYPTO_OPERATION;
898     }
899     uint32_t len = strlen(algName) + 1;
900     return DeepCopyDataToOut(algName, len, outName);
901 }
902 
GetSigAlgOidX509Openssl(HcfX509CertificateSpi * self,CfBlob * out)903 static CfResult GetSigAlgOidX509Openssl(HcfX509CertificateSpi *self, CfBlob *out)
904 {
905     if ((self == NULL) || (out == NULL)) {
906         LOGE("[GetSigAlgOID openssl] The input data is null!");
907         return CF_INVALID_PARAMS;
908     }
909     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
910         LOGE("[GetSigAlgOID openssl] Input wrong class type!");
911         return CF_INVALID_PARAMS;
912     }
913     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
914     X509 *x509 = realCert->x509;
915 
916     const X509_ALGOR *alg = NULL;
917     X509_get0_signature(NULL, &alg, x509);
918     const ASN1_OBJECT *oid = NULL;
919     X509_ALGOR_get0(&oid, NULL, NULL, alg);
920     char algOid[OID_STR_MAX_LEN] = { 0 };
921     int32_t resLen = OBJ_obj2txt(algOid, OID_STR_MAX_LEN, oid, 1);
922     if ((resLen <= 0) || (resLen >= OID_STR_MAX_LEN)) {
923         LOGE("Failed to convert x509 object to text!");
924         CfPrintOpensslError();
925         return CF_ERR_CRYPTO_OPERATION;
926     }
927     uint32_t len = strlen(algOid) + 1;
928     return DeepCopyDataToOut(algOid, len, out);
929 }
930 
GetSigAlgParamsX509Openssl(HcfX509CertificateSpi * self,CfBlob * sigAlgParamsOut)931 static CfResult GetSigAlgParamsX509Openssl(HcfX509CertificateSpi *self, CfBlob *sigAlgParamsOut)
932 {
933     if ((self == NULL) || (sigAlgParamsOut == NULL)) {
934         LOGE("[GetSigAlgParams openssl] The input data is null!");
935         return CF_INVALID_PARAMS;
936     }
937     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
938         LOGE("[GetSigAlgParams openssl] Input wrong class type!");
939         return CF_INVALID_PARAMS;
940     }
941     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
942     X509 *x509 = realCert->x509;
943 
944     const X509_ALGOR *alg = NULL;
945     X509_get0_signature(NULL, &alg, x509);
946     int32_t paramType = 0;
947     const void *paramValue = NULL;
948     X509_ALGOR_get0(NULL, &paramType, &paramValue, alg);
949     if (paramType == V_ASN1_UNDEF) {
950         LOGE("get_X509_ALGOR_parameter, no parameters!");
951         return CF_NOT_SUPPORT;
952     }
953     ASN1_TYPE *param = ASN1_TYPE_new();
954     if (param == NULL) {
955         LOGE("Failed to malloc for asn1 type data!");
956         return CF_ERR_MALLOC;
957     }
958     if (ASN1_TYPE_set1(param, paramType, paramValue) != CF_OPENSSL_SUCCESS) {
959         LOGE("Failed to set asn1 type in openssl!");
960         CfPrintOpensslError();
961         ASN1_TYPE_free(param);
962         return CF_ERR_CRYPTO_OPERATION;
963     }
964     unsigned char *out = NULL;
965     int32_t len = i2d_ASN1_TYPE(param, &out);
966     if (len <= 0 || out == NULL) {
967         LOGE("Failed to convert ASN1_TYPE!");
968         CfPrintOpensslError();
969         ASN1_TYPE_free(param);
970         return CF_ERR_CRYPTO_OPERATION;
971     }
972     ASN1_TYPE_free(param);
973     CfResult res = DeepCopyDataToOut((const char *)out, len, sigAlgParamsOut);
974     OPENSSL_free(out);
975     return res;
976 }
977 
ConvertAsn1String2BoolArray(const ASN1_BIT_STRING * string,CfBlob * boolArr)978 static CfResult ConvertAsn1String2BoolArray(const ASN1_BIT_STRING *string, CfBlob *boolArr)
979 {
980     uint32_t length = ASN1_STRING_length(string) * CHAR_TO_BIT_LEN;
981     if ((uint32_t)(string->flags) & ASN1_STRING_FLAG_BITS_LEFT) {
982         length -= (uint32_t)(string->flags) & FLAG_BIT_LEFT_NUM;
983     }
984     boolArr->data = (uint8_t *)CfMalloc(length, 0);
985     if (boolArr->data == NULL) {
986         LOGE("Failed to malloc for bit array data!");
987         return CF_ERR_MALLOC;
988     }
989     for (uint32_t i = 0; i < length; i++) {
990         boolArr->data[i] = ASN1_BIT_STRING_get_bit(string, i);
991     }
992     boolArr->size = length;
993     return CF_SUCCESS;
994 }
995 
GetKeyUsageX509Openssl(HcfX509CertificateSpi * self,CfBlob * boolArr)996 static CfResult GetKeyUsageX509Openssl(HcfX509CertificateSpi *self, CfBlob *boolArr)
997 {
998     if ((self == NULL) || (boolArr == NULL)) {
999         LOGE("[GetKeyUsage openssl] The input data is null!");
1000         return CF_INVALID_PARAMS;
1001     }
1002     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
1003         LOGE("Input wrong class type!");
1004         return CF_INVALID_PARAMS;
1005     }
1006     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
1007     X509 *x509 = realCert->x509;
1008 
1009     ASN1_BIT_STRING *keyUsage = (ASN1_BIT_STRING *)X509_get_ext_d2i(x509, NID_key_usage, NULL, NULL);
1010     if ((keyUsage == NULL) || (keyUsage->length <= 0) || (keyUsage->length >= HCF_MAX_STR_LEN)) {
1011         if (keyUsage != NULL) {
1012             ASN1_BIT_STRING_free(keyUsage);
1013         }
1014         LOGE("Failed to get x509 keyUsage in openssl!");
1015         CfPrintOpensslError();
1016         return CF_ERR_CRYPTO_OPERATION;
1017     }
1018     CfResult res = ConvertAsn1String2BoolArray(keyUsage, boolArr);
1019     ASN1_BIT_STRING_free(keyUsage);
1020     return res;
1021 }
1022 
DeepCopyExtendedKeyUsage(const STACK_OF (ASN1_OBJECT)* extUsage,int32_t i,CfArray * keyUsageOut)1023 static CfResult DeepCopyExtendedKeyUsage(const STACK_OF(ASN1_OBJECT) *extUsage,
1024     int32_t i, CfArray *keyUsageOut)
1025 {
1026     char usage[OID_STR_MAX_LEN] = { 0 };
1027     int32_t resLen = OBJ_obj2txt(usage, OID_STR_MAX_LEN, sk_ASN1_OBJECT_value(extUsage, i), 1);
1028     if ((resLen <= 0) || (resLen >= OID_STR_MAX_LEN)) {
1029         LOGE("Failed to convert x509 object to text!");
1030         CfPrintOpensslError();
1031         return CF_ERR_CRYPTO_OPERATION;
1032     }
1033     uint32_t len = strlen(usage) + 1;
1034     keyUsageOut->data[i].data = (uint8_t *)CfMalloc(len, 0);
1035     if (keyUsageOut->data[i].data == NULL) {
1036         LOGE("Failed to malloc for key usage!");
1037         return CF_ERR_MALLOC;
1038     }
1039     (void)memcpy_s(keyUsageOut->data[i].data, len, usage, len);
1040     keyUsageOut->data[i].size = len;
1041     return CF_SUCCESS;
1042 }
1043 
GetExtendedKeyUsageX509Openssl(HcfX509CertificateSpi * self,CfArray * keyUsageOut)1044 static CfResult GetExtendedKeyUsageX509Openssl(HcfX509CertificateSpi *self, CfArray *keyUsageOut)
1045 {
1046     if ((self == NULL) || (keyUsageOut == NULL)) {
1047         LOGE("The input data is null!");
1048         return CF_INVALID_PARAMS;
1049     }
1050     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
1051         LOGE("Input wrong class type!");
1052         return CF_INVALID_PARAMS;
1053     }
1054     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
1055     X509 *x509 = realCert->x509;
1056     STACK_OF(ASN1_OBJECT) *extUsage = X509_get_ext_d2i(x509, NID_ext_key_usage, NULL, NULL);
1057     if (extUsage == NULL) {
1058         LOGE("Failed to get x509 extended keyUsage in openssl!");
1059         return CF_ERR_CRYPTO_OPERATION;
1060     }
1061     CfResult res = CF_SUCCESS;
1062     do {
1063         int32_t size = sk_ASN1_OBJECT_num(extUsage);
1064         if (size <= 0) {
1065             LOGE("The extended key usage size in openssl is invalid!");
1066             CfPrintOpensslError();
1067             res = CF_ERR_CRYPTO_OPERATION;
1068             break;
1069         }
1070         int32_t blobSize = sizeof(CfBlob) * size;
1071         keyUsageOut->data = (CfBlob *)CfMalloc(blobSize, 0);
1072         if (keyUsageOut->data == NULL) {
1073             LOGE("Failed to malloc for keyUsageOut array!");
1074             res = CF_ERR_MALLOC;
1075             break;
1076         }
1077         keyUsageOut->count = (uint32_t)size;
1078         for (int32_t i = 0; i < size; ++i) {
1079             res = DeepCopyExtendedKeyUsage(extUsage, i, keyUsageOut);
1080             if (res != CF_SUCCESS) {
1081                 LOGE("Falied to copy extended key usage!");
1082                 break;
1083             }
1084         }
1085     } while (0);
1086     if (res != CF_SUCCESS) {
1087         CfArrayDataClearAndFree(keyUsageOut);
1088     }
1089     sk_ASN1_OBJECT_pop_free(extUsage, ASN1_OBJECT_free);
1090     return res;
1091 }
1092 
GetBasicConstraintsX509Openssl(HcfX509CertificateSpi * self)1093 static int32_t GetBasicConstraintsX509Openssl(HcfX509CertificateSpi *self)
1094 {
1095     if (self == NULL) {
1096         LOGE("The input data is null!");
1097         return INVALID_CONSTRAINTS_LEN;
1098     }
1099     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
1100         LOGE("Input wrong class type!");
1101         return INVALID_CONSTRAINTS_LEN;
1102     }
1103     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
1104     X509 *x509 = realCert->x509;
1105     if (x509 == NULL) {
1106         LOGE("X509 cert is null!");
1107         return INVALID_CONSTRAINTS_LEN;
1108     }
1109     BASIC_CONSTRAINTS *constraints = (BASIC_CONSTRAINTS *)X509_get_ext_d2i(x509, NID_basic_constraints, NULL, NULL);
1110     if (constraints == NULL) {
1111         LOGE("Failed to get basic constraints in openssl!");
1112         return INVALID_CONSTRAINTS_LEN;
1113     }
1114     /* Path len is only valid for CA cert. */
1115     if (!constraints->ca) {
1116         BASIC_CONSTRAINTS_free(constraints);
1117         LOGI("The cert in not a CA!");
1118         return INVALID_CONSTRAINTS_LEN;
1119     }
1120     if ((constraints->pathlen == NULL) || (constraints->pathlen->type == V_ASN1_NEG_INTEGER)) {
1121         BASIC_CONSTRAINTS_free(constraints);
1122         LOGE("The cert path len is negative in openssl!");
1123         return INVALID_CONSTRAINTS_LEN;
1124     }
1125     long pathLen = ASN1_INTEGER_get(constraints->pathlen);
1126     if ((pathLen < 0) || (pathLen > INT_MAX)) {
1127         BASIC_CONSTRAINTS_free(constraints);
1128         LOGE("Get the overflow path length in openssl!");
1129         return INVALID_CONSTRAINTS_LEN;
1130     }
1131     BASIC_CONSTRAINTS_free(constraints);
1132     return (int32_t)pathLen;
1133 }
1134 
DeepCopyAlternativeNames(const STACK_OF (GENERAL_NAME)* altNames,int32_t i,CfArray * outName)1135 static CfResult DeepCopyAlternativeNames(const STACK_OF(GENERAL_NAME) *altNames, int32_t i, CfArray *outName)
1136 {
1137     GENERAL_NAME *general = sk_GENERAL_NAME_value(altNames, i);
1138     int32_t generalType = 0;
1139     ASN1_STRING *ans1Str = GENERAL_NAME_get0_value(general, &generalType);
1140     const char *str = (const char *)ASN1_STRING_get0_data(ans1Str);
1141     if ((str == NULL) || (strlen(str) > HCF_MAX_STR_LEN)) {
1142         LOGE("Failed to get x509 altNames string in openssl!");
1143         CfPrintOpensslError();
1144         return CF_ERR_CRYPTO_OPERATION;
1145     }
1146     uint32_t nameLen = strlen(str) + 1;
1147     outName->data[i].data = (uint8_t *)CfMalloc(nameLen, 0);
1148     if (outName->data[i].data == NULL) {
1149         LOGE("Failed to malloc for outName!");
1150         return CF_ERR_MALLOC;
1151     }
1152     (void)memcpy_s(outName->data[i].data, nameLen, str, nameLen);
1153     outName->data[i].size = nameLen;
1154     return CF_SUCCESS;
1155 }
1156 
GetSubjectAltNamesX509Openssl(HcfX509CertificateSpi * self,CfArray * outName)1157 static CfResult GetSubjectAltNamesX509Openssl(HcfX509CertificateSpi *self, CfArray *outName)
1158 {
1159     if ((self == NULL) || (outName == NULL)) {
1160         LOGE("[GetSubjectAltNames openssl] The input data is null!");
1161         return CF_INVALID_PARAMS;
1162     }
1163     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
1164         LOGE("Input wrong class type!");
1165         return CF_INVALID_PARAMS;
1166     }
1167     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
1168     X509 *x509 = realCert->x509;
1169     STACK_OF(GENERAL_NAME) *subjectAltName = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, NULL);
1170     if (subjectAltName == NULL) {
1171         LOGE("Failed to get subjectAltName in openssl!");
1172         CfPrintOpensslError();
1173         return CF_ERR_CRYPTO_OPERATION;
1174     }
1175     CfResult res = CF_SUCCESS;
1176     do {
1177         int32_t size = sk_GENERAL_NAME_num(subjectAltName);
1178         if (size <= 0) {
1179             LOGE("The subjectAltName number in openssl is invalid!");
1180             CfPrintOpensslError();
1181             res = CF_ERR_CRYPTO_OPERATION;
1182             break;
1183         }
1184         int32_t blobSize = sizeof(CfBlob) * size;
1185         outName->data = (CfBlob *)CfMalloc(blobSize, 0);
1186         if (outName->data == NULL) {
1187             LOGE("Failed to malloc for subjectAltName array!");
1188             res = CF_ERR_MALLOC;
1189             break;
1190         }
1191         outName->count = (uint32_t)size;
1192         for (int32_t i = 0; i < size; ++i) {
1193             res = DeepCopyAlternativeNames(subjectAltName, i, outName);
1194             if (res != CF_SUCCESS) {
1195                 LOGE("Falied to copy subjectAltName!");
1196                 break;
1197             }
1198         }
1199     } while (0);
1200     if (res != CF_SUCCESS) {
1201         CfArrayDataClearAndFree(outName);
1202     }
1203     GENERAL_NAMES_free(subjectAltName);
1204     return res;
1205 }
1206 
GetIssuerAltNamesX509Openssl(HcfX509CertificateSpi * self,CfArray * outName)1207 static CfResult GetIssuerAltNamesX509Openssl(HcfX509CertificateSpi *self, CfArray *outName)
1208 {
1209     if ((self == NULL) || (outName == NULL)) {
1210         LOGE("[GetIssuerAltNames openssl] The input data is null!");
1211         return CF_INVALID_PARAMS;
1212     }
1213     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
1214         LOGE("Input wrong class type!");
1215         return CF_INVALID_PARAMS;
1216     }
1217     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
1218     X509 *x509 = realCert->x509;
1219     STACK_OF(GENERAL_NAME) *issuerAltName = X509_get_ext_d2i(x509, NID_issuer_alt_name, NULL, NULL);
1220     if (issuerAltName == NULL) {
1221         LOGE("Failed to get issuerAltName in openssl!");
1222         CfPrintOpensslError();
1223         return CF_ERR_CRYPTO_OPERATION;
1224     }
1225     CfResult res = CF_SUCCESS;
1226     do {
1227         int32_t size = sk_GENERAL_NAME_num(issuerAltName);
1228         if (size <= 0) {
1229             LOGE("The issuerAltName number in openssl is invalid!");
1230             CfPrintOpensslError();
1231             res = CF_ERR_CRYPTO_OPERATION;
1232             break;
1233         }
1234         int32_t blobSize = sizeof(CfBlob) * size;
1235         outName->data = (CfBlob *)CfMalloc(blobSize, 0);
1236         if (outName->data == NULL) {
1237             LOGE("Failed to malloc for issuerAltName array!");
1238             res = CF_ERR_MALLOC;
1239             break;
1240         }
1241         outName->count = (uint32_t)size;
1242         for (int32_t i = 0; i < size; ++i) {
1243             res = DeepCopyAlternativeNames(issuerAltName, i, outName);
1244             if (res != CF_SUCCESS) {
1245                 LOGE("Falied to copy issuerAltName!");
1246                 break;
1247             }
1248         }
1249     } while (0);
1250     if (res != CF_SUCCESS) {
1251         CfArrayDataClearAndFree(outName);
1252     }
1253     GENERAL_NAMES_free(issuerAltName);
1254     return res;
1255 }
1256 
ToStringX509Openssl(HcfX509CertificateSpi * self,CfBlob * out)1257 static CfResult ToStringX509Openssl(HcfX509CertificateSpi *self, CfBlob *out)
1258 {
1259     if ((self == NULL) || (out == NULL)) {
1260         LOGE("The input data is null!");
1261         return CF_INVALID_PARAMS;
1262     }
1263     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
1264         LOGE("Input wrong class type!");
1265         return CF_INVALID_PARAMS;
1266     }
1267     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
1268     BIO *bio = BIO_new(BIO_s_mem());
1269     if (bio == NULL) {
1270         LOGE("BIO_new error");
1271         return CF_ERR_MALLOC;
1272     }
1273     int len = X509_print(bio, realCert->x509);
1274     if (len <= 0) {
1275         LOGE("X509_print error");
1276         BIO_free(bio);
1277         return CF_ERR_CRYPTO_OPERATION;
1278     }
1279     BUF_MEM *bufMem = NULL;
1280     if (BIO_get_mem_ptr(bio, &bufMem) > 0 && bufMem != NULL) {
1281         CfResult res = DeepCopyDataToOut(bufMem->data, bufMem->length, out);
1282         BIO_free(bio);
1283         return res;
1284     }
1285 
1286     BIO_free(bio);
1287     LOGE("BIO_get_mem_ptr error");
1288     return CF_ERR_CRYPTO_OPERATION;
1289 }
1290 
HashCodeX509Openssl(HcfX509CertificateSpi * self,CfBlob * out)1291 static CfResult HashCodeX509Openssl(HcfX509CertificateSpi *self, CfBlob *out)
1292 {
1293     if ((self == NULL) || (out == NULL)) {
1294         LOGE("The input data is null!");
1295         return CF_INVALID_PARAMS;
1296     }
1297     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
1298         LOGE("Input wrong class type!");
1299         return CF_INVALID_PARAMS;
1300     }
1301     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
1302     X509 *x509 = realCert->x509;
1303 
1304     unsigned char *buf = NULL;
1305     int len = i2d_X509(x509, &buf);
1306     if (len < 0 || buf == NULL) {
1307         LOGE("i2d_X509 error");
1308         return CF_ERR_CRYPTO_OPERATION;
1309     }
1310 
1311     out->data = (uint8_t *)CfMalloc(SHA256_DIGEST_LENGTH, 0);
1312     if (out->data == NULL) {
1313         LOGE("CfMalloc error");
1314         OPENSSL_free(buf);
1315         return CF_ERR_MALLOC;
1316     }
1317     if (SHA256(buf, len, out->data) == NULL) {
1318         LOGE("Compute sha256 error");
1319         CfFree(out->data);
1320         OPENSSL_free(buf);
1321         return CF_ERR_CRYPTO_OPERATION;
1322     }
1323     out->size = SHA256_DIGEST_LENGTH;
1324     OPENSSL_free(buf);
1325     return CF_SUCCESS;
1326 }
1327 
GetExtensionsObjectX509Openssl(HcfX509CertificateSpi * self,CfBlob * out)1328 static CfResult GetExtensionsObjectX509Openssl(HcfX509CertificateSpi *self, CfBlob *out)
1329 {
1330     if ((self == NULL) || (out == NULL)) {
1331         LOGE("The input data is null!");
1332         return CF_INVALID_PARAMS;
1333     }
1334     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
1335         LOGE("Input wrong class type!");
1336         return CF_INVALID_PARAMS;
1337     }
1338     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
1339     if (realCert->x509 == NULL) {
1340         LOGE("X509 cert is null!");
1341         return CF_INVALID_PARAMS;
1342     }
1343     unsigned char *extensions = NULL;
1344     int len = i2d_X509_EXTENSIONS(X509_get0_extensions(realCert->x509), &extensions);
1345     if (len <= 0 || extensions == NULL) {
1346         LOGE("i2d_X509_EXTENSIONS error");
1347         return CF_ERR_CRYPTO_OPERATION;
1348     }
1349 
1350     out->data = (uint8_t *)CfMalloc(len, 0);
1351     if (out->data == NULL) {
1352         LOGE("Failed to malloc for extensions data!");
1353         OPENSSL_free(extensions);
1354         return CF_ERR_MALLOC;
1355     }
1356     (void)memcpy_s(out->data, len, extensions, len);
1357     OPENSSL_free(extensions);
1358     out->size = len;
1359     return CF_SUCCESS;
1360 }
1361 
MatchPart1(HcfX509CertificateSpi * self,const HcfX509CertMatchParams * matchParams,bool * out)1362 static CfResult MatchPart1(HcfX509CertificateSpi *self, const HcfX509CertMatchParams *matchParams, bool *out)
1363 {
1364     CfResult res = CF_SUCCESS;
1365     *out = true;
1366 
1367     // x509Cert
1368     res = CompareCertBlobX509Openssl(self, matchParams->x509Cert, out);
1369     if (res != CF_SUCCESS || (*out == false)) {
1370         LOGE("Failed to CompareCertBlob!");
1371         return res;
1372     }
1373     // subject
1374     res = CompareNameObjectX509Openssl(self, matchParams->subject, NAME_TYPE_SUBJECT, out);
1375     if (res != CF_SUCCESS || (*out == false)) {
1376         LOGE("Failed to CompareSubject!");
1377         return res;
1378     }
1379     // validDate
1380     if (matchParams->validDate != NULL) {
1381         if (!CfBlobIsStr(matchParams->validDate)) {
1382             LOGE("Invalid param!");
1383             return CF_INVALID_PARAMS;
1384         }
1385         res = CheckValidityWithDateX509Openssl(self, (const char *)matchParams->validDate->data);
1386         if ((res == CF_ERR_CERT_NOT_YET_VALID) || (res == CF_ERR_CERT_HAS_EXPIRED)) {
1387             *out = false;
1388             return CF_SUCCESS;
1389         }
1390         if (res != CF_SUCCESS) {
1391             LOGE("Failed to CheckValidityWithDate!");
1392             return res;
1393         }
1394     }
1395     // issuer
1396     res = CompareNameObjectX509Openssl(self, matchParams->issuer, NAME_TYPE_ISSUER, out);
1397     if (res != CF_SUCCESS || (*out == false)) {
1398         LOGE("Failed to CompareIssuer!");
1399         return res;
1400     }
1401     return res;
1402 }
1403 
MatchPart2(HcfX509CertificateSpi * self,const HcfX509CertMatchParams * matchParams,bool * out)1404 static CfResult MatchPart2(HcfX509CertificateSpi *self, const HcfX509CertMatchParams *matchParams, bool *out)
1405 {
1406     CfResult res = CF_SUCCESS;
1407     *out = true;
1408 
1409     // keyUsage
1410     res = CompareKeyUsageX509Openssl(self, matchParams->keyUsage, out);
1411     if (res != CF_SUCCESS || (*out == false)) {
1412         LOGE("Failed to CompareKeyUsage!");
1413         return res;
1414     }
1415     // serialNumber
1416     res = CompareSerialNumberX509Openssl(self, matchParams->serialNumber, out);
1417     if (res != CF_SUCCESS || (*out == false)) {
1418         LOGE("Failed to CompareSerialNumber!");
1419         return res;
1420     }
1421     // publicKey
1422     res = ComparePublicKeyX509Openssl(self, matchParams->publicKey, out);
1423     if (res != CF_SUCCESS || (*out == false)) {
1424         LOGE("Failed to ComparePublicKey!");
1425         return res;
1426     }
1427     // publicKeyAlgID
1428     res = ComparePublicKeyAlgOidX509Openssl(self, matchParams->publicKeyAlgID, out);
1429     if (res != CF_SUCCESS || (*out == false)) {
1430         LOGE("Failed to ComparePublicKeyAlgOid!");
1431         return res;
1432     }
1433 
1434     return CF_SUCCESS;
1435 }
1436 
DeepCopySubAltName(const STACK_OF (GENERAL_NAME)* altname,int32_t i,const SubAltNameArray * subAltNameArrayOut)1437 static CfResult DeepCopySubAltName(
1438     const STACK_OF(GENERAL_NAME) * altname, int32_t i, const SubAltNameArray *subAltNameArrayOut)
1439 {
1440     GENERAL_NAME *generalName = sk_GENERAL_NAME_value(altname, i);
1441     unsigned char *derData = NULL;
1442     int derLength = i2d_GENERAL_NAME(generalName, &derData);
1443     if (derLength <= 0 || derData == NULL) {
1444         LOGE("Get generalName failed!");
1445         return CF_ERR_CRYPTO_OPERATION;
1446     }
1447 
1448     SubjectAlternaiveNameData *subAltNameData = &(subAltNameArrayOut->data[i]);
1449     subAltNameData->name.data = CfMalloc(derLength, 0);
1450     if (subAltNameData->name.data == NULL) {
1451         LOGE("Failed to malloc for sub alt name data!");
1452         OPENSSL_free(derData);
1453         return CF_ERR_MALLOC;
1454     }
1455     (void)memcpy_s(subAltNameData->name.data, derLength, derData, derLength);
1456     subAltNameData->name.size = (uint32_t)derLength;
1457     subAltNameData->type = generalName->type;
1458     OPENSSL_free(derData);
1459     return CF_SUCCESS;
1460 }
1461 
IsMatch(SubjectAlternaiveNameData * subAltName,SubAltNameArray * subArraySelf)1462 static bool IsMatch(SubjectAlternaiveNameData *subAltName, SubAltNameArray *subArraySelf)
1463 {
1464     if (subAltName == NULL || subArraySelf == NULL) {
1465         return false;
1466     }
1467     for (uint32_t j = 0; j < subArraySelf->count; j++) {
1468         if (subAltName->type == subArraySelf->data[j].type &&
1469             subAltName->name.size == subArraySelf->data[j].name.size &&
1470             memcmp(subAltName->name.data, subArraySelf->data[j].name.data, subAltName->name.size) == 0) {
1471             return true;
1472         }
1473     }
1474     return false;
1475 }
1476 
CompareSubAltNameMatch(const SubAltNameArray * subArrayInput,SubAltNameArray * subArraySelf,bool matchAll)1477 static bool CompareSubAltNameMatch(const SubAltNameArray *subArrayInput, SubAltNameArray *subArraySelf, bool matchAll)
1478 {
1479     if (matchAll) {
1480         if (subArrayInput->count != subArraySelf->count) {
1481             return false;
1482         }
1483         for (uint32_t i = 0; i < subArrayInput->count; i++) {
1484             if (!IsMatch(&subArrayInput->data[i], subArraySelf)) {
1485                 return false;
1486             }
1487         }
1488         return true;
1489     } else {
1490         for (uint32_t i = 0; i < subArrayInput->count; i++) {
1491             if (IsMatch(&subArrayInput->data[i], subArraySelf)) {
1492                 return true;
1493             }
1494         }
1495         return false;
1496     }
1497 }
1498 
DetailForMinPathLenConstraint(X509 * x509,int minPathLenConstraint)1499 static bool DetailForMinPathLenConstraint(X509 *x509, int minPathLenConstraint)
1500 {
1501     if (minPathLenConstraint == MIN_PATH_LEN_CONSTRAINT) {
1502         X509_EXTENSION *ext = X509_get_ext(x509, X509_get_ext_by_NID(x509, NID_basic_constraints, -1));
1503         if (ext == NULL) {
1504             // when minPathLenConstraint is -2 and get basic_constraints from cert failed is ok, return true.
1505             return true;
1506         }
1507         BASIC_CONSTRAINTS *bc = X509V3_EXT_d2i(ext);
1508         if (bc == NULL) {
1509             return false;
1510         }
1511         bool ca = (bc->ca != 0);
1512         BASIC_CONSTRAINTS_free(bc);
1513         if (!ca) {
1514             return true;
1515         }
1516         return false;
1517     } else if (minPathLenConstraint >= 0) {
1518         X509_EXTENSION *ext = X509_get_ext(x509, X509_get_ext_by_NID(x509, NID_basic_constraints, -1));
1519         if (ext == NULL) {
1520             return false;
1521         }
1522         BASIC_CONSTRAINTS *bc = X509V3_EXT_d2i(ext);
1523         if (bc == NULL) {
1524             return false;
1525         }
1526         bool ca = (bc->ca != 0);
1527         long pathLen = ASN1_INTEGER_get(bc->pathlen);
1528         BASIC_CONSTRAINTS_free(bc);
1529         if (ca && (pathLen >= minPathLenConstraint || pathLen == -1)) {
1530             return true;
1531         }
1532         return false;
1533     } else {
1534         return true;
1535     }
1536 }
1537 
CompareGN2Blob(const GENERAL_NAME * gen,CfBlob * nc)1538 static bool CompareGN2Blob(const GENERAL_NAME *gen, CfBlob *nc)
1539 {
1540     unsigned char *bytes = NULL;
1541     unsigned char *point = NULL;
1542     int32_t len = 0;
1543     bool ret = false;
1544     switch (gen->type) {
1545         case GEN_X400:
1546             len = sizeof(uint8_t) * (gen->d.x400Address->length);
1547             bytes = (unsigned char *)gen->d.x400Address->data;
1548             break;
1549         case GEN_EDIPARTY:
1550             len = i2d_EDIPARTYNAME(gen->d.ediPartyName, &bytes);
1551             point = bytes;
1552             break;
1553         case GEN_OTHERNAME:
1554             len = i2d_OTHERNAME(gen->d.otherName, &bytes);
1555             point = bytes;
1556             break;
1557         case GEN_EMAIL:
1558         case GEN_DNS:
1559         case GEN_URI:
1560             len = i2d_ASN1_IA5STRING(gen->d.ia5, &bytes);
1561             point = bytes;
1562             break;
1563         case GEN_DIRNAME:
1564             len = i2d_X509_NAME(gen->d.dirn, &bytes);
1565             point = bytes;
1566             break;
1567         case GEN_IPADD:
1568             len = i2d_ASN1_OCTET_STRING(gen->d.ip, &bytes);
1569             point = bytes;
1570             break;
1571         case GEN_RID:
1572             len = i2d_ASN1_OBJECT(gen->d.rid, &bytes);
1573             point = bytes;
1574             break;
1575         default:
1576             LOGE("Unknown type.");
1577             break;
1578     }
1579     ret = (len == (int32_t)(nc->size)) && (strncmp((const char *)bytes, (const char *)nc->data, len) == 0);
1580     if (point != NULL) {
1581         OPENSSL_free(point);
1582     }
1583 
1584     return ret;
1585 }
1586 
CompareSubAltNameX509Openssl(HcfX509CertificateSpi * self,const SubAltNameArray * subAltNameArray,const bool matchAllSubAltNames,bool * out)1587 static CfResult CompareSubAltNameX509Openssl(
1588     HcfX509CertificateSpi *self, const SubAltNameArray *subAltNameArray, const bool matchAllSubAltNames, bool *out)
1589 {
1590     if (subAltNameArray == NULL) {
1591         LOGE("The input data is null!");
1592         return CF_SUCCESS;
1593     }
1594     *out = false;
1595     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
1596     X509 *x509 = realCert->x509;
1597     STACK_OF(GENERAL_NAME) *altname = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, NULL);
1598     if (altname == NULL) {
1599         LOGE("Failed to get subject alternative name!");
1600         return CF_SUCCESS;
1601     }
1602     SubAltNameArray subAltNameArrayOut = { 0 };
1603     CfResult res = CF_SUCCESS;
1604     do {
1605         int32_t size = sk_GENERAL_NAME_num(altname);
1606         if (size <= 0) {
1607             LOGE("The altname in openssl is invalid!");
1608             res = CF_ERR_CRYPTO_OPERATION;
1609             break;
1610         }
1611         if ((size_t)size > INT32_MAX / sizeof(SubjectAlternaiveNameData)) {
1612             LOGE("Size is out of max!");
1613             res = CF_ERR_MALLOC;
1614             break;
1615         }
1616         int32_t blobSize = sizeof(SubjectAlternaiveNameData) * size;
1617         subAltNameArrayOut.data = (SubjectAlternaiveNameData *)CfMalloc(blobSize, 0);
1618         if (subAltNameArrayOut.data == NULL) {
1619             LOGE("Failed to malloc for subject alternative name array!");
1620             res = CF_ERR_MALLOC;
1621             break;
1622         }
1623         subAltNameArrayOut.count = (uint32_t)size;
1624         for (int32_t i = 0; i < size; ++i) {
1625             res = DeepCopySubAltName(altname, i, &subAltNameArrayOut);
1626             if (res != CF_SUCCESS) {
1627                 LOGE("Falied to copy subject alternative Name!");
1628                 break;
1629             }
1630         }
1631     } while (0);
1632     if (res == CF_SUCCESS && CompareSubAltNameMatch(subAltNameArray, &subAltNameArrayOut, matchAllSubAltNames)) {
1633         *out = true;
1634     }
1635     GENERAL_NAMES_free(altname);
1636     SubAltNameArrayDataClearAndFree(&subAltNameArrayOut);
1637     return res;
1638 }
1639 
ComparePathLenConstraintX509Openssl(HcfX509CertificateSpi * self,const int32_t minPath,bool * out)1640 static CfResult ComparePathLenConstraintX509Openssl(HcfX509CertificateSpi *self, const int32_t minPath, bool *out)
1641 {
1642     if (minPath < 0 && minPath != MIN_PATH_LEN_CONSTRAINT) {
1643         LOGE("The input minpath is invalid!");
1644         return CF_SUCCESS;
1645     }
1646     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
1647     X509 *x509 = realCert->x509;
1648     if (!DetailForMinPathLenConstraint(x509, minPath)) {
1649         *out = false;
1650     }
1651     return CF_SUCCESS;
1652 }
1653 
CompareExtendKeyUsageX509Openssl(HcfX509CertificateSpi * self,const CfArray * extendKeyUsage,bool * out)1654 static CfResult CompareExtendKeyUsageX509Openssl(HcfX509CertificateSpi *self, const CfArray *extendKeyUsage, bool *out)
1655 {
1656     if (extendKeyUsage == NULL) {
1657         LOGE("The input data is null!");
1658         return CF_SUCCESS;
1659     }
1660     CfArray extendout = { 0 };
1661     CfResult res = GetExtendedKeyUsageX509Openssl(self, &extendout);
1662     if (res == CF_SUCCESS) {
1663         if (!CfArrayContains(extendKeyUsage, &extendout)) {
1664             *out = false;
1665         }
1666     }
1667     CfArrayDataClearAndFree(&extendout);
1668     return res;
1669 }
1670 
CompareNameConstraintsX509Openssl(HcfX509CertificateSpi * self,CfBlob * nameConstraints,bool * out)1671 static CfResult CompareNameConstraintsX509Openssl(HcfX509CertificateSpi *self, CfBlob *nameConstraints, bool *out)
1672 {
1673     if (nameConstraints == NULL) {
1674         LOGE("The input data is null!");
1675         return CF_SUCCESS;
1676     }
1677     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
1678     X509 *x509 = realCert->x509;
1679     NAME_CONSTRAINTS *nc = X509_get_ext_d2i(x509, NID_name_constraints, NULL, NULL);
1680     if (nc == NULL || nc->permittedSubtrees == NULL || nc->excludedSubtrees == NULL) {
1681         if (nc != NULL) {
1682             NAME_CONSTRAINTS_free(nc);
1683         }
1684         LOGE("Failed to get name constraints!");
1685         *out = false;
1686         return CF_SUCCESS;
1687     }
1688 
1689     int i = 0;
1690     for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->permittedSubtrees); i++) {
1691         GENERAL_SUBTREE *tree = NULL;
1692         tree = sk_GENERAL_SUBTREE_value(nc->permittedSubtrees, i);
1693         if (tree != NULL && CompareGN2Blob(tree->base, nameConstraints)) {
1694             NAME_CONSTRAINTS_free(nc);
1695             return CF_SUCCESS;
1696         }
1697     }
1698     for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->excludedSubtrees); i++) {
1699         GENERAL_SUBTREE *tree = NULL;
1700         tree = sk_GENERAL_SUBTREE_value(nc->excludedSubtrees, i);
1701         if (tree != NULL && CompareGN2Blob(tree->base, nameConstraints) == true) {
1702             NAME_CONSTRAINTS_free(nc);
1703             return CF_SUCCESS;
1704         }
1705     }
1706     *out = false;
1707     NAME_CONSTRAINTS_free(nc);
1708     return CF_SUCCESS;
1709 }
1710 
DeepCopyCertPolices(const CERTIFICATEPOLICIES * certPolicesIn,int32_t i,CfArray * certPolices)1711 static CfResult DeepCopyCertPolices(const CERTIFICATEPOLICIES *certPolicesIn, int32_t i, CfArray *certPolices)
1712 {
1713     POLICYINFO *policy = sk_POLICYINFO_value(certPolicesIn, i);
1714     ASN1_OBJECT *policyOid = policy->policyid;
1715     char policyBuff[OID_STR_MAX_LEN] = { 0 };
1716     int32_t resLen = OBJ_obj2txt(policyBuff, OID_STR_MAX_LEN, policyOid, 1);
1717     if ((resLen <= 0) || (resLen >= OID_STR_MAX_LEN)) {
1718         LOGE("Failed to convert x509 object to text!");
1719         CfPrintOpensslError();
1720         return CF_ERR_CRYPTO_OPERATION;
1721     }
1722     uint32_t len = strlen(policyBuff) + 1;
1723     certPolices->data[i].data = (uint8_t *)CfMalloc(len, 0);
1724     if (certPolices->data[i].data == NULL) {
1725         LOGE("Failed to malloc for cert policies!");
1726         return CF_ERR_MALLOC;
1727     }
1728     (void)memcpy_s(certPolices->data[i].data, len, policyBuff, len);
1729     certPolices->data[i].size = len;
1730     return CF_SUCCESS;
1731 }
1732 
CompareCertPolicesX509Openssl(HcfX509CertificateSpi * self,CfArray * certPolices,bool * out)1733 static CfResult CompareCertPolicesX509Openssl(HcfX509CertificateSpi *self, CfArray *certPolices, bool *out)
1734 {
1735     if (certPolices == NULL) {
1736         LOGE("The input data is null!");
1737         return CF_SUCCESS;
1738     }
1739     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
1740     X509 *x509 = realCert->x509;
1741     CERTIFICATEPOLICIES *extCpols = X509_get_ext_d2i(x509, NID_certificate_policies, NULL, NULL);
1742     if (extCpols == NULL) {
1743         LOGE("Failed to get x509 cert polices in openssl!");
1744         *out = false;
1745         return CF_SUCCESS;
1746     }
1747     CfResult res = CF_SUCCESS;
1748     CfArray certPolicesOut = { NULL, 0 };
1749     do {
1750         int32_t size = sk_POLICYINFO_num(extCpols);
1751         if (size <= 0) {
1752             LOGE("The extended key usage size in openssl is invalid!");
1753             res = CF_ERR_CRYPTO_OPERATION;
1754             break;
1755         }
1756         if ((size_t)size > INT32_MAX / sizeof(CfBlob)) {
1757             LOGE("Size is out of max!");
1758             res = CF_ERR_MALLOC;
1759             break;
1760         }
1761         int32_t blobSize = sizeof(CfBlob) * size;
1762         certPolicesOut.data = (CfBlob *)CfMalloc(blobSize, 0);
1763         if (certPolicesOut.data == NULL) {
1764             LOGE("Failed to malloc for certPolicesOut array!");
1765             res = CF_ERR_MALLOC;
1766             break;
1767         }
1768         certPolicesOut.count = (uint32_t)size;
1769         for (int32_t i = 0; i < size; ++i) {
1770             res = DeepCopyCertPolices(extCpols, i, &certPolicesOut);
1771             if (res != CF_SUCCESS) {
1772                 LOGE("Falied to copy cert polices!");
1773                 break;
1774             }
1775         }
1776     } while (0);
1777     if (res == CF_SUCCESS && !CfArrayContains(certPolices, &certPolicesOut)) {
1778         *out = false;
1779     }
1780     CERTIFICATEPOLICIES_free(extCpols);
1781     CfArrayDataClearAndFree(&certPolicesOut);
1782     return res;
1783 }
1784 
ComparePrivateKeyValidX509Openssl(HcfX509CertificateSpi * self,CfBlob * privateKeyValid,bool * out)1785 static CfResult ComparePrivateKeyValidX509Openssl(HcfX509CertificateSpi *self, CfBlob *privateKeyValid, bool *out)
1786 {
1787     if (privateKeyValid == NULL) {
1788         LOGE("The input data is null!");
1789         return CF_SUCCESS;
1790     }
1791     *out = false;
1792     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
1793     X509 *x509 = realCert->x509;
1794     PKEY_USAGE_PERIOD *pKeyValid = X509_get_ext_d2i(x509, NID_private_key_usage_period, NULL, NULL);
1795     if (pKeyValid == NULL || pKeyValid->notBefore == NULL || pKeyValid->notAfter == NULL) {
1796         if (pKeyValid != NULL) {
1797             PKEY_USAGE_PERIOD_free(pKeyValid);
1798         }
1799         LOGE("Failed to get x509 Private key valid in openssl!");
1800         return CF_SUCCESS;
1801     }
1802     char *notBefore = Asn1TimeToStr(pKeyValid->notBefore);
1803     char *notAfter = Asn1TimeToStr(pKeyValid->notAfter);
1804     PKEY_USAGE_PERIOD_free(pKeyValid);
1805     if (notBefore == NULL || notAfter == NULL) {
1806         LOGE("Get original data failed");
1807         CfFree(notBefore);
1808         CfFree(notAfter);
1809         return CF_SUCCESS;
1810     }
1811     if (privateKeyValid->size < DATETIME_LEN || strlen(notBefore) < DATETIME_LEN || strlen(notAfter) < DATETIME_LEN) {
1812         LOGE("Get private key valid date is not valid!");
1813         CfFree(notBefore);
1814         CfFree(notAfter);
1815         return CF_INVALID_PARAMS;
1816     }
1817     if (strncmp((const char *)privateKeyValid->data, (const char *)notBefore, DATETIME_LEN) >= 0 &&
1818         strncmp((const char *)privateKeyValid->data, (const char *)notAfter, DATETIME_LEN) <= 0) {
1819         *out = true;
1820     }
1821     CfFree(notBefore);
1822     CfFree(notAfter);
1823     return CF_SUCCESS;
1824 }
1825 
MatchPart3(HcfX509CertificateSpi * self,const HcfX509CertMatchParams * matchParams,bool * out)1826 static CfResult MatchPart3(HcfX509CertificateSpi *self, const HcfX509CertMatchParams *matchParams, bool *out)
1827 {
1828     CfResult res = CF_SUCCESS;
1829     *out = true;
1830 
1831     // subjectAlternativeNames
1832     res = CompareSubAltNameX509Openssl(
1833         self, matchParams->subjectAlternativeNames, matchParams->matchAllSubjectAltNames, out);
1834     if (res != CF_SUCCESS || (*out == false)) {
1835         LOGE("Failed to compare subject alternative name!");
1836         return res;
1837     }
1838     // authorityKeyIdentifier
1839     res = CompareNameObjectX509Openssl(self, matchParams->authorityKeyIdentifier, NAME_TYPE_AUKEYID, out);
1840     if (res != CF_SUCCESS || (*out == false)) {
1841         LOGE("Failed to compare authority key identifier!");
1842         return res;
1843     }
1844     // minPathLenConstraint
1845     res = ComparePathLenConstraintX509Openssl(self, matchParams->minPathLenConstraint, out);
1846     if (res != CF_SUCCESS || (*out == false)) {
1847         LOGE("Failed to compare pathlen constraint!");
1848         return res;
1849     }
1850     // extendedKeyUsage Array<String>
1851     res = CompareExtendKeyUsageX509Openssl(self, matchParams->extendedKeyUsage, out);
1852     if (res != CF_SUCCESS || (*out == false)) {
1853         LOGE("Failed to compare extended key usage!");
1854         return res;
1855     }
1856     // nameConstraints
1857     res = CompareNameConstraintsX509Openssl(self, matchParams->nameConstraints, out);
1858     if (res != CF_SUCCESS || (*out == false)) {
1859         LOGE("Failed to compare name constraints!");
1860         return res;
1861     }
1862     // certPolicy Array<String>
1863     res = CompareCertPolicesX509Openssl(self, matchParams->certPolicy, out);
1864     if (res != CF_SUCCESS || (*out == false)) {
1865         LOGE("Failed to compare cert polices!");
1866         return res;
1867     }
1868     // privateKeyValid
1869     res = ComparePrivateKeyValidX509Openssl(self, matchParams->privateKeyValid, out);
1870     if (res != CF_SUCCESS || (*out == false)) {
1871         LOGE("Failed to compare private key valid!");
1872         return res;
1873     }
1874     // subjectKeyIdentifier
1875     res = CompareNameObjectX509Openssl(self, matchParams->subjectKeyIdentifier, NAME_TYPE_SUBKEYID, out);
1876     if (res != CF_SUCCESS || (*out == false)) {
1877         LOGE("Failed to compare subject key identifier!");
1878         return res;
1879     }
1880     return res;
1881 }
1882 
MatchX509Openssl(HcfX509CertificateSpi * self,const HcfX509CertMatchParams * matchParams,bool * out)1883 static CfResult MatchX509Openssl(HcfX509CertificateSpi *self, const HcfX509CertMatchParams *matchParams, bool *out)
1884 {
1885     if ((self == NULL) || (matchParams == NULL) || (out == NULL)) {
1886         LOGE("[GetIssuerAltNames openssl] The input data is null!");
1887         return CF_INVALID_PARAMS;
1888     }
1889     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
1890         LOGE("Input wrong class type!");
1891         return CF_INVALID_PARAMS;
1892     }
1893     CfResult res = CF_SUCCESS;
1894     *out = true;
1895     res = MatchPart1(self, matchParams, out);
1896     if (res != CF_SUCCESS || (*out == false)) {
1897         LOGE("Failed to match part1!");
1898         return res;
1899     }
1900 
1901     res = MatchPart2(self, matchParams, out);
1902     if (res != CF_SUCCESS || (*out == false)) {
1903         LOGE("Failed to match part2!");
1904         return res;
1905     }
1906 
1907     res = MatchPart3(self, matchParams, out);
1908     if (res != CF_SUCCESS || (*out == false)) {
1909         LOGE("Failed to match part3!");
1910         return res;
1911     }
1912     return CF_SUCCESS;
1913 }
1914 
DeepCopyURIs(ASN1_STRING * uri,uint32_t index,CfArray * outURI)1915 static CfResult DeepCopyURIs(ASN1_STRING *uri, uint32_t index, CfArray *outURI)
1916 {
1917     if (index >= outURI->count) { /* exceed the maximum memory capacity. */
1918         LOGE("exceed the maximum memory capacity, uriCount = %u, malloc count = %u", index, outURI->count);
1919         return CF_ERR_CRYPTO_OPERATION;
1920     }
1921 
1922     const char *str = (const char *)ASN1_STRING_get0_data(uri);
1923     if ((str == NULL) || (strlen(str) > HCF_MAX_STR_LEN)) {
1924         LOGE("Failed to get CRL DP URI string in openssl!");
1925         return CF_ERR_CRYPTO_OPERATION;
1926     }
1927 
1928     uint32_t uriLen = strlen(str) + 1;
1929     outURI->data[index].data = (uint8_t *)CfMalloc(uriLen, 0);
1930     if (outURI->data[index].data == NULL) {
1931         LOGE("Failed to malloc for outURI[%u]!", index);
1932         return CF_ERR_MALLOC;
1933     }
1934     (void)memcpy_s(outURI->data[index].data, uriLen, str, uriLen);
1935     outURI->data[index].size = uriLen;
1936     return CF_SUCCESS;
1937 }
1938 
GetDpURIFromGenName(GENERAL_NAME * genName,bool isFormatOutURI,uint32_t * uriCount,CfArray * outURI)1939 static CfResult GetDpURIFromGenName(GENERAL_NAME *genName, bool isFormatOutURI, uint32_t *uriCount, CfArray *outURI)
1940 {
1941     int type = 0;
1942     ASN1_STRING *uri = GENERAL_NAME_get0_value(genName, &type);
1943     if (uri == NULL) {
1944         LOGE("get uri asn1 string failed");
1945         return CF_ERR_CRYPTO_OPERATION;
1946     }
1947 
1948     if (type != GEN_URI) {
1949         LOGI("not URI type, type is %d", type);
1950         return CF_SUCCESS;
1951     }
1952 
1953     if (isFormatOutURI) {
1954         CfResult ret = DeepCopyURIs(uri, *uriCount, outURI);
1955         if (ret != CF_SUCCESS) {
1956             LOGE("copy URI[%u] failed", *uriCount);
1957             return ret;
1958         }
1959     }
1960     *uriCount += 1;
1961     return CF_SUCCESS;
1962 }
1963 
GetDpURIFromGenNames(GENERAL_NAMES * genNames,bool isFormatOutURI,uint32_t * uriCount,CfArray * outURI)1964 static CfResult GetDpURIFromGenNames(GENERAL_NAMES *genNames, bool isFormatOutURI, uint32_t *uriCount,
1965     CfArray *outURI)
1966 {
1967     CfResult ret = CF_SUCCESS;
1968     int genNameNum = sk_GENERAL_NAME_num(genNames);
1969     for (int i = 0; i < genNameNum; ++i) {
1970         GENERAL_NAME *genName = sk_GENERAL_NAME_value(genNames, i);
1971         if (genName == NULL) {
1972             LOGE("get gen name failed!");
1973             ret = CF_ERR_CRYPTO_OPERATION;
1974             break;
1975         }
1976 
1977         ret = GetDpURIFromGenName(genName, isFormatOutURI, uriCount, outURI);
1978         if (ret != CF_SUCCESS) {
1979             LOGE("get gen name failed!");
1980             break;
1981         }
1982     }
1983     return ret;
1984 }
1985 
GetDpURI(STACK_OF (DIST_POINT)* crlDp,int32_t dpNumber,bool isFormatOutURI,uint32_t * uriCount,CfArray * outURI)1986 static CfResult GetDpURI(STACK_OF(DIST_POINT) *crlDp, int32_t dpNumber, bool isFormatOutURI,
1987     uint32_t *uriCount, CfArray *outURI)
1988 {
1989     CfResult ret = CF_SUCCESS;
1990     for (int i = 0; i < dpNumber; ++i) {
1991         DIST_POINT *dp = sk_DIST_POINT_value(crlDp, i);
1992         if (dp == NULL) {
1993             LOGE("get distribution point failed!");
1994             ret = CF_ERR_CRYPTO_OPERATION;
1995             break;
1996         }
1997 
1998         if (dp->distpoint == NULL || dp->distpoint->type != 0) {
1999             LOGI("not fullnames, continue!");
2000             continue;
2001         }
2002 
2003         ret = GetDpURIFromGenNames(dp->distpoint->name.fullname, isFormatOutURI, uriCount, outURI);
2004         if (ret != CF_SUCCESS) {
2005             LOGE("get dp uri from general names failed");
2006             break;
2007         }
2008     }
2009     if (ret == CF_SUCCESS && isFormatOutURI) {
2010         outURI->count = *uriCount;
2011     }
2012     return ret;
2013 }
2014 
GetCRLDpURI(STACK_OF (DIST_POINT)* crlDp,CfArray * outURI)2015 static CfResult GetCRLDpURI(STACK_OF(DIST_POINT) *crlDp, CfArray *outURI)
2016 {
2017     /* 1. get CRL distribution point URI count */
2018     int32_t dpNumber = sk_DIST_POINT_num(crlDp);
2019     uint32_t uriCount = 0;
2020     CfResult ret = GetDpURI(crlDp, dpNumber, false, &uriCount, outURI);
2021     if (ret != CF_SUCCESS) {
2022         LOGE("get dp URI count failed, ret = %d", ret);
2023         return ret;
2024     }
2025     if (uriCount == 0) {
2026         LOGE("CRL DP URI not exist");
2027         return CF_NOT_EXIST;
2028     }
2029     if (uriCount > CF_MAX_URI_COUNT) {
2030         LOGE("uriCount[%u] exceed max count", uriCount);
2031         return CF_ERR_CRYPTO_OPERATION;
2032     }
2033 
2034     /* 2. malloc outArray buffer */
2035     int32_t blobSize = (int32_t)(sizeof(CfBlob) * uriCount);
2036     outURI->data = (CfBlob *)CfMalloc(blobSize, 0);
2037     if (outURI->data == NULL) {
2038         LOGE("Failed to malloc for outURI array!");
2039         return CF_ERR_MALLOC;
2040     }
2041     outURI->count = uriCount;
2042 
2043     /* 2. copy CRL distribution point URIs */
2044     uriCount = 0;
2045     ret = GetDpURI(crlDp, dpNumber, true, &uriCount, outURI);
2046     if (ret != CF_SUCCESS) {
2047         LOGE("get dp URI format failed, ret = %d", ret);
2048         CfArrayDataClearAndFree(outURI);
2049         return ret;
2050     }
2051 
2052     return ret;
2053 }
2054 
GetCRLDistributionPointsURIX509Openssl(HcfX509CertificateSpi * self,CfArray * outURI)2055 static CfResult GetCRLDistributionPointsURIX509Openssl(HcfX509CertificateSpi *self, CfArray *outURI)
2056 {
2057     if ((self == NULL) || (outURI == NULL)) {
2058         LOGE("[GetCRLDistributionPointsURI openssl] The input data is null!");
2059         return CF_INVALID_PARAMS;
2060     }
2061     if (!CfIsClassMatch((CfObjectBase *)self, GetX509CertClass())) {
2062         LOGE("[GetCRLDistributionPointsURI openssl] Input wrong class type!");
2063         return CF_INVALID_PARAMS;
2064     }
2065 
2066     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
2067     X509 *x509 = realCert->x509;
2068 
2069     STACK_OF(DIST_POINT) *crlDp = X509_get_ext_d2i(x509, NID_crl_distribution_points, NULL, NULL);
2070     if (crlDp == NULL) {
2071         LOGE("Failed to get crl distribution point in openssl!");
2072         CfPrintOpensslError();
2073         return CF_NOT_EXIST;
2074     }
2075 
2076     CfResult ret = GetCRLDpURI(crlDp, outURI);
2077     sk_DIST_POINT_pop_free(crlDp, DIST_POINT_free);
2078     return ret;
2079 }
2080 
GetSubjectPubKeyAlgOidX509Openssl(HcfX509CertificateSpi * self,CfBlob * out)2081 static CfResult GetSubjectPubKeyAlgOidX509Openssl(HcfX509CertificateSpi *self, CfBlob *out)
2082 {
2083     CfResult res = CF_SUCCESS;
2084     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self;
2085     X509 *x509 = realCert->x509;
2086     EVP_PKEY *pubkey = X509_get_pubkey(x509);
2087     if (NULL == pubkey) {
2088         LOGE("Failed to get public key from x509 cert.");
2089         CfPrintOpensslError();
2090         return CF_ERR_CRYPTO_OPERATION;
2091     }
2092     int nId = EVP_PKEY_get_base_id(pubkey);
2093     ASN1_OBJECT *obj = OBJ_nid2obj(nId);
2094     if (NULL == obj) {
2095         LOGE("Failed to get algObj from pubkey.");
2096         CfPrintOpensslError();
2097         EVP_PKEY_free(pubkey);
2098         return CF_ERR_CRYPTO_OPERATION;
2099     }
2100 
2101     char algOid[OID_STR_MAX_LEN] = { 0 };
2102     int32_t resLen = OBJ_obj2txt(algOid, OID_STR_MAX_LEN, obj, 1);
2103     if ((resLen <= 0) || (resLen >= OID_STR_MAX_LEN)) {
2104         LOGE("Failed to convert x509 object to text!");
2105         CfPrintOpensslError();
2106         EVP_PKEY_free(pubkey);
2107         ASN1_OBJECT_free(obj);
2108         return CF_ERR_CRYPTO_OPERATION;
2109     }
2110     uint32_t len = strlen(algOid) + 1;
2111     res = DeepCopyDataToOut(algOid, len, out);
2112     EVP_PKEY_free(pubkey);
2113     ASN1_OBJECT_free(obj);
2114     return res;
2115 }
2116 
CreateX509CertInner(const CfEncodingBlob * encodingBlob)2117 static X509 *CreateX509CertInner(const CfEncodingBlob *encodingBlob)
2118 {
2119     X509 *x509 = NULL;
2120     BIO *bio = BIO_new_mem_buf(encodingBlob->data, encodingBlob->len);
2121     if (bio == NULL) {
2122         LOGE("Openssl bio new buf failed.");
2123         return NULL;
2124     }
2125     if (encodingBlob->encodingFormat == CF_FORMAT_DER) {
2126         x509 = d2i_X509_bio(bio, NULL);
2127     } else if (encodingBlob->encodingFormat == CF_FORMAT_PEM) {
2128         x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
2129     }
2130     BIO_free(bio);
2131     return x509;
2132 }
2133 
OpensslX509CertSpiCreate(const CfEncodingBlob * inStream,HcfX509CertificateSpi ** spi)2134 CfResult OpensslX509CertSpiCreate(const CfEncodingBlob *inStream, HcfX509CertificateSpi **spi)
2135 {
2136     if ((inStream == NULL) || (inStream->data == NULL) || (spi == NULL)) {
2137         LOGE("The input data blob is null!");
2138         return CF_INVALID_PARAMS;
2139     }
2140     HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)CfMalloc(sizeof(HcfOpensslX509Cert), 0);
2141     if (realCert == NULL) {
2142         LOGE("Failed to malloc for x509 instance!");
2143         return CF_ERR_MALLOC;
2144     }
2145     realCert->x509 = CreateX509CertInner(inStream);
2146     if (realCert->x509 == NULL) {
2147         CfFree(realCert);
2148         LOGE("Failed to create x509 cert from input data!");
2149         return CF_INVALID_PARAMS;
2150     }
2151     realCert->base.base.getClass = GetX509CertClass;
2152     realCert->base.base.destroy = DestroyX509Openssl;
2153     realCert->base.engineVerify = VerifyX509Openssl;
2154     realCert->base.engineGetEncoded = GetEncodedX509Openssl;
2155     realCert->base.engineGetPublicKey = GetPublicKeyX509Openssl;
2156     realCert->base.engineCheckValidityWithDate = CheckValidityWithDateX509Openssl;
2157     realCert->base.engineGetVersion = GetVersionX509Openssl;
2158     realCert->base.engineGetSerialNumber = GetSerialNumberX509Openssl;
2159     realCert->base.engineGetIssuerName = GetIssuerDNX509Openssl;
2160     realCert->base.engineGetSubjectName = GetSubjectDNX509Openssl;
2161     realCert->base.engineGetSubjectNameEx = GetSubjectDNX509OpensslEx;
2162     realCert->base.engineGetNotBeforeTime = GetNotBeforeX509Openssl;
2163     realCert->base.engineGetNotAfterTime = GetNotAfterX509Openssl;
2164     realCert->base.engineGetSignature = GetSignatureX509Openssl;
2165     realCert->base.engineGetSignatureAlgName = GetSigAlgNameX509Openssl;
2166     realCert->base.engineGetSignatureAlgOid = GetSigAlgOidX509Openssl;
2167     realCert->base.engineGetSignatureAlgParams = GetSigAlgParamsX509Openssl;
2168     realCert->base.engineGetKeyUsage = GetKeyUsageX509Openssl;
2169     realCert->base.engineGetExtKeyUsage = GetExtendedKeyUsageX509Openssl;
2170     realCert->base.engineGetBasicConstraints = GetBasicConstraintsX509Openssl;
2171     realCert->base.engineGetSubjectAltNames = GetSubjectAltNamesX509Openssl;
2172     realCert->base.engineGetIssuerAltNames = GetIssuerAltNamesX509Openssl;
2173     realCert->base.engineGetCRLDistributionPointsURI = GetCRLDistributionPointsURIX509Openssl;
2174     realCert->base.engineMatch = MatchX509Openssl;
2175     realCert->base.engineToString = ToStringX509Openssl;
2176     realCert->base.engineHashCode = HashCodeX509Openssl;
2177     realCert->base.engineGetExtensionsObject = GetExtensionsObjectX509Openssl;
2178 
2179     *spi = (HcfX509CertificateSpi *)realCert;
2180     return CF_SUCCESS;
2181 }
2182