code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_PKI_X509 #include "securec.h" #include "bsl_obj.h" #include "bsl_obj_internal.h" #include "bsl_sal.h" #include "bsl_types.h" #include "bsl_err_internal.h" #include "hitls_pki_errno.h" #include "hitls_x509_local.h" #define BITS_OF_BYTE 8 #define HITLS_X509_EXT_NOT_FOUND 1 #define HITLS_X509_EXT_KEYUSAGE_UNUSED_BIT 0xFFFF7F00 // Only 9 bits are used. typedef enum { HITLS_X509_EXT_OID_IDX, HITLS_X509_EXT_CRITICAL_IDX, HITLS_X509_EXT_VALUE_IDX, HITLS_X509_EXT_MAX } HITLS_X509_EXT_IDX; /** * RFC 5280: section-4.2.1.9 * BasicConstraints ::= SEQUENCE { * cA BOOLEAN DEFAULT FALSE, * pathLenConstraint INTEGER (0..MAX) OPTIONAL } */ static BSL_ASN1_TemplateItem g_bConsTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, {BSL_ASN1_TAG_BOOLEAN, BSL_ASN1_FLAG_DEFAULT, 1}, {BSL_ASN1_TAG_INTEGER, BSL_ASN1_FLAG_OPTIONAL, 1}, }; typedef enum { HITLS_X509_EXT_BC_CA_IDX, HITLS_X509_EXT_BC_PATHLEN_IDX, HITLS_X509_EXT_BC_MAX } HITLS_X509_EXT_BASICCONSTRAINTS; /** * RFC 5280: section-4.2.1.1 * AuthorityKeyIdentifier ::= SEQUENCE { * keyIdentifier [0] KeyIdentifier OPTIONAL, * authorityCertIssuer [1] GeneralNames OPTIONAL, * authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL } */ #define HITLS_X509_CTX_SPECIFIC_TAG_AKID_KID 0 #define HITLS_X509_CTX_SPECIFIC_TAG_AKID_ISSUER 1 #define HITLS_X509_CTX_SPECIFIC_TAG_AKID_SERIAL 2 static BSL_ASN1_TemplateItem g_akidTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* KeyIdentifier */ {BSL_ASN1_CLASS_CTX_SPECIFIC | HITLS_X509_CTX_SPECIFIC_TAG_AKID_KID, BSL_ASN1_FLAG_OPTIONAL, 1}, /* authorityCertIssuer */ {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_X509_CTX_SPECIFIC_TAG_AKID_ISSUER, BSL_ASN1_FLAG_OPTIONAL | BSL_ASN1_FLAG_HEADERONLY, 1}, /* authorityCertSerialNumber */ {BSL_ASN1_CLASS_CTX_SPECIFIC | HITLS_X509_CTX_SPECIFIC_TAG_AKID_SERIAL, BSL_ASN1_FLAG_OPTIONAL, 1}, }; typedef enum { HITLS_X509_EXT_AKI_KID_IDX, HITLS_X509_EXT_AKI_ISSUER_IDX, HITLS_X509_EXT_AKI_SERIAL_IDX, HITLS_X509_EXT_AKI_MAX, } HITLS_X509_EXT_AKI; /** * RFC 5280: section-4.2.1.2 * Two common methods for generating key identifiers from the public key are: * (1) The kid is composed of 160-bit sha1 hash of the BIT STRING subjectPublicKey. * (2) The kid is composed of a 4-bit type field with the value 0100 followed by the lease significant 60 bits of the * sha1 hash of the BIT STRING subjectPublicKey. */ #define HITLS_X509_KID_MIN_LEN 8 #define HITLS_X509_KID_MAX_LEN 20 #define HITLS_X509_CRLNUMBER_MIN_LEN 1 #define HITLS_X509_CRLNUMBER_MAX_LEN 20 /** * RFC 5280: section-4.2.1.6 * SubjectAltName ::= GeneralNames * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName * GeneralName ::= CHOICE { * otherName [0] OtherName, -- not support * rfc822Name [1] IA5String, * dNSName [2] IA5String, * x400Address [3] ORAddress, -- not support * directoryName [4] Name, * ediPartyName [5] EDIPartyName, -- not support * uniformResourceIdentifier [6] IA5String, * iPAddress [7] OCTET STRING, * registeredID [8] OBJECT IDENTIFIER -- not support * } */ #define HITLS_X509_GENERALNAME_OTHER_TAG (BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | 0) #define HITLS_X509_GENERALNAME_RFC822_TAG (BSL_ASN1_CLASS_CTX_SPECIFIC | 1) #define HITLS_X509_GENERALNAME_DNS_TAG (BSL_ASN1_CLASS_CTX_SPECIFIC | 2) #define HITLS_X509_GENERALNAME_X400_TAG (BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | 3) #define HITLS_X509_GENERALNAME_DIR_TAG (BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | 4) #define HITLS_X509_GENERALNAME_EDI_TAG (BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | 5) #define HITLS_X509_GENERALNAME_URI_TAG (BSL_ASN1_CLASS_CTX_SPECIFIC | 6) #define HITLS_X509_GENERALNAME_IP_TAG (BSL_ASN1_CLASS_CTX_SPECIFIC | 7) #define HITLS_X509_GENERALNAME_RID_TAG (BSL_ASN1_CLASS_CTX_SPECIFIC | 8) typedef struct { uint8_t tag; int32_t type; } HITLS_X509_GeneralNameMap; static HITLS_X509_GeneralNameMap g_generalNameMap[] = { {HITLS_X509_GENERALNAME_OTHER_TAG, HITLS_X509_GN_OTHER}, {HITLS_X509_GENERALNAME_RFC822_TAG, HITLS_X509_GN_EMAIL}, {HITLS_X509_GENERALNAME_DNS_TAG, HITLS_X509_GN_DNS}, {HITLS_X509_GENERALNAME_X400_TAG, HITLS_X509_GN_X400}, {HITLS_X509_GENERALNAME_DIR_TAG, HITLS_X509_GN_DNNAME}, {HITLS_X509_GENERALNAME_EDI_TAG, HITLS_X509_GN_EDI}, {HITLS_X509_GENERALNAME_URI_TAG, HITLS_X509_GN_URI}, {HITLS_X509_GENERALNAME_IP_TAG, HITLS_X509_GN_IP}, {HITLS_X509_GENERALNAME_RID_TAG, HITLS_X509_GN_RID}, }; static int32_t CmpExtByCid(const void *pExt, const void *pCid) { const HITLS_X509_ExtEntry *ext = pExt; BslCid cid = *(const BslCid *)pCid; return cid == ext->cid ? 0 : HITLS_X509_EXT_NOT_FOUND; } #if defined(HITLS_PKI_X509_CRT_PARSE) || defined(HITLS_PKI_X509_CRL_PARSE) || defined(HITLS_PKI_X509_CSR) static int32_t CmpExtByOid(const void *pExt, const void *pOid) { const HITLS_X509_ExtEntry *ext = pExt; const BSL_ASN1_Buffer *oid = pOid; if (ext->extnId.len != oid->len) { return HITLS_X509_EXT_NOT_FOUND; } return memcmp(ext->extnId.buff, oid->buff, oid->len) == 0 ? 0 : HITLS_X509_EXT_NOT_FOUND; } static int32_t ParseExtKeyUsage(HITLS_X509_ExtEntry *extEntry, HITLS_X509_CertExt *ext) { uint32_t len; uint8_t *temp = extEntry->extnValue.buff; uint32_t tempLen = extEntry->extnValue.len; int32_t ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_BITSTRING, &temp, &tempLen, &len); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_Buffer asn = {BSL_ASN1_TAG_BITSTRING, len, temp}; BSL_ASN1_BitString bitString = {0}; ret = BSL_ASN1_DecodePrimitiveItem(&asn, &bitString); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (bitString.len > sizeof(ext->keyUsage)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PARSE_EXT_KU); return HITLS_X509_ERR_PARSE_EXT_KU; } for (uint32_t i = 0; i < bitString.len; i++) { ext->keyUsage |= (bitString.buff[i] << (BITS_OF_BYTE * i)); } ext->extFlags |= HITLS_X509_EXT_FLAG_KUSAGE; return HITLS_PKI_SUCCESS; } static int32_t ParseExtBasicConstraints(HITLS_X509_ExtEntry *extEntry, HITLS_X509_CertExt *ext) { uint8_t *temp = extEntry->extnValue.buff; uint32_t tempLen = extEntry->extnValue.len; BSL_ASN1_Buffer asnArr[HITLS_X509_EXT_BC_MAX] = {0}; BSL_ASN1_Template templ = {g_bConsTempl, sizeof(g_bConsTempl) / sizeof(g_bConsTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &temp, &tempLen, asnArr, HITLS_X509_EXT_BC_MAX); if (tempLen != 0) { ret = HITLS_X509_ERR_PARSE_EXT_BUF; } if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (asnArr[HITLS_X509_EXT_BC_CA_IDX].tag != 0) { ret = BSL_ASN1_DecodePrimitiveItem(&asnArr[HITLS_X509_EXT_BC_CA_IDX], &ext->isCa); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } if (asnArr[HITLS_X509_EXT_BC_PATHLEN_IDX].tag != 0) { ret = BSL_ASN1_DecodePrimitiveItem(&asnArr[HITLS_X509_EXT_BC_PATHLEN_IDX], &ext->maxPathLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } ext->extFlags |= HITLS_X509_EXT_FLAG_BCONS; return ret; } #endif static int32_t ParseDirName(uint8_t **encode, uint32_t *encLen, BslList **list) { uint32_t valueLen; int32_t ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, encode, encLen, &valueLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } *list = BSL_LIST_New(sizeof(HITLS_X509_NameNode)); if (*list == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } BSL_ASN1_Buffer asn = {.buff = *encode, .len = valueLen}; ret = HITLS_X509_ParseNameList(&asn, *list); if (ret == BSL_SUCCESS) { *encode += valueLen; *encLen -= valueLen; } else { BSL_LIST_FREE(*list, NULL); } return ret; } static int32_t ParseGeneralName(uint8_t tag, uint8_t **encode, uint32_t *encLen, uint32_t nameLen, BslList *list) { int32_t type = -1; int32_t ret; BslList *dirNames = NULL; BSL_Buffer value = {0}; for (uint32_t i = 0; i < sizeof(g_generalNameMap) / sizeof(g_generalNameMap[0]); i++) { if (g_generalNameMap[i].tag == tag) { type = g_generalNameMap[i].type; break; } } if (type == -1) { return HITLS_X509_ERR_PARSE_SAN_ITEM_UNKNOW; } if (tag == HITLS_X509_GENERALNAME_DIR_TAG) { ret = ParseDirName(encode, encLen, &dirNames); if (ret != HITLS_PKI_SUCCESS) { return ret; } value.data = (uint8_t *)dirNames; value.dataLen = sizeof(BslList *); } else { value.data = *encode; value.dataLen = nameLen; } HITLS_X509_GeneralName *name = BSL_SAL_Calloc(1, sizeof(HITLS_X509_GeneralName)); if (name == NULL) { if (dirNames != NULL) { BSL_LIST_FREE(dirNames, NULL); } BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } name->type = type; name->value = value; ret = BSL_LIST_AddElement(list, name, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { BSL_LIST_FREE(dirNames, NULL); BSL_SAL_Free(name); } return ret; } static void FreeGeneralName(void *data) { HITLS_X509_GeneralName *name = (HITLS_X509_GeneralName *)data; if (name->type == HITLS_X509_GN_DNNAME) { BSL_LIST_DeleteAll((BslList *)name->value.data, NULL); BSL_SAL_Free(name->value.data); } BSL_SAL_Free(data); } void HITLS_X509_FreeGeneralName(HITLS_X509_GeneralName *data) { if (data == NULL) { return; } if (data->type == HITLS_X509_GN_DNNAME) { BSL_LIST_DeleteAll((BslList *)data->value.data, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeNameNode); } BSL_SAL_Free(data->value.data); BSL_SAL_Free(data); } void HITLS_X509_ClearGeneralNames(BslList *names) { if (names == NULL) { return; } BSL_LIST_DeleteAll(names, (BSL_LIST_PFUNC_FREE)FreeGeneralName); } HITLS_X509_Ext *X509_ExtNew(HITLS_X509_Ext *ext, int32_t type) { HITLS_X509_Ext *tmp = NULL; if (ext == NULL) { tmp = (HITLS_X509_Ext *)BSL_SAL_Calloc(1, sizeof(HITLS_X509_Ext)); if (tmp == NULL) { return NULL; } ext = tmp; } ext->type = type; ext->extList = BSL_LIST_New(sizeof(HITLS_X509_ExtEntry *)); if (ext->extList == NULL) { BSL_SAL_Free(tmp); return NULL; } if (type != HITLS_X509_EXT_TYPE_CRL) { ext->extData = BSL_SAL_Calloc(1, sizeof(HITLS_X509_CertExt)); if (ext->extData == NULL) { BSL_SAL_Free(ext->extList); ext->extList = NULL; BSL_SAL_Free(tmp); return NULL; } ((HITLS_X509_CertExt *)(ext->extData))->maxPathLen = -1; } return ext; } void X509_ExtFree(HITLS_X509_Ext *ext, bool isFreeOut) { if (ext == NULL) { return; } if ((ext->flag & HITLS_X509_EXT_FLAG_PARSE) != 0) { BSL_LIST_FREE(ext->extList, NULL); } else { BSL_LIST_FREE(ext->extList, (BSL_LIST_PFUNC_FREE)HITLS_X509_ExtEntryFree); } BSL_SAL_Free(ext->extData); if (isFreeOut) { BSL_SAL_Free(ext); } } int32_t HITLS_X509_ParseGeneralNames(uint8_t *encode, uint32_t encLen, BslList *list) { uint8_t *buff = encode; uint32_t buffLen = encLen; uint32_t nameValueLen; uint8_t tag; int32_t ret = HITLS_PKI_SUCCESS; while (buffLen != 0) { // tag tag = *buff; buff++; buffLen--; // length ret = BSL_ASN1_DecodeLen(&buff, &buffLen, false, &nameValueLen); if (ret != BSL_SUCCESS) { break; } if (nameValueLen == 0) { continue; } // value ret = ParseGeneralName(tag, &buff, &buffLen, nameValueLen, list); if (ret != BSL_SUCCESS) { break; } if (tag != HITLS_X509_GENERALNAME_DIR_TAG) { buff += nameValueLen; buffLen -= nameValueLen; } } if (ret != BSL_SUCCESS) { HITLS_X509_ClearGeneralNames(list); BSL_ERR_PUSH_ERROR(ret); } return ret; } void HITLS_X509_ClearAuthorityKeyId(HITLS_X509_ExtAki *aki) { if (aki == NULL) { return; } if (aki->issuerName != NULL) { HITLS_X509_ClearGeneralNames(aki->issuerName); BSL_SAL_Free(aki->issuerName); aki->issuerName = NULL; } } int32_t HITLS_X509_ParseAuthorityKeyId(HITLS_X509_ExtEntry *extEntry, HITLS_X509_ExtAki *aki) { uint8_t *temp = extEntry->extnValue.buff; uint32_t tempLen = extEntry->extnValue.len; BslList *list = NULL; BSL_ASN1_Buffer asnArr[HITLS_X509_EXT_AKI_MAX] = {0}; BSL_ASN1_Template templ = {g_akidTempl, sizeof(g_akidTempl) / sizeof(g_akidTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &temp, &tempLen, asnArr, HITLS_X509_EXT_AKI_MAX); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (asnArr[HITLS_X509_EXT_AKI_KID_IDX].tag != 0) { aki->kid.data = asnArr[HITLS_X509_EXT_AKI_KID_IDX].buff; aki->kid.dataLen = asnArr[HITLS_X509_EXT_AKI_KID_IDX].len; } /** * ITU-T x509: 8.2.2.1 Authority key identifier extension * authorityCertIssuer PRESENT, authorityCertSerialNumber PRESENT * authorityCertIssuer ABSENT, authorityCertSerialNumber ABSENT */ if ((asnArr[HITLS_X509_EXT_AKI_SERIAL_IDX].buff != NULL && asnArr[HITLS_X509_EXT_AKI_ISSUER_IDX].buff == NULL) || (asnArr[HITLS_X509_EXT_AKI_SERIAL_IDX].buff == NULL && asnArr[HITLS_X509_EXT_AKI_ISSUER_IDX].buff != NULL)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_ILLEGAL_AKI); return HITLS_X509_ERR_EXT_ILLEGAL_AKI; } if (asnArr[HITLS_X509_EXT_AKI_SERIAL_IDX].tag != 0) { aki->serialNum.data = asnArr[HITLS_X509_EXT_AKI_SERIAL_IDX].buff; aki->serialNum.dataLen = asnArr[HITLS_X509_EXT_AKI_SERIAL_IDX].len; } if (asnArr[HITLS_X509_EXT_AKI_ISSUER_IDX].tag != 0) { list = BSL_LIST_New(sizeof(HITLS_X509_GeneralName)); if (list == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PARSE_AKI); return HITLS_X509_ERR_PARSE_AKI; } ret = HITLS_X509_ParseGeneralNames( asnArr[HITLS_X509_EXT_AKI_ISSUER_IDX].buff, asnArr[HITLS_X509_EXT_AKI_ISSUER_IDX].len, list); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_Free(list); BSL_ERR_PUSH_ERROR(ret); return ret; } aki->issuerName = list; } aki->critical = extEntry->critical; return ret; } int32_t HITLS_X509_ParseSubjectKeyId(HITLS_X509_ExtEntry *extEntry, HITLS_X509_ExtSki *ski) { uint8_t *temp = extEntry->extnValue.buff; uint32_t tempLen = extEntry->extnValue.len; uint32_t kidLen = 0; int32_t ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_OCTETSTRING, &temp, &tempLen, &kidLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ski->kid.data = temp; ski->kid.dataLen = kidLen; ski->critical = extEntry->critical; return ret; } int32_t X509_ParseCrlNumber(HITLS_X509_ExtEntry *extEntry, HITLS_X509_ExtCrlNumber *crlNumber) { uint8_t *temp = extEntry->extnValue.buff; uint32_t tempLen = extEntry->extnValue.len; uint32_t valueLen = 0; // CRL Number is encoded as an INTEGER int32_t ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_INTEGER, &temp, &tempLen, &valueLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // Check CRL Number length if (valueLen < HITLS_X509_CRLNUMBER_MIN_LEN || valueLen > HITLS_X509_CRLNUMBER_MAX_LEN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_CRLNUMBER); return HITLS_X509_ERR_EXT_CRLNUMBER; } // Store CRL Number value crlNumber->crlNumber.data = temp; crlNumber->crlNumber.dataLen = valueLen; crlNumber->critical = extEntry->critical; return HITLS_PKI_SUCCESS; } #if defined(HITLS_PKI_X509_CRT_PARSE) || defined(HITLS_PKI_X509_CRL_PARSE) || defined(HITLS_PKI_X509_CSR_PARSE) static int32_t ParseExKeyUsageList(uint32_t layer, BSL_ASN1_Buffer *asn, void *param, BSL_ASN1_List *list) { (void)param; if (layer == 1) { return HITLS_PKI_SUCCESS; } BSL_Buffer *buff = BSL_SAL_Malloc(sizeof(BSL_Buffer)); if (buff == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PARSE_EXKU_ITEM); return HITLS_X509_ERR_PARSE_EXKU_ITEM; } buff->data = asn->buff; buff->dataLen = asn->len; int32_t ret = BSL_LIST_AddElement(list, buff, BSL_LIST_POS_AFTER); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); BSL_SAL_Free(buff); } return ret; } int32_t HITLS_X509_ParseExtendedKeyUsage(HITLS_X509_ExtEntry *extEntry, HITLS_X509_ExtExKeyUsage *exku) { uint8_t expTag[] = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_TAG_OBJECT_ID}; BSL_ASN1_DecodeListParam listParam = {sizeof(expTag) / sizeof(uint8_t), expTag}; BslList *list = BSL_LIST_New(sizeof(BSL_Buffer)); if (list == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PARSE_EXKU); return HITLS_X509_ERR_PARSE_EXKU; } int32_t ret = BSL_ASN1_DecodeListItem(&listParam, &extEntry->extnValue, ParseExKeyUsageList, NULL, list); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_DeleteAll(list, NULL); BSL_SAL_Free(list); return ret; } exku->critical = extEntry->critical; exku->oidList = list; return ret; } void HITLS_X509_ClearSubjectAltName(HITLS_X509_ExtSan *san) { if (san == NULL) { return; } if (san->names != NULL) { HITLS_X509_ClearGeneralNames(san->names); BSL_SAL_Free(san->names); san->names = NULL; } } int32_t HITLS_X509_ParseSubjectAltName(HITLS_X509_ExtEntry *extEntry, HITLS_X509_ExtSan *san) { uint32_t len; uint8_t *buff = extEntry->extnValue.buff; uint32_t buffLen = extEntry->extnValue.len; // skip the sequence int32_t ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, &buff, &buffLen, &len); if (ret == BSL_SUCCESS && buffLen != len) { ret = HITLS_X509_ERR_PARSE_NO_ENOUGH; } if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BslList *list = BSL_LIST_New(sizeof(HITLS_X509_GeneralName)); if (list == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PARSE_SAN); return HITLS_X509_ERR_PARSE_SAN; } ret = HITLS_X509_ParseGeneralNames(buff, len, list); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_FREE(list); BSL_ERR_PUSH_ERROR(ret); return ret; } san->names = list; san->critical = extEntry->critical; return ret; } void HITLS_X509_ClearExtendedKeyUsage(HITLS_X509_ExtExKeyUsage *exku) { if (exku == NULL) { return; } BSL_LIST_FREE(exku->oidList, NULL); } #endif #if defined(HITLS_PKI_X509_CRT_PARSE) || defined(HITLS_PKI_X509_CRL_PARSE) || defined(HITLS_PKI_X509_CSR) static BSL_ASN1_TemplateItem g_x509ExtTempl[] = { {BSL_ASN1_TAG_OBJECT_ID, 0, 0}, {BSL_ASN1_TAG_BOOLEAN, BSL_ASN1_FLAG_DEFAULT, 0}, {BSL_ASN1_TAG_OCTETSTRING, 0, 0}, }; int32_t HITLS_X509_ParseExtItem(BSL_ASN1_Buffer *extItem, HITLS_X509_ExtEntry *extEntry) { uint8_t *temp = extItem->buff; uint32_t tempLen = extItem->len; BSL_ASN1_Buffer asnArr[HITLS_X509_EXT_MAX] = {0}; BSL_ASN1_Template templ = {g_x509ExtTempl, sizeof(g_x509ExtTempl) / sizeof(g_x509ExtTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &temp, &tempLen, asnArr, HITLS_X509_EXT_MAX); if (tempLen != 0) { ret = HITLS_X509_ERR_PARSE_EXT_BUF; } if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // extnid extEntry->extnId = asnArr[HITLS_X509_EXT_OID_IDX]; BslOidString oid = {extEntry->extnId.len, (char *)extEntry->extnId.buff, 0}; extEntry->cid = BSL_OBJ_GetCID(&oid); // critical if (asnArr[HITLS_X509_EXT_CRITICAL_IDX].tag == 0) { extEntry->critical = false; } else { ret = BSL_ASN1_DecodePrimitiveItem(&asnArr[HITLS_X509_EXT_CRITICAL_IDX], &extEntry->critical); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } extEntry->extnValue = asnArr[HITLS_X509_EXT_VALUE_IDX]; return ret; } #endif #if defined(HITLS_PKI_X509_CRT_GEN) || defined(HITLS_PKI_X509_CRL_GEN) || defined(HITLS_PKI_X509_CSR_GEN) static void FreeExtEntryCont(HITLS_X509_ExtEntry *entry) { BSL_SAL_FREE(entry->extnId.buff); BSL_SAL_FREE(entry->extnValue.buff); entry->extnId.len = 0; entry->extnValue.len = 0; } static int32_t GetExtEntryByCid(BslList *extList, BslCid cid, HITLS_X509_ExtEntry **entry, bool *isNew) { BslOidString *oid = BSL_OBJ_GetOID(cid); if (oid == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_OID); return HITLS_X509_ERR_EXT_OID; } HITLS_X509_ExtEntry *extEntry = BSL_LIST_Search(extList, &cid, CmpExtByCid, NULL); if (extEntry != NULL) { *isNew = false; FreeExtEntryCont(extEntry); extEntry->critical = false; } else { extEntry = BSL_SAL_Calloc(1, sizeof(HITLS_X509_ExtEntry)); if (extEntry == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } *isNew = true; } extEntry->cid = cid; extEntry->extnId.tag = BSL_ASN1_TAG_OBJECT_ID; extEntry->extnId.len = oid->octetLen; if (extEntry->extnId.len != 0) { extEntry->extnId.buff = BSL_SAL_Dump(oid->octs, oid->octetLen); if (extEntry->extnId.buff == NULL) { if (*isNew) { BSL_SAL_Free(extEntry); } BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return BSL_DUMP_FAIL; } } extEntry->extnValue.tag = BSL_ASN1_TAG_OCTETSTRING; *entry = extEntry; return HITLS_PKI_SUCCESS; } #endif #if defined(HITLS_PKI_X509_CRT_PARSE) || defined(HITLS_PKI_X509_CRL_PARSE) || defined(HITLS_PKI_X509_CSR) static int32_t ParseExtAsnItem(BSL_ASN1_Buffer *asn, void *param, BSL_ASN1_List *list) { HITLS_X509_Ext *ext = param; HITLS_X509_ExtEntry extEntry = {0}; int32_t ret = HITLS_X509_ParseExtItem(asn, &extEntry); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // Check if the extension already exists. if (BSL_LIST_Search(list, &extEntry.extnId, CmpExtByOid, NULL) != NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PARSE_EXT_REPEAT); return HITLS_X509_ERR_PARSE_EXT_REPEAT; } // Add the extension to list. ret = HITLS_X509_AddListItemDefault(&extEntry, sizeof(HITLS_X509_ExtEntry), list); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BslOidString oid = {extEntry.extnId.len, (char *)extEntry.extnId.buff, 0}; switch (BSL_OBJ_GetCID(&oid)) { case BSL_CID_CE_KEYUSAGE: return ParseExtKeyUsage(&extEntry, (HITLS_X509_CertExt *)ext->extData); case BSL_CID_CE_BASICCONSTRAINTS: return ParseExtBasicConstraints(&extEntry, (HITLS_X509_CertExt *)ext->extData); default: return HITLS_PKI_SUCCESS; } } static int32_t ParseExtSeqof(uint32_t layer, BSL_ASN1_Buffer *asn, void *param, BSL_ASN1_List *list) { return layer == 1 ? HITLS_PKI_SUCCESS : ParseExtAsnItem(asn, param, list); } int32_t HITLS_X509_ParseExt(BSL_ASN1_Buffer *ext, HITLS_X509_Ext *certExt) { if (certExt == NULL || certExt->extData == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_PARSE_AFTER_SET); return HITLS_X509_ERR_EXT_PARSE_AFTER_SET; } if ((certExt->flag & HITLS_X509_EXT_FLAG_GEN) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_PARSE_AFTER_SET); return HITLS_X509_ERR_EXT_PARSE_AFTER_SET; } // x509 v1 if (ext->tag == 0) { return HITLS_PKI_SUCCESS; } uint8_t expTag[] = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE}; BSL_ASN1_DecodeListParam listParam = {2, expTag}; int ret = BSL_ASN1_DecodeListItem(&listParam, ext, &ParseExtSeqof, certExt, certExt->extList); if (ret != BSL_SUCCESS) { BSL_LIST_DeleteAll(certExt->extList, NULL); BSL_ERR_PUSH_ERROR(ret); return ret; } certExt->flag |= HITLS_X509_EXT_FLAG_PARSE; return ret; } #endif #if defined(HITLS_PKI_X509_CRT_GEN) || defined(HITLS_PKI_X509_CRL_GEN) || defined(HITLS_PKI_X509_CSR_GEN) static int32_t SetExtBCons(HITLS_X509_Ext *ext, HITLS_X509_ExtEntry *entry, const void *val) { const HITLS_X509_ExtBCons *bCons = (const HITLS_X509_ExtBCons *)val; BSL_ASN1_Template templ = {g_bConsTempl, sizeof(g_bConsTempl) / sizeof(g_bConsTempl[0])}; /** * RFC 5280: section-4.2.1.9 * BasicConstraints ::= SEQUENCE { * cA BOOLEAN DEFAULT FALSE, * pathLenConstraint INTEGER (0..MAX) OPTIONAL } */ BSL_ASN1_Buffer asns[] = { {BSL_ASN1_TAG_BOOLEAN, bCons->isCa ? sizeof(bool) : 0, bCons->isCa ? (uint8_t *)(uintptr_t)&bCons->isCa : NULL}, {BSL_ASN1_TAG_INTEGER, 0, NULL}, }; int32_t ret; if (bCons->maxPathLen >= 0) { ret = BSL_ASN1_EncodeLimb(BSL_ASN1_TAG_INTEGER, (uint64_t)bCons->maxPathLen, asns + 1); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } ret = BSL_ASN1_EncodeTemplate( &templ, asns, sizeof(asns) / sizeof(asns[0]), &entry->extnValue.buff, &entry->extnValue.len); BSL_SAL_Free(asns[1].buff); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } entry->critical = bCons->critical; HITLS_X509_CertExt *certExt = (HITLS_X509_CertExt *)ext->extData; certExt->isCa = bCons->isCa; certExt->maxPathLen = bCons->maxPathLen; certExt->extFlags |= HITLS_X509_EXT_FLAG_BCONS; return HITLS_PKI_SUCCESS; } static int32_t SetExtKeyUsage(HITLS_X509_Ext *ext, HITLS_X509_ExtEntry *entry, const void *val) { const HITLS_X509_ExtKeyUsage *ku = (const HITLS_X509_ExtKeyUsage *)val; if (ku->keyUsage == 0 || (ku->keyUsage & HITLS_X509_EXT_KEYUSAGE_UNUSED_BIT) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_KU); return HITLS_X509_ERR_EXT_KU; } // bit string uint16_t keyUsage = (uint16_t)ku->keyUsage; BSL_ASN1_BitString bs = {0}; bs.len = (keyUsage & HITLS_X509_EXT_KU_DECIPHER_ONLY) == 0 ? 1 : 2; // 2: decipher only is not 0 uint8_t buff[2] = {0}; // The max length of content(BitString, except unused bits) is 2 bytes. buff[0] = (uint8_t)keyUsage; buff[1] = (uint8_t)(keyUsage >> 8); // 8: 8 bits per byte bs.buff = buff; uint8_t tmp = bs.len == 1 ? (uint8_t)keyUsage : (uint8_t)(keyUsage >> BITS_OF_BYTE); for (int32_t i = 1; i < BITS_OF_BYTE; i++) { if ((uint8_t)(tmp << i) == 0) { bs.unusedBits = BITS_OF_BYTE - i; break; } } // encode bit string BSL_ASN1_Buffer asn = {BSL_ASN1_TAG_BITSTRING, sizeof(BSL_ASN1_BitString), (uint8_t *)&bs}; BSL_ASN1_TemplateItem item = {BSL_ASN1_TAG_BITSTRING, 0, 0}; BSL_ASN1_Template templ = {&item, 1}; int32_t ret = BSL_ASN1_EncodeTemplate(&templ, &asn, 1, &entry->extnValue.buff, &entry->extnValue.len); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } entry->critical = ku->critical; HITLS_X509_CertExt *certExt = (HITLS_X509_CertExt *)ext->extData; certExt->extFlags |= HITLS_X509_EXT_FLAG_KUSAGE; return ret; } static int32_t SetExtAki(HITLS_X509_Ext *ext, HITLS_X509_ExtEntry *entry, const void *val) { (void)ext; const HITLS_X509_ExtAki *aki = (const HITLS_X509_ExtAki *)val; entry->critical = aki->critical; if (aki->kid.dataLen < HITLS_X509_KID_MIN_LEN || aki->kid.dataLen > HITLS_X509_KID_MAX_LEN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_KID); return HITLS_X509_ERR_EXT_KID; } BSL_ASN1_Buffer asns[] = { {BSL_ASN1_CLASS_CTX_SPECIFIC | HITLS_X509_CTX_SPECIFIC_TAG_AKID_KID, aki->kid.dataLen, aki->kid.data}, {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_X509_CTX_SPECIFIC_TAG_AKID_ISSUER, 0, NULL}, {BSL_ASN1_CLASS_CTX_SPECIFIC | HITLS_X509_CTX_SPECIFIC_TAG_AKID_SERIAL, 0, NULL}, }; BSL_ASN1_Template templ = {g_akidTempl, sizeof(g_akidTempl) / sizeof(g_akidTempl[0])}; int32_t ret = BSL_ASN1_EncodeTemplate( &templ, asns, sizeof(asns) / sizeof(asns[0]), &entry->extnValue.buff, &entry->extnValue.len); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t SetExtSki(HITLS_X509_Ext *ext, HITLS_X509_ExtEntry *entry, const void *val) { (void)ext; const HITLS_X509_ExtSki *ski = (const HITLS_X509_ExtSki *)val; entry->critical = ski->critical; if (ski->kid.dataLen < HITLS_X509_KID_MIN_LEN || ski->kid.dataLen > HITLS_X509_KID_MAX_LEN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_KID); return HITLS_X509_ERR_EXT_KID; } BSL_ASN1_Buffer asn = {BSL_ASN1_TAG_OCTETSTRING, ski->kid.dataLen, ski->kid.data}; BSL_ASN1_TemplateItem item = {BSL_ASN1_TAG_OCTETSTRING, 0, 0}; BSL_ASN1_Template templ = {&item, 1}; int32_t ret = BSL_ASN1_EncodeTemplate(&templ, &asn, 1, &entry->extnValue.buff, &entry->extnValue.len); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static void SetAsn1Templ(BSL_Buffer *value, uint8_t tag, BSL_ASN1_TemplateItem *item, BSL_ASN1_Buffer *asn) { item->tag = tag; asn->tag = tag; asn->len = value->dataLen; asn->buff = value->data; } static void FreeGnAsns(BSL_ASN1_Buffer *asns, uint32_t number) { for (uint32_t i = 0; i < number; i++) { if (asns[i].tag == HITLS_X509_GENERALNAME_DIR_TAG) { BSL_SAL_Free(asns[i].buff); } } BSL_SAL_Free(asns); } static int32_t GetSanDirNameExtnValue(BslList *dirNames, BSL_ASN1_Buffer *extnValue) { BSL_ASN1_Buffer tmp = {0}; int32_t ret = HITLS_X509_EncodeNameList((BSL_ASN1_List *)dirNames, &tmp); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_TemplateItem item = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}; BSL_ASN1_Template templ = {&item, 1}; ret = BSL_ASN1_EncodeTemplate(&templ, &tmp, 1, &extnValue->buff, &extnValue->len); BSL_SAL_Free(tmp.buff); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } extnValue->tag = HITLS_X509_GENERALNAME_DIR_TAG; return ret; } static int32_t SetGnEncodeParam(BslList *names, BSL_ASN1_TemplateItem *items, BSL_ASN1_Buffer *asns) { HITLS_X509_GeneralName **name = BSL_LIST_First(names); BSL_ASN1_TemplateItem *item = items; BSL_ASN1_Buffer *asn = asns; int32_t ret; while (name != NULL) { if ((*name)->value.data == NULL || (*name)->value.dataLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_SAN_ELE); return HITLS_X509_ERR_EXT_SAN_ELE; } switch ((*name)->type) { case HITLS_X509_GN_EMAIL: SetAsn1Templ(&(*name)->value, HITLS_X509_GENERALNAME_RFC822_TAG, item, asn); break; case HITLS_X509_GN_DNS: SetAsn1Templ(&(*name)->value, HITLS_X509_GENERALNAME_DNS_TAG, item, asn); break; case HITLS_X509_GN_DNNAME: ret = GetSanDirNameExtnValue((BSL_ASN1_List *)(*name)->value.data, asn); if (ret != HITLS_PKI_SUCCESS) { return ret; } item->tag = HITLS_X509_GENERALNAME_DIR_TAG; break; case HITLS_X509_GN_URI: SetAsn1Templ(&(*name)->value, HITLS_X509_GENERALNAME_URI_TAG, item, asn); break; case HITLS_X509_GN_IP: SetAsn1Templ(&(*name)->value, HITLS_X509_GENERALNAME_IP_TAG, item, asn); break; default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_GN_UNSUPPORT); return HITLS_X509_ERR_EXT_GN_UNSUPPORT; } item->depth = 1; item++; asn++; name = BSL_LIST_Next(names); } return HITLS_PKI_SUCCESS; } static int32_t AllocEncodeParam(BSL_ASN1_TemplateItem **items, uint32_t itemNum, BSL_ASN1_Buffer **asns, uint32_t asnNum) { *items = BSL_SAL_Calloc(itemNum, sizeof(BSL_ASN1_TemplateItem)); // sequence + names if (*items == NULL) { return BSL_MALLOC_FAIL; } *asns = BSL_SAL_Calloc(asnNum, sizeof(BSL_ASN1_Buffer)); if (*asns == NULL) { BSL_SAL_Free(*items); *items = NULL; return BSL_MALLOC_FAIL; } return HITLS_PKI_SUCCESS; } static int32_t SetExtGeneralNames(HITLS_X509_Ext *ext, HITLS_X509_ExtEntry *entry, const void *val) { (void)ext; const HITLS_X509_ExtSan *san = (const HITLS_X509_ExtSan *)val; if (san->names == NULL || BSL_LIST_COUNT(san->names) <= 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_SAN); return HITLS_X509_ERR_EXT_SAN; } entry->critical = san->critical; /* Encode extnValue */ BSL_ASN1_TemplateItem *items = NULL; BSL_ASN1_Buffer *asns = NULL; uint32_t number = (uint32_t)BSL_LIST_COUNT(san->names); int32_t ret = AllocEncodeParam(&items, 1 + number, &asns, number); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } items[0].depth = 0; items[0].tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; ret = SetGnEncodeParam(san->names, items + 1, asns); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_Free(items); FreeGnAsns(asns, number); BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_Template templ = {items, number + 1}; ret = BSL_ASN1_EncodeTemplate(&templ, asns, number, &entry->extnValue.buff, &entry->extnValue.len); BSL_SAL_Free(items); FreeGnAsns(asns, number); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t SetExtExKeyUsage(HITLS_X509_Ext *ext, HITLS_X509_ExtEntry *entry, const void *val) { (void)ext; const HITLS_X509_ExtExKeyUsage *exku = (const HITLS_X509_ExtExKeyUsage *)val; if (exku->oidList == NULL || BSL_LIST_COUNT(exku->oidList) <= 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_EXTENDED_KU); return HITLS_X509_ERR_EXT_EXTENDED_KU; } entry->critical = exku->critical; BSL_ASN1_TemplateItem *items = NULL; BSL_ASN1_Buffer *asns = NULL; uint32_t number = (uint32_t)BSL_LIST_COUNT(exku->oidList); int32_t ret = AllocEncodeParam(&items, number + 1, &asns, number); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } items[0].depth = 0; items[0].tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; BSL_Buffer **buffer = BSL_LIST_First(exku->oidList); for (uint32_t i = 0; i < number; i++) { if (buffer == NULL || *buffer == NULL || (*buffer)->dataLen == 0 || (*buffer)->data == NULL) { BSL_SAL_Free(items); BSL_SAL_Free(asns); BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_EXTENDED_KU_ELE); return HITLS_X509_ERR_EXT_EXTENDED_KU_ELE; } items[i + 1].depth = 1; items[i + 1].tag = BSL_ASN1_TAG_OBJECT_ID; asns[i].tag = BSL_ASN1_TAG_OBJECT_ID; asns[i].len = (*buffer)->dataLen; asns[i].buff = (*buffer)->data; buffer = BSL_LIST_Next(exku->oidList); } BSL_ASN1_Template templ = {items, number + 1}; ret = BSL_ASN1_EncodeTemplate(&templ, asns, number, &entry->extnValue.buff, &entry->extnValue.len); BSL_SAL_Free(items); BSL_SAL_Free(asns); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t SetExtCrlNumber(HITLS_X509_Ext *ext, HITLS_X509_ExtEntry *entry, const void *val) { if (ext->type != HITLS_X509_EXT_TYPE_CRL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_SET); return HITLS_X509_ERR_EXT_SET; } const HITLS_X509_ExtCrlNumber *crlNumber = (const HITLS_X509_ExtCrlNumber *)val; entry->critical = crlNumber->critical; if (crlNumber->crlNumber.dataLen < HITLS_X509_CRLNUMBER_MIN_LEN || crlNumber->crlNumber.dataLen > HITLS_X509_CRLNUMBER_MAX_LEN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_CRLNUMBER); return HITLS_X509_ERR_EXT_CRLNUMBER; } BSL_ASN1_Buffer asn = {BSL_ASN1_TAG_INTEGER, crlNumber->crlNumber.dataLen, crlNumber->crlNumber.data}; BSL_ASN1_TemplateItem item = {BSL_ASN1_TAG_INTEGER, 0, 0}; BSL_ASN1_Template templ = {&item, 1}; int32_t ret = BSL_ASN1_EncodeTemplate(&templ, &asn, 1, &entry->extnValue.buff, &entry->extnValue.len); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t HITLS_X509_SetExtList(void *param, BslList *extList, BslCid cid, BSL_Buffer *val, EncodeExtCb encodeExt) { HITLS_X509_ExtEntry *extEntry = NULL; bool isNew; int32_t ret = GetExtEntryByCid(extList, cid, &extEntry, &isNew); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = encodeExt(param, extEntry, val->data); if (ret != HITLS_PKI_SUCCESS) { FreeExtEntryCont(extEntry); if (isNew) { BSL_SAL_Free(extEntry); } return ret; } if (isNew) { ret = BSL_LIST_AddElement(extList, extEntry, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); FreeExtEntryCont(extEntry); BSL_SAL_Free(extEntry); return ret; } } return HITLS_PKI_SUCCESS; } static int32_t SetExt(HITLS_X509_Ext *ext, BslCid cid, BSL_Buffer *val, uint32_t expectLen, EncodeExtCb encodeExt) { if ((ext->flag & HITLS_X509_EXT_FLAG_PARSE) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_SET_AFTER_PARSE); return HITLS_X509_ERR_EXT_SET_AFTER_PARSE; } if (val->dataLen != expectLen) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } int32_t ret = HITLS_X509_SetExtList(ext, ext->extList, cid, val, encodeExt); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ext->flag |= HITLS_X509_EXT_FLAG_GEN; return ret; } static int32_t SetExtCtrl(HITLS_X509_Ext *ext, int32_t cmd, void *val, uint32_t valLen) { BSL_Buffer buff = {val, valLen}; switch (cmd) { case HITLS_X509_EXT_SET_BCONS: return SetExt(ext, BSL_CID_CE_BASICCONSTRAINTS, &buff, sizeof(HITLS_X509_ExtBCons), (EncodeExtCb)SetExtBCons); case HITLS_X509_EXT_SET_KUSAGE: return SetExt(ext, BSL_CID_CE_KEYUSAGE, &buff, sizeof(HITLS_X509_ExtKeyUsage), (EncodeExtCb)SetExtKeyUsage); case HITLS_X509_EXT_SET_AKI: return SetExt(ext, BSL_CID_CE_AUTHORITYKEYIDENTIFIER, &buff, sizeof(HITLS_X509_ExtAki), (EncodeExtCb)SetExtAki); case HITLS_X509_EXT_SET_SKI: return SetExt(ext, BSL_CID_CE_SUBJECTKEYIDENTIFIER, &buff, sizeof(HITLS_X509_ExtSki), (EncodeExtCb)SetExtSki); case HITLS_X509_EXT_SET_SAN: return SetExt(ext, BSL_CID_CE_SUBJECTALTNAME, &buff, sizeof(HITLS_X509_ExtSan), (EncodeExtCb)SetExtGeneralNames); case HITLS_X509_EXT_SET_EXKUSAGE: return SetExt(ext, BSL_CID_CE_EXTKEYUSAGE, &buff, sizeof(HITLS_X509_ExtExKeyUsage), (EncodeExtCb)SetExtExKeyUsage); case HITLS_X509_EXT_SET_CRLNUMBER: return SetExt(ext, BSL_CID_CE_CRLNUMBER, &buff, sizeof(HITLS_X509_ExtCrlNumber), (EncodeExtCb)SetExtCrlNumber); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } int32_t HITLS_X509_SetGeneralNames(HITLS_X509_ExtEntry *extEntry, void *val) { if (extEntry == NULL || val == NULL) { return BSL_NULL_INPUT; } return SetExtGeneralNames(NULL, extEntry, val); } #endif int32_t HITLS_X509_GetExt(BslList *ext, BslCid cid, BSL_Buffer *val, uint32_t expectLen, DecodeExtCb decodeExt) { if (ext == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_NOT_FOUND); return HITLS_X509_ERR_EXT_NOT_FOUND; } if (val->dataLen != expectLen) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } HITLS_X509_ExtEntry *extEntry = BSL_LIST_Search(ext, &cid, CmpExtByCid, NULL); if (extEntry == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_NOT_FOUND); return HITLS_X509_ERR_EXT_NOT_FOUND; } return decodeExt(extEntry, val->data); } static int32_t GetExtKeyUsage(HITLS_X509_Ext *ext, uint32_t *val, uint32_t valLen) { if (val == NULL || valLen != sizeof(uint32_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } HITLS_X509_CertExt *certExt = (HITLS_X509_CertExt *)ext->extData; *val = certExt->extFlags & HITLS_X509_EXT_FLAG_KUSAGE ? certExt->keyUsage : HITLS_X509_EXT_KU_NONE; return HITLS_PKI_SUCCESS; } static int32_t GetExtCtrl(HITLS_X509_Ext *ext, int32_t cmd, void *val, uint32_t valLen) { BSL_Buffer buff = {val, valLen}; switch (cmd) { case HITLS_X509_EXT_GET_SKI: return HITLS_X509_GetExt(ext->extList, BSL_CID_CE_SUBJECTKEYIDENTIFIER, &buff, sizeof(HITLS_X509_ExtSki), (DecodeExtCb)HITLS_X509_ParseSubjectKeyId); case HITLS_X509_EXT_GET_AKI: return HITLS_X509_GetExt(ext->extList, BSL_CID_CE_AUTHORITYKEYIDENTIFIER, &buff, sizeof(HITLS_X509_ExtAki), (DecodeExtCb)HITLS_X509_ParseAuthorityKeyId); case HITLS_X509_EXT_GET_CRLNUMBER: return HITLS_X509_GetExt(ext->extList, BSL_CID_CE_CRLNUMBER, &buff, sizeof(HITLS_X509_ExtCrlNumber), (DecodeExtCb)X509_ParseCrlNumber); case HITLS_X509_EXT_GET_KUSAGE: return GetExtKeyUsage(ext, val, valLen); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } static int32_t CheckExtByCid(HITLS_X509_Ext *ext, int32_t cid, bool *val, uint32_t valLen) { if (valLen != sizeof(bool)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } *val = BSL_LIST_Search(ext->extList, &cid, CmpExtByCid, NULL) != NULL; return HITLS_PKI_SUCCESS; } bool X509_CheckCmdValid(int32_t *cmdSet, uint32_t cmdSize, int32_t cmd) { for (uint32_t i = 0; i < cmdSize; i++) { if (cmd == cmdSet[i]) { return true; } } return false; } int32_t X509_ExtCtrl(HITLS_X509_Ext *ext, int32_t cmd, void *val, uint32_t valLen) { #if defined(HITLS_PKI_X509_CRT_GEN) || defined(HITLS_PKI_X509_CRL_GEN) || defined(HITLS_PKI_X509_CSR_GEN) if (cmd >= HITLS_X509_EXT_SET_SKI && cmd < HITLS_X509_EXT_GET_SKI) { return SetExtCtrl(ext, cmd, val, valLen); } #endif if (cmd >= HITLS_X509_EXT_GET_SKI && cmd < HITLS_X509_EXT_CHECK_SKI) { return GetExtCtrl(ext, cmd, val, valLen); } if (cmd >= HITLS_X509_EXT_CHECK_SKI && cmd < HITLS_X509_CSR_GET_ATTRIBUTES) { return CheckExtByCid(ext, BSL_CID_CE_SUBJECTKEYIDENTIFIER, val, valLen); } BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } int32_t HITLS_X509_ExtCtrl(HITLS_X509_Ext *ext, int32_t cmd, void *val, uint32_t valLen) { if (ext == NULL || val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (ext->type == HITLS_X509_EXT_TYPE_CERT || ext->type == HITLS_X509_EXT_TYPE_CRL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_UNSUPPORT); return HITLS_X509_ERR_EXT_UNSUPPORT; } static int32_t cmdSet[] = {HITLS_X509_EXT_SET_SKI, HITLS_X509_EXT_SET_AKI, HITLS_X509_EXT_SET_KUSAGE, HITLS_X509_EXT_SET_SAN, HITLS_X509_EXT_SET_BCONS, HITLS_X509_EXT_SET_EXKUSAGE, HITLS_X509_EXT_GET_SKI, HITLS_X509_EXT_GET_AKI, HITLS_X509_EXT_CHECK_SKI, HITLS_X509_EXT_GET_KUSAGE}; if (!X509_CheckCmdValid(cmdSet, sizeof(cmdSet) / sizeof(int32_t), cmd)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_UNSUPPORT); return HITLS_X509_ERR_EXT_UNSUPPORT; } return X509_ExtCtrl(ext, cmd, val, valLen); } void HITLS_X509_ExtEntryFree(HITLS_X509_ExtEntry *entry) { if (entry == NULL) { return; } BSL_SAL_FREE(entry->extnId.buff); BSL_SAL_FREE(entry->extnValue.buff); BSL_SAL_Free(entry); } #if defined(HITLS_PKI_X509_CRT_GEN) || defined(HITLS_PKI_X509_CRL_GEN) || defined(HITLS_PKI_X509_CSR_GEN) /** * RFC 5280: section-4.1 * Extension ::= SEQUENCE { extnID OBJECT IDENTIFIER, critical BOOLEAN DEFAULT FALSE, extnValue OCTET STRING -- contains the DER encoding of an ASN.1 value -- corresponding to the extension type identified -- by extnID } */ static BSL_ASN1_TemplateItem g_extSeqTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, {BSL_ASN1_TAG_OBJECT_ID, 0, 1}, {BSL_ASN1_TAG_BOOLEAN, BSL_ASN1_FLAG_DEFAULT, 1}, {BSL_ASN1_TAG_OCTETSTRING, 1, 1}, }; #define X509_CRLEXT_ELEM_NUMBER 3 int32_t HITLS_X509_EncodeExtEntry(BSL_ASN1_List *list, BSL_ASN1_Buffer *ext) { uint32_t count = (uint32_t)BSL_LIST_COUNT(list); BSL_ASN1_Buffer *asnBuf = BSL_SAL_Malloc(count * X509_CRLEXT_ELEM_NUMBER * sizeof(BSL_ASN1_Buffer)); if (asnBuf == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } uint32_t iter = 0; HITLS_X509_ExtEntry *node = NULL; for (node = BSL_LIST_GET_FIRST(list); node != NULL; node = BSL_LIST_GET_NEXT(list)) { asnBuf[iter].tag = node->extnId.tag; asnBuf[iter].buff = node->extnId.buff; asnBuf[iter++].len = node->extnId.len; asnBuf[iter].tag = BSL_ASN1_TAG_BOOLEAN; asnBuf[iter].len = node->critical ? 1 : 0; asnBuf[iter++].buff = node->critical ? (uint8_t *)&(node->critical) : NULL; asnBuf[iter].tag = node->extnValue.tag; asnBuf[iter].buff = node->extnValue.buff; asnBuf[iter++].len = node->extnValue.len; } BSL_ASN1_Template templ = {g_extSeqTempl, sizeof(g_extSeqTempl) / sizeof(g_extSeqTempl[0])}; int32_t ret = BSL_ASN1_EncodeListItem(BSL_ASN1_TAG_SEQUENCE, count, &templ, asnBuf, iter, ext); BSL_SAL_Free(asnBuf); return ret; } int32_t HITLS_X509_EncodeExt(uint8_t tag, BSL_ASN1_List *list, BSL_ASN1_Buffer *ext) { if (BSL_LIST_COUNT(list) <= 0) { ext->tag = tag; ext->len = 0; ext->buff = NULL; return HITLS_PKI_SUCCESS; } BSL_ASN1_Buffer extbuff = {0}; int32_t ret = HITLS_X509_EncodeExtEntry(list, &extbuff); if (ret != HITLS_PKI_SUCCESS) { return ret; } BSL_ASN1_TemplateItem extTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, }; BSL_ASN1_Template templ = {extTempl, 1}; ret = BSL_ASN1_EncodeTemplate(&templ, &extbuff, 1, &(ext->buff), &(ext->len)); BSL_SAL_Free(extbuff.buff); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ext->tag = tag; return HITLS_PKI_SUCCESS; } #endif // HITLS_PKI_X509_CRT_GEN || HITLS_PKI_X509_CRL_GEN || HITLS_PKI_X509_CSR_GEN #if defined(HITLS_PKI_X509_CRT_GEN) || defined(HITLS_PKI_X509_CRL_GEN) HITLS_X509_ExtEntry *X509_DupExtEntry(const HITLS_X509_ExtEntry *src) { /* Src is not null. */ HITLS_X509_ExtEntry *dest = BSL_SAL_Malloc(sizeof(HITLS_X509_ExtEntry)); if (dest == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } dest->cid = src->cid; dest->critical = src->critical; // extId dest->extnId.tag = src->extnId.tag; dest->extnId.len = src->extnId.len; if (src->extnId.len != 0) { dest->extnId.buff = BSL_SAL_Dump(src->extnId.buff, src->extnId.len); if (dest->extnId.buff == NULL) { BSL_SAL_Free(dest); BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return NULL; } } // extnValue dest->extnValue.tag = src->extnValue.tag; dest->extnValue.len = src->extnValue.len; if (src->extnValue.len != 0) { dest->extnValue.buff = BSL_SAL_Dump(src->extnValue.buff, src->extnValue.len); if (dest->extnValue.buff == NULL) { BSL_SAL_Free(dest->extnId.buff); BSL_SAL_Free(dest); BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return NULL; } } return dest; } #endif #ifdef HITLS_PKI_X509_CRT_GEN int32_t HITLS_X509_ExtReplace(HITLS_X509_Ext *dest, HITLS_X509_Ext *src) { if (dest == NULL || dest->extData == NULL || src == NULL || src->extData == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if ((dest->flag & HITLS_X509_EXT_FLAG_PARSE) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_SET_AFTER_PARSE); return HITLS_X509_ERR_EXT_SET_AFTER_PARSE; } HITLS_X509_CertExt *certExt = (HITLS_X509_CertExt *)dest->extData; HITLS_X509_CertExt *srcExt = (HITLS_X509_CertExt *)src->extData; certExt->isCa = srcExt->isCa; certExt->maxPathLen = srcExt->maxPathLen; certExt->keyUsage = srcExt->keyUsage; certExt->extFlags = srcExt->extFlags; if (BSL_LIST_COUNT(src->extList) <= 0) { BSL_LIST_DeleteAll(dest->extList, (BSL_LIST_PFUNC_FREE)HITLS_X509_ExtEntryFree); return HITLS_PKI_SUCCESS; } BslList *list = BSL_LIST_Copy(src->extList, (BSL_LIST_PFUNC_DUP)X509_DupExtEntry, (BSL_LIST_PFUNC_FREE)HITLS_X509_ExtEntryFree); if (list == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_SET); return HITLS_X509_ERR_EXT_SET; } BSL_LIST_FREE(dest->extList, (BSL_LIST_PFUNC_FREE)HITLS_X509_ExtEntryFree); dest->extList = list; dest->flag |= HITLS_X509_EXT_FLAG_GEN; return HITLS_PKI_SUCCESS; } #endif HITLS_X509_Ext *HITLS_X509_ExtNew(int32_t type) { if (type == HITLS_X509_EXT_TYPE_CERT || type == HITLS_X509_EXT_TYPE_CRL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return NULL; } return X509_ExtNew(NULL, type); } void HITLS_X509_ExtFree(HITLS_X509_Ext *ext) { X509_ExtFree(ext, true); } #endif // HITLS_PKI_X509
2401_83913325/openHiTLS-examples_2461
pki/x509_common/src/hitls_x509_ext.c
C
unknown
52,232
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_CRL_LOCAL_H #define HITLS_CRL_LOCAL_H #include "hitls_build.h" #ifdef HITLS_PKI_X509_CRL #include <stdint.h> #include "bsl_asn1_internal.h" #include "bsl_obj.h" #include "sal_atomic.h" #include "hitls_x509_local.h" #ifdef __cplusplus extern "C" { #endif #define HITLS_X509_CRL_PARSE_FLAG 0x01 #define HITLS_X509_CRL_GEN_FLAG 0x02 #define BSL_TIME_REVOKE_TIME_IS_GMT 0x4 typedef struct _HITLS_X509_CrlEntry { uint8_t flag; BSL_ASN1_Buffer serialNumber; BSL_TIME time; BSL_ASN1_List *extList; } HITLS_X509_CrlEntry; typedef struct { uint8_t *tbsRawData; uint32_t tbsRawDataLen; int32_t version; HITLS_X509_Asn1AlgId signAlgId; BSL_ASN1_List *issuerName; HITLS_X509_ValidTime validTime; BSL_ASN1_List *revokedCerts; HITLS_X509_Ext crlExt; } HITLS_X509_CrlTbs; typedef enum { HITLS_X509_CRL_STATE_NEW = 0, HITLS_X509_CRL_STATE_SET, HITLS_X509_CRL_STATE_SIGN, HITLS_X509_CRL_STATE_GEN, } HITLS_X509_CRL_STATE; typedef struct _HITLS_X509_Crl { uint8_t flag; uint8_t state; uint8_t *rawData; uint32_t rawDataLen; HITLS_X509_CrlTbs tbs; HITLS_X509_Asn1AlgId signAlgId; BSL_ASN1_BitString signature; BSL_SAL_RefCount references; } HITLS_X509_Crl; int32_t HITLS_ParseCrlExtInvalidTime(HITLS_X509_ExtEntry *extEntry, void *val); int32_t HITLS_ParseCrlExtReason(HITLS_X509_ExtEntry *extEntry, void *val); #ifdef __cplusplus } #endif #endif // HITLS_PKI_X509_CRL #endif // HITLS_CRL_LOCAL_H
2401_83913325/openHiTLS-examples_2461
pki/x509_crl/include/hitls_crl_local.h
C
unknown
2,054
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_PKI_X509_CRL #include "securec.h" #include "bsl_sal.h" #include "bsl_obj_internal.h" #include "bsl_log_internal.h" #ifdef HITLS_BSL_PEM #include "bsl_pem_internal.h" #endif #include "bsl_err_internal.h" #include "sal_time.h" #ifdef HITLS_BSL_SAL_FILE #include "sal_file.h" #endif #include "crypt_errno.h" #include "hitls_pki_errno.h" #include "hitls_x509_local.h" #include "hitls_crl_local.h" #include "hitls_pki_crl.h" #define HITLS_CRL_CTX_SPECIFIC_TAG_EXTENSION 0 #ifdef HITLS_PKI_X509_CRL_PARSE BSL_ASN1_TemplateItem g_crlTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* x509 */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, /* tbs */ /* 2: version */ {BSL_ASN1_TAG_INTEGER, BSL_ASN1_FLAG_DEFAULT, 2}, /* 2: signature info */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 2}, {BSL_ASN1_TAG_OBJECT_ID, 0, 3}, {BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL, 3}, // 6 /* 2: issuer */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 2}, /* 2: validity */ {BSL_ASN1_TAG_CHOICE, 0, 2}, {BSL_ASN1_TAG_CHOICE, BSL_ASN1_FLAG_OPTIONAL, 2}, /* 2: revoked crl list */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME | BSL_ASN1_FLAG_OPTIONAL, 2}, /* 2: extension */ {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_CRL_CTX_SPECIFIC_TAG_EXTENSION, BSL_ASN1_FLAG_OPTIONAL | BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 2}, // 11 {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, /* signAlg */ {BSL_ASN1_TAG_OBJECT_ID, 0, 2}, {BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL, 2}, {BSL_ASN1_TAG_BITSTRING, 0, 1} /* sig */ }; typedef enum { HITLS_X509_CRL_VERSION_IDX, HITLS_X509_CRL_TBS_SIGNALG_OID_IDX, HITLS_X509_CRL_TBS_SIGNALG_ANY_IDX, HITLS_X509_CRL_ISSUER_IDX, HITLS_X509_CRL_BEFORE_VALID_IDX, HITLS_X509_CRL_AFTER_VALID_IDX, HITLS_X509_CRL_CRL_LIST_IDX, HITLS_X509_CRL_EXT_IDX, HITLS_X509_CRL_SIGNALG_IDX, HITLS_X509_CRL_SIGNALG_ANY_IDX, HITLS_X509_CRL_SIGN_IDX, HITLS_X509_CRL_MAX_IDX, } HITLS_X509_CRL_IDX; int32_t HITLS_X509_CrlTagGetOrCheck(int32_t type, uint32_t idx, void *data, void *expVal) { (void) idx; switch (type) { case BSL_ASN1_TYPE_CHECK_CHOICE_TAG: { uint8_t tag = *(uint8_t *) data; if ((tag == BSL_ASN1_TAG_UTCTIME) || (tag == BSL_ASN1_TAG_GENERALIZEDTIME)) { *(uint8_t *) expVal = tag; return BSL_SUCCESS; } return HITLS_X509_ERR_CHECK_TAG; } case BSL_ASN1_TYPE_GET_ANY_TAG: { BSL_ASN1_Buffer *param = (BSL_ASN1_Buffer *) data; BslOidString oidStr = {param->len, (char *)param->buff, 0}; BslCid cid = BSL_OBJ_GetCID(&oidStr); if (cid == BSL_CID_UNKNOWN) { return HITLS_X509_ERR_GET_ANY_TAG; } if (cid == BSL_CID_RSASSAPSS) { // note: any It can be encoded empty or it can be null *(uint8_t *) expVal = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; return BSL_SUCCESS; } else { *(uint8_t *) expVal = BSL_ASN1_TAG_NULL; // is null return BSL_SUCCESS; } return HITLS_X509_ERR_GET_ANY_TAG; } default: return HITLS_X509_ERR_INVALID_PARAM; } } #endif // HITLS_PKI_X509_CRL_PARSE void HITLS_X509_CrlFree(HITLS_X509_Crl *crl) { if (crl == NULL) { return; } int ret = 0; BSL_SAL_AtomicDownReferences(&(crl->references), &ret); if (ret > 0) { return; } if ((crl->flag & HITLS_X509_CRL_GEN_FLAG) != 0) { BSL_LIST_FREE(crl->tbs.issuerName, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeNameNode); BSL_SAL_FREE(crl->tbs.tbsRawData); BSL_SAL_FREE(crl->signature.buff); } else { BSL_LIST_FREE(crl->tbs.issuerName, NULL); } #ifdef HITLS_CRYPTO_SM2 if (crl->signAlgId.algId == BSL_CID_SM2DSAWITHSM3) { BSL_SAL_FREE(crl->signAlgId.sm2UserId.data); } #endif BSL_LIST_FREE(crl->tbs.revokedCerts, (BSL_LIST_PFUNC_FREE)HITLS_X509_CrlEntryFree); X509_ExtFree(&crl->tbs.crlExt, false); BSL_SAL_ReferencesFree(&(crl->references)); BSL_SAL_FREE(crl->rawData); BSL_SAL_Free(crl); return; } HITLS_X509_Crl *HITLS_X509_CrlNew(void) { HITLS_X509_Crl *crl = NULL; BSL_ASN1_List *issuerName = NULL; BSL_ASN1_List *entryList = NULL; HITLS_X509_Ext *ext = NULL; crl = (HITLS_X509_Crl *)BSL_SAL_Calloc(1, sizeof(HITLS_X509_Crl)); if (crl == NULL) { return NULL; } issuerName = BSL_LIST_New(sizeof(HITLS_X509_NameNode)); if (issuerName == NULL) { goto ERR; } entryList = BSL_LIST_New(sizeof(HITLS_X509_CrlEntry)); if (entryList == NULL) { goto ERR; } ext = X509_ExtNew(&crl->tbs.crlExt, HITLS_X509_EXT_TYPE_CRL); if (ext == NULL) { goto ERR; } BSL_SAL_ReferencesInit(&(crl->references)); crl->tbs.issuerName = issuerName; crl->tbs.revokedCerts = entryList; crl->state = HITLS_X509_CRL_STATE_NEW; return crl; ERR: BSL_SAL_Free(crl); BSL_SAL_Free(issuerName); BSL_SAL_Free(entryList); return NULL; } #ifdef HITLS_PKI_X509_CRL_PARSE int32_t HITLS_CRL_ParseExtAsnItem(uint32_t layer, BSL_ASN1_Buffer *asn, void *param, BSL_ASN1_List *list) { (void) param; (void) layer; HITLS_X509_ExtEntry extEntry = {0}; int32_t ret = HITLS_X509_ParseExtItem(asn, &extEntry); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return HITLS_X509_AddListItemDefault(&extEntry, sizeof(HITLS_X509_ExtEntry), list); } int32_t HITLS_CRL_ParseExtSeqof(uint32_t layer, BSL_ASN1_Buffer *asn, void *param, BSL_ASN1_List *list) { if (layer == 1) { return HITLS_PKI_SUCCESS; } return HITLS_CRL_ParseExtAsnItem(layer, asn, param, list); } int32_t HITLS_X509_ParseCrlExt(BSL_ASN1_Buffer *ext, HITLS_X509_Crl *crl) { if ((crl->tbs.crlExt.flag & HITLS_X509_EXT_FLAG_GEN) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_PARSE_AFTER_SET); return HITLS_X509_ERR_EXT_PARSE_AFTER_SET; } uint8_t expTag[] = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE}; BSL_ASN1_DecodeListParam listParam = {2, expTag}; int32_t ret = BSL_ASN1_DecodeListItem(&listParam, ext, &HITLS_CRL_ParseExtSeqof, crl, crl->tbs.crlExt.extList); if (ret != BSL_SUCCESS) { BSL_LIST_DeleteAll(crl->tbs.crlExt.extList, NULL); BSL_ERR_PUSH_ERROR(ret); return ret; } crl->tbs.crlExt.flag |= HITLS_X509_EXT_FLAG_PARSE; return ret; } BSL_ASN1_TemplateItem g_crlEntryTempl[] = { {BSL_ASN1_TAG_INTEGER, 0, 0}, {BSL_ASN1_TAG_CHOICE, 0, 0}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_OPTIONAL | BSL_ASN1_FLAG_HEADERONLY, 0} }; typedef enum { HITLS_X509_CRLENTRY_NUM_IDX, HITLS_X509_CRLENTRY_TIME_IDX, HITLS_X509_CRLENTRY_EXT_IDX, HITLS_X509_CRLENTRY_MAX_IDX } HITLS_X509_CRLENTRY_IDX; #endif // HITLS_PKI_X509_CRL_PARSE int32_t HITLS_X509_CrlEntryChoiceCheck(int32_t type, uint32_t idx, void *data, void *expVal) { (void) idx; (void) expVal; if (type == BSL_ASN1_TYPE_CHECK_CHOICE_TAG) { uint8_t tag = *(uint8_t *) data; if ((tag & BSL_ASN1_TAG_UTCTIME) != 0 || (tag & BSL_ASN1_TAG_GENERALIZEDTIME) != 0) { *(uint8_t *) expVal = tag; return BSL_SUCCESS; } return HITLS_X509_ERR_CHECK_TAG; } return HITLS_X509_ERR_CHECK_TAG; } #ifdef HITLS_PKI_X509_CRL_PARSE static int32_t DecodeCrlRevokeExt(BSL_ASN1_Buffer *asnArr, HITLS_X509_CrlEntry *crlEntry) { if (asnArr->buff == NULL) { return HITLS_PKI_SUCCESS; } BslList *list = BSL_LIST_New(sizeof(HITLS_X509_ExtEntry)); if (list == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } uint8_t expTag = (BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE); BSL_ASN1_DecodeListParam listParam = {1, &expTag}; int32_t ret = BSL_ASN1_DecodeListItem(&listParam, asnArr, (BSL_ASN1_ParseListAsnItem)HITLS_CRL_ParseExtAsnItem, NULL, list); if (ret != BSL_SUCCESS) { BSL_LIST_FREE(list, NULL); return ret; } crlEntry->extList = list; return HITLS_PKI_SUCCESS; } int32_t HITLS_CRL_ParseCrlEntry(BSL_ASN1_Buffer *extItem, HITLS_X509_CrlEntry *crlEntry) { uint8_t *temp = extItem->buff; uint32_t tempLen = extItem->len; BSL_ASN1_Buffer asnArr[HITLS_X509_CRLENTRY_MAX_IDX] = {0}; BSL_ASN1_Template templ = {g_crlEntryTempl, sizeof(g_crlEntryTempl) / sizeof(g_crlEntryTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, HITLS_X509_CrlEntryChoiceCheck, &temp, &tempLen, asnArr, HITLS_X509_CRLENTRY_MAX_IDX); if (tempLen != 0) { ret = HITLS_X509_ERR_CRL_ENTRY; } if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } crlEntry->serialNumber = asnArr[HITLS_X509_CRLENTRY_NUM_IDX]; ret = BSL_ASN1_DecodePrimitiveItem(&asnArr[HITLS_X509_CRLENTRY_TIME_IDX], &crlEntry->time); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (asnArr[HITLS_X509_CRLENTRY_TIME_IDX].tag == BSL_ASN1_TAG_GENERALIZEDTIME) { crlEntry->flag |= BSL_TIME_REVOKE_TIME_IS_GMT; } ret = DecodeCrlRevokeExt(&asnArr[HITLS_X509_CRLENTRY_EXT_IDX], crlEntry); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t HITLS_CRL_ParseCrlAsnItem(uint32_t layer, BSL_ASN1_Buffer *asn, void *param, BSL_ASN1_List *list) { (void) param; (void) layer; HITLS_X509_CrlEntry crlEntry = {0}; int32_t ret = HITLS_CRL_ParseCrlEntry(asn, &crlEntry); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } crlEntry.flag |= HITLS_X509_CRL_PARSE_FLAG; return HITLS_X509_AddListItemDefault(&crlEntry, sizeof(HITLS_X509_CrlEntry), list); } int32_t HITLS_X509_ParseCrlList(BSL_ASN1_Buffer *crl, BSL_ASN1_List *list) { // crl is optional if (crl->tag == 0) { return HITLS_PKI_SUCCESS; } uint8_t expTag = (BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE); BSL_ASN1_DecodeListParam listParam = {1, &expTag}; int32_t ret = BSL_ASN1_DecodeListItem(&listParam, crl, &HITLS_CRL_ParseCrlAsnItem, NULL, list); if (ret != BSL_SUCCESS) { BSL_LIST_DeleteAll(list, NULL); } return ret; } int32_t HITLS_X509_ParseCrlTbs(BSL_ASN1_Buffer *asnArr, HITLS_X509_Crl *crl) { int32_t ret; if (asnArr[HITLS_X509_CRL_VERSION_IDX].tag != 0) { ret = BSL_ASN1_DecodePrimitiveItem(&asnArr[HITLS_X509_CRL_VERSION_IDX], &crl->tbs.version); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } else { crl->tbs.version = 0; } // sign alg ret = HITLS_X509_ParseSignAlgInfo(&asnArr[HITLS_X509_CRL_TBS_SIGNALG_OID_IDX], &asnArr[HITLS_X509_CRL_TBS_SIGNALG_ANY_IDX], &crl->tbs.signAlgId); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // issuer name ret = HITLS_X509_ParseNameList(&asnArr[HITLS_X509_CRL_ISSUER_IDX], crl->tbs.issuerName); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // validity ret = HITLS_X509_ParseTime(&asnArr[HITLS_X509_CRL_BEFORE_VALID_IDX], &asnArr[HITLS_X509_CRL_AFTER_VALID_IDX], &crl->tbs.validTime); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } // crl list ret = HITLS_X509_ParseCrlList(&asnArr[HITLS_X509_CRL_CRL_LIST_IDX], crl->tbs.revokedCerts); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // ext ret = HITLS_X509_ParseCrlExt(&asnArr[HITLS_X509_CRL_EXT_IDX], crl); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } return ret; ERR: BSL_LIST_DeleteAll(crl->tbs.issuerName, NULL); BSL_LIST_DeleteAll(crl->tbs.revokedCerts, NULL); return ret; } #endif // HITLS_PKI_X509_CRL_PARSE #ifdef HITLS_PKI_X509_CRL_GEN static void X509_EncodeCrlValidTime(HITLS_X509_ValidTime *crlTime, BSL_ASN1_Buffer *validTime) { validTime[0].tag = (crlTime->flag & BSL_TIME_BEFORE_IS_UTC) != 0 ? BSL_ASN1_TAG_UTCTIME : BSL_ASN1_TAG_GENERALIZEDTIME; validTime[0].len = sizeof(BSL_TIME); validTime[0].buff = (uint8_t *)&(crlTime->start); validTime[1].tag = (crlTime->flag & BSL_TIME_AFTER_IS_UTC) != 0 ? BSL_ASN1_TAG_UTCTIME : BSL_ASN1_TAG_GENERALIZEDTIME; if ((crlTime->flag & BSL_TIME_AFTER_SET) != 0) { validTime[1].len = sizeof(BSL_TIME); validTime[1].buff = (uint8_t *)&(crlTime->end); } else { validTime[1].len = 0; validTime[1].buff = NULL; } } static int32_t X509_EncodeCrlEntry(HITLS_X509_CrlEntry *crlEntry, BSL_ASN1_Buffer *asnBuf) { asnBuf[0].tag = crlEntry->serialNumber.tag; asnBuf[0].buff = crlEntry->serialNumber.buff; asnBuf[0].len = crlEntry->serialNumber.len; asnBuf[1].tag = (crlEntry->flag & BSL_TIME_REVOKE_TIME_IS_GMT) != 0 ? BSL_ASN1_TAG_GENERALIZEDTIME : BSL_ASN1_TAG_UTCTIME; asnBuf[1].buff = (uint8_t *)&(crlEntry->time); asnBuf[1].len = sizeof(BSL_TIME); if (crlEntry->extList != NULL && BSL_LIST_COUNT(crlEntry->extList) > 0) { return HITLS_X509_EncodeExtEntry(crlEntry->extList, &asnBuf[2]); // 2: extensions } else { asnBuf[2].tag = 0; // 2: extensions asnBuf[2].buff = NULL; // 2: extensions asnBuf[2].len = 0; // 2: extensions return HITLS_PKI_SUCCESS; } } #define X509_CRLENTRY_ELEM_NUMBER 3 int32_t HITLS_X509_EncodeRevokeCrlList(BSL_ASN1_List *crlList, BSL_ASN1_Buffer *revokeBuf) { int32_t count = BSL_LIST_COUNT(crlList); if (count <= 0) { revokeBuf->buff = NULL; revokeBuf->len = 0; revokeBuf->tag = BSL_ASN1_TAG_SEQUENCE; return HITLS_PKI_SUCCESS; } BSL_ASN1_Buffer *asnBuf = BSL_SAL_Malloc((uint32_t)count * sizeof(BSL_ASN1_Buffer) * X509_CRLENTRY_ELEM_NUMBER); if (asnBuf == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } (void)memset_s(asnBuf, (uint32_t)count * sizeof(BSL_ASN1_Buffer) * X509_CRLENTRY_ELEM_NUMBER, 0, (uint32_t)count * sizeof(BSL_ASN1_Buffer) * X509_CRLENTRY_ELEM_NUMBER); HITLS_X509_CrlEntry *crlEntry = NULL; uint32_t iter = 0; int32_t ret; for (crlEntry = BSL_LIST_GET_FIRST(crlList); crlEntry != NULL; crlEntry = BSL_LIST_GET_NEXT(crlList)) { ret = X509_EncodeCrlEntry(crlEntry, &asnBuf[iter]); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } iter += X509_CRLENTRY_ELEM_NUMBER; } BSL_ASN1_TemplateItem crlEntryTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_SAME | BSL_ASN1_FLAG_OPTIONAL, 0}, {BSL_ASN1_TAG_INTEGER, 0, 1}, {BSL_ASN1_TAG_CHOICE, 0, 1}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_OPTIONAL, 1} }; BSL_ASN1_Template templ = {crlEntryTempl, sizeof(crlEntryTempl) / sizeof(crlEntryTempl[0])}; ret = BSL_ASN1_EncodeListItem(BSL_ASN1_TAG_SEQUENCE, (uint32_t)count, &templ, asnBuf, iter, revokeBuf); EXIT: for (int32_t i = 0; i < count; i++) { /** * The memory for the extension in CRLentry needs to be freed up. * The subscript 2 corresponds to the extension. */ BSL_SAL_Free(asnBuf[i * X509_CRLENTRY_ELEM_NUMBER + 2].buff); } BSL_SAL_Free(asnBuf); return ret; } BSL_ASN1_TemplateItem g_crlTbsTempl[] = { /* 1: version */ {BSL_ASN1_TAG_INTEGER, BSL_ASN1_FLAG_DEFAULT, 0}, /* 2: signature info */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 0}, /* 3: issuer */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 0}, /* 4-5: validity */ {BSL_ASN1_TAG_CHOICE, 0, 0}, {BSL_ASN1_TAG_CHOICE, BSL_ASN1_FLAG_OPTIONAL, 0}, /* 6: revoked crl list */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME | BSL_ASN1_FLAG_OPTIONAL, 0}, /* 7: extension */ {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_CRL_CTX_SPECIFIC_TAG_EXTENSION, BSL_ASN1_FLAG_OPTIONAL | BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 0}, // 11 }; int32_t HITLS_X509_EncodeCrlExt(HITLS_X509_Ext *crlExt, BSL_ASN1_Buffer *ext) { return HITLS_X509_EncodeExt( BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_CRL_CTX_SPECIFIC_TAG_EXTENSION, crlExt->extList, ext); } /** * RFC 5280 sec 5.1.2.1 * This optional field describes the version of the encoded CRL. When * extensions are used, as required by this profile, this field MUST be * present and MUST specify version 2 (the integer value is 1). */ static void X509_EncodeVersion(uint8_t *version, BSL_ASN1_Buffer *asn) { if (*version == 1) { asn->tag = BSL_ASN1_TAG_INTEGER; asn->len = 1; asn->buff = version; } else { asn->tag = BSL_ASN1_TAG_INTEGER; asn->len = 0; asn->buff = NULL; } } #define X509_CRLTBS_ELEM_NUMBER 7 int32_t HITLS_X509_EncodeCrlTbsRaw(HITLS_X509_CrlTbs *crlTbs, BSL_ASN1_Buffer *asn) { BSL_ASN1_Buffer asnArr[X509_CRLTBS_ELEM_NUMBER] = {0}; uint8_t version = (uint8_t)crlTbs->version; X509_EncodeVersion(&version, asnArr); // 0 is version BSL_ASN1_Buffer *signAlgAsn = &asnArr[1]; // 1 is signAlg BSL_ASN1_Buffer *issuerAsn = &asnArr[2]; // 2 is issuer name BSL_ASN1_Buffer *revokeBuf = &asnArr[5]; // 5 is revoke list BSL_ASN1_Buffer *crlExt = &asnArr[6]; // 6 is crl extension int32_t ret = HITLS_X509_EncodeSignAlgInfo(&crlTbs->signAlgId, signAlgAsn); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_X509_EncodeNameList(crlTbs->issuerName, issuerAsn); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } X509_EncodeCrlValidTime(&crlTbs->validTime, &asnArr[3]); // 3 is valid time ret = HITLS_X509_EncodeRevokeCrlList(crlTbs->revokedCerts, revokeBuf); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = HITLS_X509_EncodeCrlExt(&(crlTbs->crlExt), crlExt); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } BSL_ASN1_Template templ = {g_crlTbsTempl, sizeof(g_crlTbsTempl) / sizeof(g_crlTbsTempl[0])}; ret = BSL_ASN1_EncodeTemplate(&templ, asnArr, X509_CRLTBS_ELEM_NUMBER, &(asn->buff), &(asn->len)); if (ret != HITLS_PKI_SUCCESS) { goto EXIT; } asn->tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; EXIT: BSL_SAL_Free(signAlgAsn->buff); if (issuerAsn->buff != NULL) { BSL_SAL_Free(issuerAsn->buff); } if (revokeBuf->buff != NULL) { BSL_SAL_Free(revokeBuf->buff); } if (crlExt->buff != NULL) { BSL_SAL_Free(crlExt->buff); } return ret; } #define X509_CRL_ELEM_NUMBER 3 int32_t EncodeAsn1Crl(HITLS_X509_Crl *crl) { if (crl->signature.buff == NULL || crl->signature.len == 0 || crl->tbs.tbsRawData == NULL || crl->tbs.tbsRawDataLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_NOT_SIGNED); return HITLS_X509_ERR_CRL_NOT_SIGNED; } BSL_ASN1_Buffer asnArr[X509_CRL_ELEM_NUMBER] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, crl->tbs.tbsRawDataLen, crl->tbs.tbsRawData}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, NULL}, {BSL_ASN1_TAG_BITSTRING, sizeof(BSL_ASN1_BitString), (uint8_t *)&crl->signature}, }; uint32_t valLen = 0; int32_t ret = BSL_ASN1_DecodeTagLen(asnArr[0].tag, &asnArr[0].buff, &asnArr[0].len, &valLen); // 0 is tbs if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_X509_EncodeSignAlgInfo(&crl->signAlgId, &asnArr[1]); // 1 is signAlg if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_TemplateItem crlTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* crl */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 1}, /* tbs */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 1}, /* signAlg */ {BSL_ASN1_TAG_BITSTRING, 0, 1} /* sig */ }; BSL_ASN1_Template templ = {crlTempl, sizeof(crlTempl) / sizeof(crlTempl[0])}; ret = BSL_ASN1_EncodeTemplate(&templ, asnArr, X509_CRL_ELEM_NUMBER, &crl->rawData, &crl->rawDataLen); BSL_SAL_Free(asnArr[1].buff); return ret; } /** * @brief Encode ASN.1 crl * * @param crl [IN] Pointer to the crl structure * @param buff [OUT] Pointer to the buffer. * If NULL, only the ASN.1 crl is encoded. * If non-NULL, the DER encoding content of the crl is stored in buff * @return int32_t Return value, 0 means success, other values mean failure */ int32_t HITLS_X509_EncodeAsn1Crl(HITLS_X509_Crl *crl, BSL_Buffer *buff) { int32_t ret; if ((crl->flag & HITLS_X509_CRL_GEN_FLAG) != 0) { if (crl->state != HITLS_X509_CRL_STATE_SIGN && crl->state != HITLS_X509_CRL_STATE_GEN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_NOT_SIGNED); return HITLS_X509_ERR_CRL_NOT_SIGNED; } if (crl->state == HITLS_X509_CRL_STATE_SIGN) { ret = EncodeAsn1Crl(crl); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } crl->state = HITLS_X509_CRL_STATE_GEN; } } if (crl->rawData == NULL || crl->rawDataLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_NOT_SIGNED); return HITLS_X509_ERR_CRL_NOT_SIGNED; } if (buff == NULL) { return HITLS_PKI_SUCCESS; } buff->data = BSL_SAL_Dump(crl->rawData, crl->rawDataLen); if (buff->data == NULL) { BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return BSL_DUMP_FAIL; } buff->dataLen = crl->rawDataLen; return HITLS_PKI_SUCCESS; } #ifdef HITLS_BSL_PEM int32_t HITLS_X509_EncodePemCrl(HITLS_X509_Crl *crl, BSL_Buffer *buff) { int32_t ret = HITLS_X509_EncodeAsn1Crl(crl, NULL); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_PEM_Symbol symbol = {BSL_PEM_CRL_BEGIN_STR, BSL_PEM_CRL_END_STR}; return BSL_PEM_EncodeAsn1ToPem(crl->rawData, crl->rawDataLen, &symbol, (char **)&buff->data, &buff->dataLen); } #endif // HITLS_BSL_PEM static int32_t X509_CheckCrlRevoke(HITLS_X509_Crl *crl) { BSL_ASN1_List *revokedCerts = crl->tbs.revokedCerts; if (revokedCerts != NULL) { HITLS_X509_CrlEntry *entry = NULL; for (entry = BSL_LIST_GET_FIRST(revokedCerts); entry != NULL; entry = BSL_LIST_GET_NEXT(revokedCerts)) { // Check serial number if (entry->serialNumber.buff == NULL || entry->serialNumber.len == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_ENTRY); return HITLS_X509_ERR_CRL_ENTRY; } // Check revocation time if (!BSL_DateTimeCheck(&entry->time)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_TIME_INVALID); return HITLS_X509_ERR_CRL_TIME_INVALID; } // If entry has extensions and CRL version is v1, that's an error if (entry->extList != NULL && BSL_LIST_COUNT(entry->extList) > 0 && crl->tbs.version == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_INACCURACY_VERSION); return HITLS_X509_ERR_CRL_INACCURACY_VERSION; } } } return HITLS_PKI_SUCCESS; } static int32_t X509_CheckCrlTbs(HITLS_X509_Crl *crl) { int32_t ret; if (crl->tbs.version != 0 && crl->tbs.version != 1) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_INACCURACY_VERSION); return HITLS_X509_ERR_CRL_INACCURACY_VERSION; } if (crl->tbs.crlExt.extList != NULL && BSL_LIST_COUNT(crl->tbs.crlExt.extList) > 0) { if (crl->tbs.version != 1) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_INACCURACY_VERSION); return HITLS_X509_ERR_CRL_INACCURACY_VERSION; } } // Check issuer name if (crl->tbs.issuerName == NULL || BSL_LIST_COUNT(crl->tbs.issuerName) <= 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_ISSUER_EMPTY); return HITLS_X509_ERR_CRL_ISSUER_EMPTY; } // Check validity time if ((crl->tbs.validTime.flag & BSL_TIME_BEFORE_SET) == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_THISUPDATE_UNEXIST); return HITLS_X509_ERR_CRL_THISUPDATE_UNEXIST; } // If nextUpdate is set, check it's after thisUpdate if ((crl->tbs.validTime.flag & BSL_TIME_AFTER_SET) != 0) { ret = BSL_SAL_DateTimeCompare(&crl->tbs.validTime.start, &crl->tbs.validTime.end, NULL); if (ret != BSL_TIME_DATE_BEFORE) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_TIME_INVALID); return HITLS_X509_ERR_CRL_TIME_INVALID; } } ret = X509_CheckCrlRevoke(crl); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t HITLS_X509_CrlGenBuff(int32_t format, HITLS_X509_Crl *crl, BSL_Buffer *buff) { if (crl == NULL || buff == NULL || buff->data != NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } switch (format) { case BSL_FORMAT_ASN1: return HITLS_X509_EncodeAsn1Crl(crl, buff); #ifdef HITLS_BSL_PEM case BSL_FORMAT_PEM: return HITLS_X509_EncodePemCrl(crl, buff); #endif // HITLS_BSL_PEM default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } #ifdef HITLS_BSL_SAL_FILE int32_t HITLS_X509_CrlGenFile(int32_t format, HITLS_X509_Crl *crl, const char *path) { if (path == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } BSL_Buffer buff = {0}; int32_t ret = HITLS_X509_CrlGenBuff(format, crl, &buff); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_SAL_WriteFile(path, buff.data, buff.dataLen); BSL_SAL_Free(buff.data); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif // HITLS_BSL_SAL_FILE #endif // HITLS_PKI_X509_CRL_GEN #ifdef HITLS_PKI_X509_CRL_PARSE int32_t HITLS_X509_ParseAsn1Crl(uint8_t *encode, uint32_t encodeLen, HITLS_X509_Crl *crl) { uint8_t *temp = encode; uint32_t tempLen = encodeLen; crl->rawData = encode; // crl takes over the encode immediately. if ((crl->flag & HITLS_X509_CRL_GEN_FLAG) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } // template parse BSL_ASN1_Buffer asnArr[HITLS_X509_CRL_MAX_IDX] = {0}; BSL_ASN1_Template templ = {g_crlTempl, sizeof(g_crlTempl) / sizeof(g_crlTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, HITLS_X509_CrlTagGetOrCheck, &temp, &tempLen, asnArr, HITLS_X509_CRL_MAX_IDX); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // parse tbs raw data ret = HITLS_X509_ParseTbsRawData(encode, encodeLen, &crl->tbs.tbsRawData, &crl->tbs.tbsRawDataLen); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // parse tbs ret = HITLS_X509_ParseCrlTbs(asnArr, crl); if (ret != HITLS_PKI_SUCCESS) { return ret; } // parse sign alg ret = HITLS_X509_ParseSignAlgInfo(&asnArr[HITLS_X509_CRL_SIGNALG_IDX], &asnArr[HITLS_X509_CRL_SIGNALG_ANY_IDX], &crl->signAlgId); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } // parse signature ret = BSL_ASN1_DecodePrimitiveItem(&asnArr[HITLS_X509_CRL_SIGN_IDX], &crl->signature); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } crl->rawDataLen = encodeLen - tempLen; crl->flag |= HITLS_X509_CRL_PARSE_FLAG; return HITLS_PKI_SUCCESS; ERR: BSL_LIST_DeleteAll(crl->tbs.issuerName, NULL); BSL_LIST_DeleteAll(crl->tbs.revokedCerts, NULL); BSL_LIST_DeleteAll(crl->tbs.crlExt.extList, NULL); return ret; } int32_t HITLS_X509_CrlParseBundleBuff(int32_t format, const BSL_Buffer *encode, HITLS_X509_List **crlList) { if (encode == NULL || encode->data == NULL || encode->dataLen == 0 || crlList == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } X509_ParseFuncCbk crlCbk = { .asn1Parse = (HITLS_X509_Asn1Parse)HITLS_X509_ParseAsn1Crl, .x509New = (HITLS_X509_New)HITLS_X509_CrlNew, .x509Free = (HITLS_X509_Free)HITLS_X509_CrlFree, }; HITLS_X509_List *list = BSL_LIST_New(sizeof(HITLS_X509_Crl)); if (list == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } int32_t ret = HITLS_X509_ParseX509(NULL, NULL, format, encode, false, &crlCbk, list); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(list, (BSL_LIST_PFUNC_FREE)HITLS_X509_CrlFree); BSL_ERR_PUSH_ERROR(ret); return ret; } *crlList = list; return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_CrlParseBuff(int32_t format, const BSL_Buffer *encode, HITLS_X509_Crl **crl) { HITLS_X509_List *list = NULL; if (crl == NULL || *crl != NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } int32_t ret = HITLS_X509_CrlParseBundleBuff(format, encode, &list); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } HITLS_X509_Crl *tmp = BSL_LIST_GET_FIRST(list); int ref; ret = HITLS_X509_CrlCtrl(tmp, HITLS_X509_REF_UP, &ref, sizeof(int)); BSL_LIST_FREE(list, (BSL_LIST_PFUNC_FREE)HITLS_X509_CrlFree); if (ret != HITLS_PKI_SUCCESS) { return ret; } *crl = tmp; return HITLS_PKI_SUCCESS; } #ifdef HITLS_BSL_SAL_FILE int32_t HITLS_X509_CrlParseFile(int32_t format, const char *path, HITLS_X509_Crl **crl) { uint8_t *data = NULL; uint32_t dataLen = 0; int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen); if (ret != BSL_SUCCESS) { return ret; } BSL_Buffer encode = {data, dataLen}; ret = HITLS_X509_CrlParseBuff(format, &encode, crl); BSL_SAL_Free(data); return ret; } int32_t HITLS_X509_CrlParseBundleFile(int32_t format, const char *path, HITLS_X509_List **crlList) { uint8_t *data = NULL; uint32_t dataLen = 0; int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen); if (ret != BSL_SUCCESS) { return ret; } BSL_Buffer encode = {data, dataLen}; ret = HITLS_X509_CrlParseBundleBuff(format, &encode, crlList); BSL_SAL_Free(data); return ret; } #endif // HITLS_BSL_SAL_FILE #endif // HITLS_PKI_X509_CRL_PARSE static int32_t X509_CrlRefUp(HITLS_X509_Crl *crl, int32_t *val, uint32_t valLen) { if (val == NULL || valLen != sizeof(int32_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } return BSL_SAL_AtomicUpReferences(&crl->references, val); } static int32_t X509_CrlGetThisUpdate(HITLS_X509_Crl *crl, BSL_TIME *val, uint32_t valLen) { if (valLen != sizeof(BSL_TIME)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if ((crl->tbs.validTime.flag & BSL_TIME_BEFORE_SET) == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_THISUPDATE_UNEXIST); return HITLS_X509_ERR_CRL_THISUPDATE_UNEXIST; } *val = crl->tbs.validTime.start; return HITLS_PKI_SUCCESS; } static int32_t X509_CrlGetNextUpdate(HITLS_X509_Crl *crl, BSL_TIME *val, uint32_t valLen) { if (valLen != sizeof(BSL_TIME)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if ((crl->tbs.validTime.flag & BSL_TIME_AFTER_SET) == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_NEXTUPDATE_UNEXIST); return HITLS_X509_ERR_CRL_NEXTUPDATE_UNEXIST; } *val = crl->tbs.validTime.end; return HITLS_PKI_SUCCESS; } static int32_t X509_CrlGetVersion(HITLS_X509_Crl *crl, int32_t *val, uint32_t valLen) { if (valLen != sizeof(int32_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } // CRL version is stored as v2(1), v1(0) *val = crl->tbs.version; return HITLS_PKI_SUCCESS; } static int32_t X509_CrlGetRevokeList(HITLS_X509_Crl *crl, BSL_ASN1_List **val, uint32_t valLen) { if (valLen != sizeof(BSL_ASN1_List *)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (crl->tbs.revokedCerts == NULL) { *val = NULL; BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_REVOKELIST_UNEXIST); return HITLS_X509_ERR_CRL_REVOKELIST_UNEXIST; } *val = crl->tbs.revokedCerts; return HITLS_PKI_SUCCESS; } static int32_t X509_CrlGetCtrl(HITLS_X509_Crl *crl, int32_t cmd, void *val, uint32_t valLen) { if (val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } switch (cmd) { case HITLS_X509_GET_VERSION: return X509_CrlGetVersion(crl, val, valLen); case HITLS_X509_GET_BEFORE_TIME: return X509_CrlGetThisUpdate(crl, val, valLen); case HITLS_X509_GET_AFTER_TIME: return X509_CrlGetNextUpdate(crl, val, valLen); case HITLS_X509_GET_ISSUER_DN: return HITLS_X509_GetList(crl->tbs.issuerName, val, valLen); case HITLS_X509_GET_REVOKELIST: return X509_CrlGetRevokeList(crl, val, valLen); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } #ifdef HITLS_PKI_X509_CRL_GEN static int32_t CrlSetTime(void *dest, uint8_t *val, uint32_t valLen) { if (valLen != sizeof(BSL_TIME) || !BSL_DateTimeCheck((BSL_TIME *)val)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } (void)memcpy_s(dest, valLen, val, valLen); return HITLS_PKI_SUCCESS; } static int32_t CrlSetThisUpdateTime(HITLS_X509_ValidTime *time, uint8_t *val, uint32_t valLen) { int32_t ret = CrlSetTime(&(time->start), val, valLen); if (ret != HITLS_PKI_SUCCESS) { return ret; } time->flag |= BSL_TIME_BEFORE_SET; return HITLS_PKI_SUCCESS; } static int32_t CrlSetNextUpdateTime(HITLS_X509_ValidTime *time, uint8_t *val, uint32_t valLen) { int32_t ret = CrlSetTime(&(time->end), val, valLen); if (ret != HITLS_PKI_SUCCESS) { return ret; } time->flag |= BSL_TIME_AFTER_SET; return HITLS_PKI_SUCCESS; } static HITLS_X509_CrlEntry *X509_CrlEntryDup(const HITLS_X509_CrlEntry *src) { HITLS_X509_CrlEntry *dest = (HITLS_X509_CrlEntry *)BSL_SAL_Malloc(sizeof(HITLS_X509_CrlEntry)); if (dest == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } (void)memset_s(dest, sizeof(HITLS_X509_CrlEntry), 0, sizeof(HITLS_X509_CrlEntry)); dest->serialNumber.buff = BSL_SAL_Dump(src->serialNumber.buff, src->serialNumber.len); if (dest->serialNumber.buff == NULL) { BSL_SAL_Free(dest); BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } dest->serialNumber.len = src->serialNumber.len; dest->serialNumber.tag = src->serialNumber.tag; dest->time = src->time; dest->flag = src->flag; dest->flag &= ~HITLS_X509_CRL_PARSE_FLAG; dest->flag |= HITLS_X509_CRL_GEN_FLAG; if (src->extList != NULL) { dest->extList = BSL_LIST_Copy(src->extList, (BSL_LIST_PFUNC_DUP)X509_DupExtEntry, (BSL_LIST_PFUNC_FREE)HITLS_X509_ExtEntryFree); if (dest->extList == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_SET); goto ERR; } } return dest; ERR: BSL_SAL_Free(dest->serialNumber.buff); BSL_SAL_Free(dest); return NULL; } static void X509_CrlEntryFree(HITLS_X509_CrlEntry *entry) { if (entry == NULL) { return; } BSL_SAL_Free(entry->serialNumber.buff); BSL_LIST_FREE(entry->extList, (BSL_LIST_PFUNC_FREE)HITLS_X509_ExtEntryFree); BSL_SAL_Free(entry); } int32_t HITLS_X509_CrlAddRevokedCert(HITLS_X509_Crl *crl, void *val) { HITLS_X509_CrlEntry *entry = (HITLS_X509_CrlEntry *)val; if (entry->serialNumber.buff == NULL || entry->serialNumber.len == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_ENTRY); return HITLS_X509_ERR_CRL_ENTRY; } if (!BSL_DateTimeCheck(&entry->time)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_ENTRY); return HITLS_X509_ERR_CRL_ENTRY; } if (crl->tbs.revokedCerts == NULL) { crl->tbs.revokedCerts = BSL_LIST_New(sizeof(HITLS_X509_CrlEntry)); if (crl->tbs.revokedCerts == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } } HITLS_X509_CrlEntry *newEntry = X509_CrlEntryDup(entry); if (newEntry == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } int32_t ret = BSL_LIST_AddElement(crl->tbs.revokedCerts, newEntry, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { X509_CrlEntryFree(newEntry); BSL_ERR_PUSH_ERROR(ret); return ret; } // If the CRL version is v1 and an extended revocation certificate is added, it needs to be upgraded to v2 if (crl->tbs.version == 0 && entry->extList != NULL) { crl->tbs.version = 1; // v2 } return HITLS_PKI_SUCCESS; } static int32_t X509_CrlSetVersion(HITLS_X509_Crl *crl, int32_t *val, uint32_t valLen) { if (valLen != sizeof(int32_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } int32_t version = *val; if (version != 0 && version != 1) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } crl->tbs.version = version; return HITLS_PKI_SUCCESS; } static int32_t X509_CrlSetCtrl(HITLS_X509_Crl *crl, int32_t cmd, void *val, uint32_t valLen) { if (val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if ((crl->flag & HITLS_X509_CRL_PARSE_FLAG) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SET_AFTER_PARSE); return HITLS_X509_ERR_SET_AFTER_PARSE; } crl->flag |= HITLS_X509_CRL_GEN_FLAG; crl->state = HITLS_X509_CRL_STATE_SET; switch (cmd) { case HITLS_X509_SET_VERSION: return X509_CrlSetVersion(crl, val, valLen); case HITLS_X509_SET_ISSUER_DN: return HITLS_X509_SetNameList(&crl->tbs.issuerName, val, valLen); case HITLS_X509_SET_BEFORE_TIME: return CrlSetThisUpdateTime(&crl->tbs.validTime, val, valLen); case HITLS_X509_SET_AFTER_TIME: return CrlSetNextUpdateTime(&crl->tbs.validTime, val, valLen); case HITLS_X509_CRL_ADD_REVOKED_CERT: return HITLS_X509_CrlAddRevokedCert(crl, val); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } #endif // HITLS_PKI_X509_CRL_GEN int32_t HITLS_X509_CrlCtrl(HITLS_X509_Crl *crl, int32_t cmd, void *val, uint32_t valLen) { if (crl == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (cmd == HITLS_X509_REF_UP) { return X509_CrlRefUp(crl, val, valLen); #ifdef HITLS_CRYPTO_SM2 } else if (cmd == HITLS_X509_SET_VFY_SM2_USER_ID) { if (crl->signAlgId.algId != BSL_CID_SM2DSAWITHSM3) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_SIGNALG_NOT_MATCH); return HITLS_X509_ERR_VFY_SIGNALG_NOT_MATCH; } return HITLS_X509_SetSm2UserId(&crl->signAlgId.sm2UserId, val, valLen); #endif } else if (cmd >= HITLS_X509_GET_ENCODELEN && cmd < HITLS_X509_SET_VERSION) { return X509_CrlGetCtrl(crl, cmd, val, valLen); } else if (cmd < HITLS_X509_EXT_SET_SKI) { #ifdef HITLS_PKI_X509_CRL_GEN return X509_CrlSetCtrl(crl, cmd, val, valLen); #else BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_FUNC_UNSUPPORT); return HITLS_X509_ERR_FUNC_UNSUPPORT; #endif } else if (cmd <= HITLS_X509_EXT_CHECK_SKI) { static int32_t cmdSet[] = {HITLS_X509_EXT_SET_CRLNUMBER, HITLS_X509_EXT_SET_AKI, HITLS_X509_EXT_GET_CRLNUMBER, HITLS_X509_EXT_GET_AKI, HITLS_X509_EXT_GET_KUSAGE}; if (!X509_CheckCmdValid(cmdSet, sizeof(cmdSet) / sizeof(int32_t), cmd)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_UNSUPPORT); return HITLS_X509_ERR_EXT_UNSUPPORT; } return X509_ExtCtrl(&crl->tbs.crlExt, cmd, val, valLen); } else { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } int32_t HITLS_X509_CrlVerify(void *pubkey, const HITLS_X509_Crl *crl) { if (pubkey == NULL || crl == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if ((crl->flag & HITLS_X509_CRL_GEN_FLAG) != 0 && (crl->state != HITLS_X509_CRL_STATE_SIGN) && (crl->state != HITLS_X509_CRL_STATE_GEN)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_NOT_SIGNED); return HITLS_X509_ERR_CRL_NOT_SIGNED; } int32_t ret = HITLS_X509_CheckAlg(pubkey, &(crl->signAlgId)); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = HITLS_X509_CheckSignature(pubkey, crl->tbs.tbsRawData, crl->tbs.tbsRawDataLen, &(crl->signAlgId), &crl->signature); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } HITLS_X509_CrlEntry *HITLS_X509_CrlEntryNew(void) { HITLS_X509_CrlEntry *entry = BSL_SAL_Malloc(sizeof(HITLS_X509_CrlEntry)); if (entry == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } (void)memset_s(entry, sizeof(HITLS_X509_CrlEntry), 0, sizeof(HITLS_X509_CrlEntry)); entry->flag |= HITLS_X509_CRL_GEN_FLAG; return entry; } void HITLS_X509_CrlEntryFree(HITLS_X509_CrlEntry *entry) { if (entry == NULL) { return; } if ((entry->flag & HITLS_X509_CRL_GEN_FLAG) != 0) { BSL_SAL_Free(entry->serialNumber.buff); BSL_LIST_FREE(entry->extList, (BSL_LIST_PFUNC_FREE)HITLS_X509_ExtEntryFree); } else { BSL_LIST_FREE(entry->extList, NULL); } BSL_SAL_Free(entry); } static int32_t X509_CrlGetRevokedRevokeTime(HITLS_X509_CrlEntry *entry, void *val, uint32_t valLen) { if (valLen != sizeof(BSL_TIME)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } *(BSL_TIME *)val = entry->time; return HITLS_PKI_SUCCESS; } #ifdef HITLS_PKI_X509_CRL_GEN static int32_t X509_CrlSetRevokedExt(HITLS_X509_CrlEntry *entry, BslCid cid, BSL_Buffer *buff, uint32_t exceptLen, EncodeExtCb encodeExt) { if (buff->dataLen != exceptLen) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (entry->extList == NULL) { entry->extList = BSL_LIST_New(sizeof(HITLS_X509_ExtEntry)); if (entry->extList == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } } return HITLS_X509_SetExtList(NULL, entry->extList, cid, buff, encodeExt); } static int32_t SetExtInvalidTime(void *param, HITLS_X509_ExtEntry *entry, const void *val) { (void)param; const HITLS_X509_RevokeExtTime *invalidTime = (const HITLS_X509_RevokeExtTime *)val; entry->critical = invalidTime->critical; BSL_ASN1_Buffer asns = {0}; /** * CRL issuers conforming to this profile MUST encode thisUpdate as UTCTime for dates through the year 2049. * CRL issuers conforming to this profile MUST encode thisUpdate as GeneralizedTime for dates in the year * 2050 or later. */ if (invalidTime->time.year >= 2050) { asns.tag = BSL_ASN1_TAG_GENERALIZEDTIME; } else { asns.tag = BSL_ASN1_TAG_UTCTIME; } asns.len = sizeof(BSL_TIME); asns.buff = (uint8_t *)(uintptr_t)&invalidTime->time; BSL_ASN1_TemplateItem templItem = {BSL_ASN1_TAG_CHOICE, 0, 0}; BSL_ASN1_Template templ = {&templItem, 1}; int32_t ret = BSL_ASN1_EncodeTemplate(&templ, &asns, 1, &entry->extnValue.buff, &entry->extnValue.len); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t SetExtReason(void *param, HITLS_X509_ExtEntry *extEntry, void *val) { (void)param; HITLS_X509_RevokeExtReason *reason = (HITLS_X509_RevokeExtReason *)val; if (reason->reason < HITLS_X509_REVOKED_REASON_UNSPECIFIED || reason->reason > HITLS_X509_REVOKED_REASON_AA_COMPROMISE) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } extEntry->critical = reason->critical; uint8_t tmp = (uint8_t)reason->reason; // int32_t -> uint8_t: avoid value errors in bit-endian scenario BSL_ASN1_Buffer asns = {BSL_ASN1_TAG_ENUMERATED, sizeof(uint8_t), (uint8_t *)&tmp}; BSL_ASN1_TemplateItem items = {BSL_ASN1_TAG_ENUMERATED, 0, 0}; BSL_ASN1_Template reasonTempl = {&items, 1}; int32_t ret = BSL_ASN1_EncodeTemplate(&reasonTempl, &asns, 1, &extEntry->extnValue.buff, &extEntry->extnValue.len); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif // HITLS_PKI_X509_CRL_GEN static int32_t SetExtCertificateIssuer(void *param, HITLS_X509_ExtEntry *extEntry, void *val) { (void)param; return HITLS_X509_SetGeneralNames(extEntry, val); } int32_t HITLS_ParseCrlExtInvalidTime(HITLS_X509_ExtEntry *extEntry, void *val) { uint8_t *temp = extEntry->extnValue.buff; uint32_t tempLen = extEntry->extnValue.len; BSL_ASN1_Buffer asn = {0}; BSL_ASN1_TemplateItem item = {BSL_ASN1_TAG_CHOICE, 0, 0}; BSL_ASN1_Template templ = {&item, 1}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, HITLS_X509_CrlEntryChoiceCheck, &temp, &tempLen, &asn, 1); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_ASN1_DecodePrimitiveItem(&asn, val); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t HITLS_ParseCrlExtReason(HITLS_X509_ExtEntry *extEntry, void *val) { uint8_t *temp = extEntry->extnValue.buff; uint32_t tempLen = extEntry->extnValue.len; BSL_ASN1_Buffer asn = {0}; BSL_ASN1_TemplateItem item = {BSL_ASN1_TAG_ENUMERATED, 0, 0}; BSL_ASN1_Template templ = {&item, 1}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, HITLS_X509_CrlEntryChoiceCheck, &temp, &tempLen, &asn, 1); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_ASN1_DecodePrimitiveItem(&asn, val); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t DecodeExtCertIssuer(HITLS_X509_ExtEntry *extEntry, BslList **val) { BslList *list = BSL_LIST_New(sizeof(HITLS_X509_GeneralName)); if (list == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PARSE_AKI); return HITLS_X509_ERR_PARSE_AKI; } int32_t ret = HITLS_X509_ParseGeneralNames(extEntry->extnValue.buff, extEntry->extnValue.len, list); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_Free(list); BSL_ERR_PUSH_ERROR(ret); return ret; } *val = list; return HITLS_PKI_SUCCESS; } #ifdef HITLS_PKI_X509_CRL_GEN static int32_t RevokedSet(HITLS_X509_CrlEntry *revoked, int32_t cmd, void *val, uint32_t valLen) { if ((revoked->flag & HITLS_X509_CRL_PARSE_FLAG) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_EXT_SET_AFTER_PARSE); return HITLS_X509_ERR_EXT_SET_AFTER_PARSE; } BSL_Buffer buff = {val, valLen}; switch (cmd) { case HITLS_X509_CRL_SET_REVOKED_SERIALNUM: return HITLS_X509_SetSerial(&revoked->serialNumber, val, valLen); case HITLS_X509_CRL_SET_REVOKED_REVOKE_TIME: return CrlSetTime(&revoked->time, val, valLen); case HITLS_X509_CRL_SET_REVOKED_INVALID_TIME: return X509_CrlSetRevokedExt(revoked, BSL_CID_CE_INVALIDITYDATE, &buff, sizeof(HITLS_X509_RevokeExtTime), (EncodeExtCb)SetExtInvalidTime); case HITLS_X509_CRL_SET_REVOKED_REASON: return X509_CrlSetRevokedExt(revoked, BSL_CID_CE_CRLREASONS, &buff, sizeof(HITLS_X509_RevokeExtReason), (EncodeExtCb)SetExtReason); case HITLS_X509_CRL_SET_REVOKED_CERTISSUER: return X509_CrlSetRevokedExt(revoked, BSL_CID_CE_CERTIFICATEISSUER, &buff, sizeof(HITLS_X509_RevokeExtCertIssuer), (EncodeExtCb)SetExtCertificateIssuer); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } #endif // HITLS_PKI_X509_CRL_GEN static int32_t RevokedGet(HITLS_X509_CrlEntry *revoked, int32_t cmd, void *val, uint32_t valLen) { BSL_Buffer buff = {val, valLen}; switch (cmd) { case HITLS_X509_CRL_GET_REVOKED_REVOKE_TIME: return X509_CrlGetRevokedRevokeTime(revoked, val, valLen); case HITLS_X509_CRL_GET_REVOKED_SERIALNUM: return HITLS_X509_GetSerial(&revoked->serialNumber, val, valLen); case HITLS_X509_CRL_GET_REVOKED_INVALID_TIME: return HITLS_X509_GetExt(revoked->extList, BSL_CID_CE_INVALIDITYDATE, &buff, sizeof(BSL_TIME), (DecodeExtCb)HITLS_ParseCrlExtInvalidTime); case HITLS_X509_CRL_GET_REVOKED_REASON: return HITLS_X509_GetExt(revoked->extList, BSL_CID_CE_CRLREASONS, &buff, sizeof(int32_t), (DecodeExtCb)HITLS_ParseCrlExtReason); case HITLS_X509_CRL_GET_REVOKED_CERTISSUER: return HITLS_X509_GetExt(revoked->extList, BSL_CID_CE_CERTIFICATEISSUER, &buff, sizeof(BslList *), (DecodeExtCb)DecodeExtCertIssuer); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } int32_t HITLS_X509_CrlEntryCtrl(HITLS_X509_CrlEntry *revoked, int32_t cmd, void *val, uint32_t valLen) { if (revoked == NULL || val == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } #ifdef HITLS_PKI_X509_CRL_GEN if (cmd < HITLS_X509_CRL_GET_REVOKED_SERIALNUM) { return RevokedSet(revoked, cmd, val, valLen); } #endif return RevokedGet(revoked, cmd, val, valLen); } #ifdef HITLS_PKI_X509_CRL_GEN static int32_t CrlSignCb(int32_t mdId, CRYPT_EAL_PkeyCtx *prvKey, HITLS_X509_Asn1AlgId *signAlgId, HITLS_X509_Crl *crl) { BSL_Buffer signBuff = {0}; BSL_ASN1_Buffer tbsCertList = {0}; crl->signAlgId = *signAlgId; crl->tbs.signAlgId = *signAlgId; int32_t ret = HITLS_X509_EncodeCrlTbsRaw(&crl->tbs, &tbsCertList); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = HITLS_X509_SignAsn1Data(prvKey, mdId, &tbsCertList, &signBuff, &crl->signature); BSL_SAL_Free(tbsCertList.buff); if (ret != HITLS_PKI_SUCCESS) { return ret; } crl->tbs.tbsRawData = signBuff.data; crl->tbs.tbsRawDataLen = signBuff.dataLen; crl->state = HITLS_X509_CRL_STATE_SIGN; return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_CrlSign(int32_t mdId, const CRYPT_EAL_PkeyCtx *prvKey, const HITLS_X509_SignAlgParam *algParam, HITLS_X509_Crl *crl) { if (crl == NULL || prvKey == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if ((crl->flag & HITLS_X509_CRL_PARSE_FLAG) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SIGN_AFTER_PARSE); return HITLS_X509_ERR_SIGN_AFTER_PARSE; } if (crl->state == HITLS_X509_CRL_STATE_SIGN || crl->state == HITLS_X509_CRL_STATE_GEN) { return HITLS_PKI_SUCCESS; } int32_t ret = X509_CheckCrlTbs(crl); if (ret != HITLS_PKI_SUCCESS) { return ret; } BSL_SAL_FREE(crl->signature.buff); crl->signature.len = 0; BSL_SAL_FREE(crl->tbs.tbsRawData); crl->tbs.tbsRawDataLen = 0; BSL_SAL_FREE(crl->rawData); crl->rawDataLen = 0; #ifdef HITLS_CRYPTO_SM2 if (crl->signAlgId.algId == BSL_CID_SM2DSAWITHSM3) { BSL_SAL_FREE(crl->signAlgId.sm2UserId.data); crl->signAlgId.sm2UserId.dataLen = 0; } #endif return HITLS_X509_Sign(mdId, prvKey, algParam, crl, (HITLS_X509_SignCb)CrlSignCb); } #endif // HITLS_PKI_X509_CRL_GEN #endif // HITLS_PKI_X509_CRL
2401_83913325/openHiTLS-examples_2461
pki/x509_crl/src/hitls_x509_crl.c
C
unknown
54,553
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_CSR_LOCAL_H #define HITLS_CSR_LOCAL_H #include "hitls_build.h" #ifdef HITLS_PKI_X509_CSR #include <stdint.h> #include "bsl_asn1_internal.h" #include "bsl_obj.h" #include "sal_atomic.h" #include "hitls_x509_local.h" #ifdef __cplusplus extern "C" { #endif typedef struct _HITLS_X509_ReqInfo { uint8_t *reqInfoRawData; uint32_t reqInfoRawDataLen; int32_t version; BSL_ASN1_List *subjectName; /* Entry is HITLS_X509_NameNode */ void *ealPubKey; HITLS_X509_Attrs *attributes; } HITLS_X509_ReqInfo; typedef enum { HITLS_X509_CSR_STATE_NEW = 0, HITLS_X509_CSR_STATE_SET, HITLS_X509_CSR_STATE_SIGN, HITLS_X509_CSR_STATE_GEN, } HITLS_X509_CSR_STATE; /* PKCS #10 */ typedef struct _HITLS_X509_Csr { uint8_t flag; // Used to mark csr parsing or generation, indicating resource release behavior. uint8_t state; uint8_t *rawData; uint32_t rawDataLen; HITLS_X509_ReqInfo reqInfo; HITLS_X509_Asn1AlgId signAlgId; BSL_ASN1_BitString signature; BSL_SAL_RefCount references; CRYPT_EAL_LibCtx *libCtx; // Provider context const char *attrName; // Provider attribute name } HITLS_X509_Csr; #ifdef __cplusplus } #endif #endif // HITLS_PKI_X509_CSR #endif // HITLS_CSR_LOCAL_H
2401_83913325/openHiTLS-examples_2461
pki/x509_csr/include/hitls_csr_local.h
C
unknown
1,823
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_PKI_X509_CSR #include "securec.h" #include "bsl_sal.h" #include "bsl_asn1_internal.h" #include "bsl_obj_internal.h" #include "bsl_err_internal.h" #ifdef HITLS_BSL_PEM #include "bsl_pem_internal.h" #endif // HITLS_BSL_PEM #include "bsl_log_internal.h" #include "hitls_pki_errno.h" #include "crypt_encode_decode_key.h" #include "crypt_errno.h" #ifdef HITLS_BSL_SAL_FILE #include "sal_file.h" #endif #include "crypt_eal_codecs.h" #include "hitls_csr_local.h" #include "hitls_pki_utils.h" #include "hitls_pki_csr.h" #define HITLS_CSR_CTX_SPECIFIC_TAG_ATTRIBUTE 0 #define HITLS_X509_CSR_PARSE_FLAG 0x01 #define HITLS_X509_CSR_GEN_FLAG 0x02 #ifdef HITLS_PKI_X509_CSR_PARSE /** * RFC2986: section 4 * CertificationRequest ::= SEQUENCE { * certificationRequestInfo CertificationRequestInfo, * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }}, * signature BIT STRING * } */ BSL_ASN1_TemplateItem g_csrTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* PKCS10 csr */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, /* req info */ /* 2: version */ {BSL_ASN1_TAG_INTEGER, 0, 2}, /* 2: subject name */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 2}, /* 2: public key info */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 2}, /* 2: attributes */ {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_CSR_CTX_SPECIFIC_TAG_ATTRIBUTE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 2}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, /* signAlg */ {BSL_ASN1_TAG_OBJECT_ID, 0, 2}, {BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL, 2}, {BSL_ASN1_TAG_BITSTRING, 0, 1} /* sig */ }; typedef enum { HITLS_X509_CSR_REQINFO_VERSION_IDX = 0, HITLS_X509_CSR_REQINFO_SUBJECT_NAME_IDX = 1, HITLS_X509_CSR_REQINFO_PUBKEY_INFO_IDX = 2, HITLS_X509_CSR_REQINFO_ATTRS_IDX = 3, HITLS_X509_CSR_SIGNALG_OID_IDX = 4, HITLS_X509_CSR_SIGNALG_ANY_IDX = 5, HITLS_X509_CSR_SIGN_IDX = 6, HITLS_X509_CSR_MAX_IDX = 7, } HITLS_X509_CSR_IDX; #endif // HITLS_PKI_X509_CSR_PARSE HITLS_X509_Csr *HITLS_X509_CsrNew(void) { HITLS_X509_Csr *csr = NULL; BSL_ASN1_List *subjectName = NULL; HITLS_X509_Attrs *attributes = NULL; csr = (HITLS_X509_Csr *)BSL_SAL_Calloc(1, sizeof(HITLS_X509_Csr)); if (csr == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } subjectName = BSL_LIST_New(sizeof(HITLS_X509_NameNode)); if (subjectName == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); goto ERR; } attributes = HITLS_X509_AttrsNew(); if (attributes == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); goto ERR; } BSL_SAL_ReferencesInit(&(csr->references)); csr->reqInfo.subjectName = subjectName; csr->reqInfo.attributes = attributes; csr->state = HITLS_X509_CSR_STATE_NEW; return csr; ERR: BSL_SAL_FREE(subjectName); HITLS_X509_AttrsFree(attributes, NULL); BSL_SAL_FREE(csr); return NULL; } HITLS_X509_Csr *HITLS_X509_ProviderCsrNew(HITLS_PKI_LibCtx *libCtx, const char *attrName) { HITLS_X509_Csr *csr = HITLS_X509_CsrNew(); if (csr == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } csr->libCtx = libCtx; csr->attrName = attrName; return csr; } void HITLS_X509_CsrFree(HITLS_X509_Csr *csr) { if (csr == NULL) { return; } int ret = 0; BSL_SAL_AtomicDownReferences(&(csr->references), &ret); if (ret > 0) { return; } BSL_SAL_ReferencesFree(&(csr->references)); if (csr->flag == HITLS_X509_CSR_GEN_FLAG) { BSL_LIST_FREE(csr->reqInfo.subjectName, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeNameNode); BSL_SAL_FREE(csr->reqInfo.reqInfoRawData); BSL_SAL_FREE(csr->signature.buff); } else { BSL_LIST_FREE(csr->reqInfo.subjectName, NULL); } #ifdef HITLS_CRYPTO_SM2 if (csr->signAlgId.algId == BSL_CID_SM2DSAWITHSM3) { BSL_SAL_FREE(csr->signAlgId.sm2UserId.data); csr->signAlgId.sm2UserId.dataLen = 0; } #endif HITLS_X509_AttrsFree(csr->reqInfo.attributes, NULL); csr->reqInfo.attributes = NULL; BSL_SAL_FREE(csr->rawData); CRYPT_EAL_PkeyFreeCtx(csr->reqInfo.ealPubKey); csr->reqInfo.ealPubKey = NULL; BSL_SAL_FREE(csr); } #ifdef HITLS_PKI_X509_CSR_PARSE int32_t HITLS_X509_CsrTagGetOrCheck(int32_t type, uint32_t idx, void *data, void *expVal) { (void)idx; if (type == BSL_ASN1_TYPE_GET_ANY_TAG) { BSL_ASN1_Buffer *param = (BSL_ASN1_Buffer *)data; BslOidString oidStr = {param->len, (char *)param->buff, 0}; BslCid cid = BSL_OBJ_GetCID(&oidStr); if (cid == BSL_CID_UNKNOWN) { return HITLS_X509_ERR_GET_ANY_TAG; } if (cid == BSL_CID_RSASSAPSS) { /* note: any It can be encoded empty or it can be null */ *(uint8_t *)expVal = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; return BSL_SUCCESS; } else { *(uint8_t *)expVal = BSL_ASN1_TAG_NULL; // is null return BSL_SUCCESS; } } return HITLS_X509_ERR_INVALID_PARAM; } static int32_t ParseCertRequestInfo(BSL_ASN1_Buffer *asnArr, HITLS_X509_Csr *csr) { int32_t ret = BSL_ASN1_DecodePrimitiveItem(&asnArr[HITLS_X509_CSR_REQINFO_VERSION_IDX], &csr->reqInfo.version); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } /* subject name */ ret = HITLS_X509_ParseNameList(&asnArr[HITLS_X509_CSR_REQINFO_SUBJECT_NAME_IDX], csr->reqInfo.subjectName); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } /* public key info */ BSL_Buffer subPubKeyBuff = {asnArr[HITLS_X509_CSR_REQINFO_PUBKEY_INFO_IDX].buff, asnArr[HITLS_X509_CSR_REQINFO_PUBKEY_INFO_IDX].len}; ret = CRYPT_EAL_ProviderDecodeBuffKey(csr->libCtx, csr->attrName, BSL_CID_UNKNOWN, "ASN1", "PUBKEY_SUBKEY_WITHOUT_SEQ", &subPubKeyBuff, NULL, (CRYPT_EAL_PkeyCtx **)&csr->reqInfo.ealPubKey); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } /* attributes */ ret = HITLS_X509_ParseAttrList(&asnArr[HITLS_X509_CSR_REQINFO_ATTRS_IDX], csr->reqInfo.attributes, NULL, NULL); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } return ret; ERR: if (csr->reqInfo.ealPubKey != NULL) { CRYPT_EAL_PkeyFreeCtx(csr->reqInfo.ealPubKey); csr->reqInfo.ealPubKey = NULL; } BSL_LIST_FREE(csr->reqInfo.subjectName, NULL); return ret; } static int32_t X509CsrBuffAsn1Parse(uint8_t *encode, uint32_t encodeLen, HITLS_X509_Csr *csr) { uint8_t *temp = encode; uint32_t tempLen = encodeLen; // template parse BSL_ASN1_Buffer asnArr[HITLS_X509_CSR_MAX_IDX] = {0}; BSL_ASN1_Template templ = {g_csrTempl, sizeof(g_csrTempl) / sizeof(g_csrTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, HITLS_X509_CsrTagGetOrCheck, &temp, &tempLen, asnArr, HITLS_X509_CSR_MAX_IDX); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // parse reqInfo raw data ret = HITLS_X509_ParseTbsRawData(encode, encodeLen, &csr->reqInfo.reqInfoRawData, &csr->reqInfo.reqInfoRawDataLen); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } // parse reqInfo ret = ParseCertRequestInfo(asnArr, csr); if (ret != HITLS_PKI_SUCCESS) { goto ERR; } // parse sign alg ret = HITLS_X509_ParseSignAlgInfo(&asnArr[HITLS_X509_CSR_SIGNALG_OID_IDX], &asnArr[HITLS_X509_CSR_SIGNALG_ANY_IDX], &csr->signAlgId); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } // parse signature ret = BSL_ASN1_DecodePrimitiveItem(&asnArr[HITLS_X509_CSR_SIGN_IDX], &csr->signature); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } csr->rawData = encode; csr->rawDataLen = encodeLen - tempLen; return HITLS_PKI_SUCCESS; ERR: HITLS_X509_AttrsFree(csr->reqInfo.attributes, NULL); csr->reqInfo.attributes = NULL; BSL_LIST_FREE(csr->reqInfo.subjectName, NULL); if (csr->reqInfo.ealPubKey != NULL) { CRYPT_EAL_PkeyFreeCtx(csr->reqInfo.ealPubKey); csr->reqInfo.ealPubKey = NULL; } return ret; } static int32_t X509CsrAsn1Parse(bool isCopy, const BSL_Buffer *encode, HITLS_X509_Csr *csr) { uint8_t *data = encode->data; uint32_t dataLen = encode->dataLen; if ((csr->flag & HITLS_X509_CSR_GEN_FLAG) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } uint8_t *tmp = NULL; if (isCopy) { tmp = (uint8_t *)BSL_SAL_Dump(data, dataLen); if (tmp == NULL) { BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return BSL_DUMP_FAIL; } data = tmp; } int32_t ret = X509CsrBuffAsn1Parse(data, dataLen, csr); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_FREE(tmp); return ret; } csr->flag |= HITLS_X509_CSR_PARSE_FLAG; return HITLS_PKI_SUCCESS; } #ifdef HITLS_BSL_PEM static int32_t X509CsrPemParse(const BSL_Buffer *encode, HITLS_X509_Csr *csr) { uint8_t *tmpBuf = encode->data; uint32_t tmpBufLen = encode->dataLen; BSL_Buffer asn1Buf = {NULL, 0}; BSL_PEM_Symbol symbol = {BSL_PEM_CERT_REQ_BEGIN_STR, BSL_PEM_CERT_REQ_END_STR}; int32_t ret = BSL_PEM_DecodePemToAsn1((char **)&tmpBuf, &tmpBufLen, &symbol, &asn1Buf.data, &asn1Buf.dataLen); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = X509CsrAsn1Parse(false, &asn1Buf, csr); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_FREE(asn1Buf.data); BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif // HITLS_BSL_PEM int32_t HITLS_X509_CsrParseBuff(int32_t format, const BSL_Buffer *encode, HITLS_X509_Csr **csr) { if (encode == NULL || csr == NULL || *csr != NULL || encode->data == NULL || encode->dataLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } int32_t ret; HITLS_X509_Csr *tempCsr = HITLS_X509_CsrNew(); if (tempCsr == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } switch (format) { case BSL_FORMAT_ASN1: ret = X509CsrAsn1Parse(true, encode, tempCsr); break; #ifdef HITLS_BSL_PEM case BSL_FORMAT_PEM: ret = X509CsrPemParse(encode, tempCsr); break; #endif // HITLS_BSL_PEM default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_FORMAT_UNSUPPORT); ret = HITLS_X509_ERR_FORMAT_UNSUPPORT; break; } if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); HITLS_X509_CsrFree(tempCsr); return ret; } *csr = tempCsr; return ret; } #ifdef HITLS_BSL_SAL_FILE int32_t HITLS_X509_CsrParseFile(int32_t format, const char *path, HITLS_X509_Csr **csr) { if (path == NULL || csr == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } uint8_t *data = NULL; uint32_t dataLen = 0; int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Buffer encode = {data, dataLen}; ret = HITLS_X509_CsrParseBuff(format, &encode, csr); BSL_SAL_Free(data); return ret; } #endif // HITLS_BSL_SAL_FILE #endif // HITLS_PKI_X509_CSR_PARSE #ifdef HITLS_PKI_X509_CSR_GEN static int32_t CheckCsrValid(HITLS_X509_Csr *csr) { if (csr->reqInfo.ealPubKey == NULL) { return HITLS_X509_ERR_CSR_INVALID_PUBKEY; } if (csr->reqInfo.subjectName == NULL || BSL_LIST_COUNT(csr->reqInfo.subjectName) <= 0) { return HITLS_X509_ERR_CSR_INVALID_SUBJECT_DN; } return HITLS_PKI_SUCCESS; } static int32_t EncodeCsrReqInfoItem(HITLS_X509_ReqInfo *reqInfo, BSL_ASN1_Buffer *subject, BSL_ASN1_Buffer *publicKey, BSL_ASN1_Buffer *attributes) { /* encode subject name */ int32_t ret = HITLS_X509_EncodeNameList(reqInfo->subjectName, subject); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } /* encode public key */ BSL_Buffer pub = {0}; ret = CRYPT_EAL_EncodePubKeyBuffInternal(reqInfo->ealPubKey, BSL_FORMAT_ASN1, CRYPT_PUBKEY_SUBKEY, false, &pub); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } /* encode attribute */ ret = HITLS_X509_EncodeAttrList( BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_CSR_CTX_SPECIFIC_TAG_ATTRIBUTE, reqInfo->attributes, NULL, attributes); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } publicKey->buff = pub.data; publicKey->len = pub.dataLen; return ret; ERR: BSL_SAL_FREE(subject->buff); BSL_SAL_FREE(pub.data); BSL_SAL_FREE(attributes->buff); return ret; } static BSL_ASN1_TemplateItem g_reqInfoTempl[] = { /* version */ {BSL_ASN1_TAG_INTEGER, 0, 0}, /* subject name */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 0}, /* public key */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 0}, /* attributes */ {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | HITLS_CSR_CTX_SPECIFIC_TAG_ATTRIBUTE, BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 0}, }; #define HITLS_X509_CSR_REQINFO_SIZE 4 static int32_t EncodeCsrReqInfo(HITLS_X509_ReqInfo *reqInfo, BSL_ASN1_Buffer *reqInfoBuff) { BSL_ASN1_Buffer subject = {0, 0, NULL}; BSL_ASN1_Buffer publicKey = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, NULL}; BSL_ASN1_Buffer attributes = {0, 0, NULL}; int ret = EncodeCsrReqInfoItem(reqInfo, &subject, &publicKey, &attributes); if (ret != HITLS_PKI_SUCCESS) { return ret; } uint8_t version = (uint8_t)reqInfo->version; BSL_ASN1_Template templ = { g_reqInfoTempl, sizeof(g_reqInfoTempl) / sizeof(g_reqInfoTempl[0]) }; BSL_ASN1_Buffer reqInfoAsn[HITLS_X509_CSR_REQINFO_SIZE] = { {BSL_ASN1_TAG_INTEGER, 1, &version}, subject, publicKey, attributes }; ret = BSL_ASN1_EncodeTemplate(&templ, reqInfoAsn, HITLS_X509_CSR_REQINFO_SIZE, &reqInfoBuff->buff, &reqInfoBuff->len); BSL_SAL_FREE(subject.buff); BSL_SAL_FREE(publicKey.buff); BSL_SAL_FREE(attributes.buff); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } BSL_ASN1_TemplateItem g_briefCsrTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* pkcs10 csr */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, /* reqInfo */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, /* signAlg */ {BSL_ASN1_TAG_BITSTRING, 0, 1} /* sig */ }; #define HITLS_X509_CSR_BRIEF_SIZE 3 static int32_t X509EncodeAsn1CsrCore(HITLS_X509_Csr *csr) { if (csr->signature.buff == NULL || csr->signature.len == 0 || csr->reqInfo.reqInfoRawData == NULL || csr->reqInfo.reqInfoRawDataLen == 0 || csr->signAlgId.algId == BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CSR_NOT_SIGNED); return HITLS_X509_ERR_CSR_NOT_SIGNED; } BSL_ASN1_Buffer asnArr[HITLS_X509_CSR_BRIEF_SIZE] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, csr->reqInfo.reqInfoRawDataLen, csr->reqInfo.reqInfoRawData}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, NULL}, {BSL_ASN1_TAG_BITSTRING, sizeof(BSL_ASN1_BitString), (uint8_t *)&csr->signature} }; uint32_t valLen = 0; int32_t ret = BSL_ASN1_DecodeTagLen(asnArr[0].tag, &asnArr[0].buff, &asnArr[0].len, &valLen); // 0 is reqInfo if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_X509_EncodeSignAlgInfo(&csr->signAlgId, &asnArr[1]); // 1 is signAlg if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_Template csrTempl = { g_briefCsrTempl, sizeof(g_briefCsrTempl) / sizeof(g_briefCsrTempl[0]) }; ret = BSL_ASN1_EncodeTemplate(&csrTempl, asnArr, HITLS_X509_CSR_BRIEF_SIZE, &csr->rawData, &csr->rawDataLen); BSL_SAL_FREE(asnArr[1].buff); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } /** * @brief Encode ASN.1 csr * * @param csr [IN] Pointer to the csr structure * @param buff [OUT] Pointer to the buffer. * If NULL, only the ASN.1 csr is encoded. * If non-NULL, the DER encoding content of the csr is stored in buff * @return int32_t Return value, 0 means success, other values mean failure */ static int32_t X509EncodeAsn1Csr(HITLS_X509_Csr *csr, BSL_Buffer *buff) { int32_t ret; if ((csr->flag & HITLS_X509_CSR_GEN_FLAG) != 0) { if (csr->state != HITLS_X509_CSR_STATE_SIGN && csr->state != HITLS_X509_CSR_STATE_GEN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CSR_NOT_SIGNED); return HITLS_X509_ERR_CSR_NOT_SIGNED; } if (csr->state == HITLS_X509_CSR_STATE_SIGN) { ret = X509EncodeAsn1CsrCore(csr); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } csr->state = HITLS_X509_CSR_STATE_GEN; } } if (csr->rawData == NULL || csr->rawDataLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CSR_NOT_SIGNED); return HITLS_X509_ERR_CSR_NOT_SIGNED; } if (buff == NULL) { return HITLS_PKI_SUCCESS; } buff->data = BSL_SAL_Dump(csr->rawData, csr->rawDataLen); if (buff->data == NULL) { BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return BSL_DUMP_FAIL; } buff->dataLen = csr->rawDataLen; return HITLS_PKI_SUCCESS; } #ifdef HITLS_BSL_PEM static int32_t X509EncodePemCsr(HITLS_X509_Csr *csr, BSL_Buffer *buff) { BSL_Buffer asn1 = {0}; int32_t ret = X509EncodeAsn1Csr(csr, &asn1); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Buffer base64 = {0}; BSL_PEM_Symbol symbol = {BSL_PEM_CERT_REQ_BEGIN_STR, BSL_PEM_CERT_REQ_END_STR}; ret = BSL_PEM_EncodeAsn1ToPem(asn1.data, asn1.dataLen, &symbol, (char **)&base64.data, &base64.dataLen); BSL_SAL_FREE(asn1.data); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } buff->data = base64.data; buff->dataLen = base64.dataLen; return HITLS_PKI_SUCCESS; } #endif // HITLS_BSL_PEM int32_t HITLS_X509_CsrGenBuff(int32_t format, HITLS_X509_Csr *csr, BSL_Buffer *buff) { if (csr == NULL || buff == NULL || buff->data != NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } switch (format) { case BSL_FORMAT_ASN1: return X509EncodeAsn1Csr(csr, buff); #ifdef HITLS_BSL_PEM case BSL_FORMAT_PEM: return X509EncodePemCsr(csr, buff); #endif // HITLS_BSL_PEM default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_FORMAT_UNSUPPORT); return HITLS_X509_ERR_FORMAT_UNSUPPORT; } } #ifdef HITLS_BSL_SAL_FILE int32_t HITLS_X509_CsrGenFile(int32_t format, HITLS_X509_Csr *csr, const char *path) { if (path == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } BSL_Buffer encode = { NULL, 0}; int32_t ret = HITLS_X509_CsrGenBuff(format, csr, &encode); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_SAL_WriteFile(path, encode.data, encode.dataLen); BSL_SAL_Free(encode.data); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif // HITLS_BSL_SAL_FILE #endif // HITLS_PKI_X509_CSR_GEN static int32_t X509GetAttr(HITLS_X509_Attrs *attrs, HITLS_X509_Attrs **val, uint32_t valLen) { if (val == NULL || valLen != sizeof(HITLS_X509_Attrs *)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } *val = attrs; return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_CsrCtrl(HITLS_X509_Csr *csr, int32_t cmd, void *val, uint32_t valLen) { if (csr == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (((csr->flag & HITLS_X509_CSR_PARSE_FLAG) != 0) && cmd >= HITLS_X509_SET_VERSION && cmd < HITLS_X509_EXT_SET_SKI) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SET_AFTER_PARSE); return HITLS_X509_ERR_SET_AFTER_PARSE; } switch (cmd) { case HITLS_X509_REF_UP: return HITLS_X509_RefUp(&csr->references, val, valLen); #ifdef HITLS_PKI_X509_CSR_GEN case HITLS_X509_SET_PUBKEY: csr->flag |= HITLS_X509_CSR_GEN_FLAG; csr->state = HITLS_X509_CSR_STATE_SET; return HITLS_X509_SetPkey(&csr->reqInfo.ealPubKey, val); case HITLS_X509_ADD_SUBJECT_NAME: csr->flag |= HITLS_X509_CSR_GEN_FLAG; csr->state = HITLS_X509_CSR_STATE_SET; return HITLS_X509_AddDnName(csr->reqInfo.subjectName, (HITLS_X509_DN *)val, valLen); #ifdef HITLS_CRYPTO_SM2 case HITLS_X509_SET_VFY_SM2_USER_ID: if (csr->signAlgId.algId != BSL_CID_SM2DSA && csr->signAlgId.algId != BSL_CID_SM2DSAWITHSM3) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_SIGNALG_NOT_MATCH); return HITLS_X509_ERR_VFY_SIGNALG_NOT_MATCH; } return HITLS_X509_SetSm2UserId(&csr->signAlgId.sm2UserId, val, valLen); #endif #endif case HITLS_X509_GET_ENCODELEN: return HITLS_X509_GetEncodeLen(csr->rawDataLen, val, valLen); case HITLS_X509_GET_ENCODE: return HITLS_X509_GetEncodeData(csr->rawData, val); case HITLS_X509_GET_PUBKEY: return HITLS_X509_GetPubKey(csr->reqInfo.ealPubKey, val); case HITLS_X509_GET_SIGNALG: return HITLS_X509_GetSignAlg(csr->signAlgId.algId, (int32_t *)val, valLen); case HITLS_X509_GET_SUBJECT_DN: return HITLS_X509_GetList(csr->reqInfo.subjectName, val, valLen); case HITLS_X509_CSR_GET_ATTRIBUTES: return X509GetAttr(csr->reqInfo.attributes, val, valLen); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } int32_t HITLS_X509_CsrVerify(HITLS_X509_Csr *csr) { if (csr == NULL || csr->reqInfo.ealPubKey == NULL || csr->reqInfo.reqInfoRawData == NULL || csr->signature.buff == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } int32_t ret = HITLS_X509_CheckSignature((const CRYPT_EAL_PkeyCtx *)csr->reqInfo.ealPubKey, csr->reqInfo.reqInfoRawData, csr->reqInfo.reqInfoRawDataLen, &csr->signAlgId, &csr->signature); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #ifdef HITLS_PKI_X509_CSR_GEN int32_t CsrSignCb(int32_t mdId, CRYPT_EAL_PkeyCtx *prvKey, HITLS_X509_Asn1AlgId *signAlgId, HITLS_X509_Csr *csr) { BSL_ASN1_Buffer reqInfoAsn1 = {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, NULL}; BSL_Buffer signBuff = {NULL, 0}; csr->signAlgId = *signAlgId; int32_t ret = CRYPT_EAL_PkeyPairCheck((CRYPT_EAL_PkeyCtx *)csr->reqInfo.ealPubKey, prvKey); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = EncodeCsrReqInfo(&csr->reqInfo, &reqInfoAsn1); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_X509_SignAsn1Data(prvKey, mdId, &reqInfoAsn1, &signBuff, &csr->signature); BSL_SAL_Free(reqInfoAsn1.buff); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } csr->reqInfo.reqInfoRawData = signBuff.data; csr->reqInfo.reqInfoRawDataLen = signBuff.dataLen; csr->state = HITLS_X509_CSR_STATE_SIGN; return ret; } int32_t HITLS_X509_CsrSign(int32_t mdId, const CRYPT_EAL_PkeyCtx *prvKey, const HITLS_X509_SignAlgParam *algParam, HITLS_X509_Csr *csr) { if (csr == NULL || prvKey == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if ((csr->flag & HITLS_X509_CSR_PARSE_FLAG) != 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_SIGN_AFTER_PARSE); return HITLS_X509_ERR_SIGN_AFTER_PARSE; } if (csr->state == HITLS_X509_CSR_STATE_SIGN || csr->state == HITLS_X509_CSR_STATE_GEN) { return HITLS_PKI_SUCCESS; } int32_t ret = CheckCsrValid(csr); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_SAL_FREE(csr->signature.buff); csr->signature.len = 0; BSL_SAL_FREE(csr->reqInfo.reqInfoRawData); csr->reqInfo.reqInfoRawDataLen = 0; BSL_SAL_FREE(csr->rawData); csr->rawDataLen = 0; #ifdef HITLS_CRYPTO_SM2 if (csr->signAlgId.algId == BSL_CID_SM2DSAWITHSM3) { BSL_SAL_FREE(csr->signAlgId.sm2UserId.data); csr->signAlgId.sm2UserId.dataLen = 0; } #endif return HITLS_X509_Sign(mdId, prvKey, algParam, csr, (HITLS_X509_SignCb)CsrSignCb); } #endif // HITLS_PKI_X509_CSR_GEN #endif // HITLS_PKI_X509_CSR
2401_83913325/openHiTLS-examples_2461
pki/x509_csr/src/hitls_x509_csr.c
C
unknown
26,575
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_X509_VERIFY_H #define HITLS_X509_VERIFY_H #include "hitls_build.h" #ifdef HITLS_PKI_X509_VFY #include <stdint.h> #include "bsl_asn1_internal.h" #include "bsl_list.h" #include "hitls_pki_x509.h" #include "sal_atomic.h" #ifdef __cplusplus extern "C" { #endif typedef enum { HITLS_X509_VFY_FLAG_SECBITS = 0x100000000, HITLS_X509_VFY_FLAG_TIME = 0x200000000, } HITLS_X509_IN_VerifyFlag; typedef struct _HITLS_X509_VerifyParam { int32_t maxDepth; int64_t time; uint32_t securityBits; uint64_t flags; #ifdef HITLS_CRYPTO_SM2 BSL_Buffer sm2UserId; #endif } HITLS_X509_VerifyParam; struct _HITLS_X509_StoreCtx { HITLS_X509_List *store; HITLS_X509_List *crl; BSL_SAL_RefCount references; HITLS_X509_VerifyParam verifyParam; BslList *caPaths; // List of CA directory paths for on-demand loading (char*) CRYPT_EAL_LibCtx *libCtx; // Provider context const char *attrName; // Provider attribute name }; int32_t HITLS_X509_VerifyParamAndExt(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *chain); /* * Verify the CRL, which is the default full certificate chain validation. * You can configure not to verify or only verify the terminal certificate */ int32_t HITLS_X509_VerifyCrl(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *chain); int32_t HITLS_X509_GetIssuerFromStore(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_Cert *cert, HITLS_X509_Cert **issuer); #ifdef __cplusplus } #endif #endif // HITLS_PKI_X509_VFY #endif // HITLS_X509_VERIFY_H
2401_83913325/openHiTLS-examples_2461
pki/x509_verify/include/hitls_x509_verify.h
C
unknown
2,094
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_PKI_X509_VFY #include <string.h> #include "securec.h" #include "hitls_pki_x509.h" #include "hitls_pki_cert.h" #include "bsl_types.h" #include "sal_atomic.h" #include "bsl_err_internal.h" #include "hitls_crl_local.h" #include "hitls_cert_local.h" #include "hitls_x509_local.h" #include "bsl_obj_internal.h" #include "hitls_pki_errno.h" #include "bsl_list.h" #include "bsl_list_internal.h" #include "hitls_x509_verify.h" #include "crypt_eal_md.h" #include "crypt_algid.h" #include "crypt_errno.h" #define CRYPT_SHA1_DIGESTSIZE 20 #define MAX_PATH_LEN 4096 typedef int32_t (*HITLS_X509_TrvListCallBack)(void *ctx, void *node); typedef int32_t (*HITLS_X509_TrvListWithParentCallBack)(void *ctx, void *node, void *parent); // lists can be cert, ext, and so on. static int32_t HITLS_X509_TrvList(BslList *list, HITLS_X509_TrvListCallBack callBack, void *ctx) { int32_t ret = HITLS_PKI_SUCCESS; void *node = BSL_LIST_GET_FIRST(list); while (node != NULL) { ret = callBack(ctx, node); if (ret != BSL_SUCCESS) { return ret; } node = BSL_LIST_GET_NEXT(list); } return ret; } // lists can be cert, ext, and so on. static int32_t HITLS_X509_TrvListWithParent(BslList *list, HITLS_X509_TrvListWithParentCallBack callBack, void *ctx) { int32_t ret = HITLS_PKI_SUCCESS; void *node = BSL_LIST_GET_FIRST(list); void *parentNode = BSL_LIST_GET_NEXT(list); while (node != NULL && parentNode != NULL) { ret = callBack(ctx, node, parentNode); if (ret != BSL_SUCCESS) { return ret; } node = parentNode; parentNode = BSL_LIST_GET_NEXT(list); } return ret; } #define HITLS_X509_MAX_DEPTH 20 void HITLS_X509_StoreCtxFree(HITLS_X509_StoreCtx *storeCtx) { if (storeCtx == NULL) { return; } int ret; (void)BSL_SAL_AtomicDownReferences(&storeCtx->references, &ret); if (ret > 0) { return; } #ifdef HITLS_CRYPTO_SM2 BSL_SAL_FREE(storeCtx->verifyParam.sm2UserId.data); #endif BSL_LIST_FREE(storeCtx->store, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); BSL_LIST_FREE(storeCtx->crl, (BSL_LIST_PFUNC_FREE)HITLS_X509_CrlFree); // Free CA paths list if (storeCtx->caPaths != NULL) { BSL_LIST_FREE(storeCtx->caPaths, (BSL_LIST_PFUNC_FREE)BSL_SAL_Free); } BSL_SAL_ReferencesFree(&storeCtx->references); BSL_SAL_Free(storeCtx); } static int32_t X509_CrlCmp(HITLS_X509_Crl *crlOri, HITLS_X509_Crl *crl) { if (crlOri == crl) { return 0; } if (HITLS_X509_CmpNameNode(crlOri->tbs.issuerName, crl->tbs.issuerName) != 0) { return 1; } if (crlOri->tbs.tbsRawDataLen != crl->tbs.tbsRawDataLen) { return 1; } return memcmp(crlOri->tbs.tbsRawData, crl->tbs.tbsRawData, crl->tbs.tbsRawDataLen); } static int32_t X509_CertCmp(HITLS_X509_Cert *certOri, HITLS_X509_Cert *cert) { if (certOri == cert) { return 0; } if (HITLS_X509_CmpNameNode(certOri->tbs.subjectName, cert->tbs.subjectName) != 0) { return 1; } if (certOri->tbs.tbsRawDataLen != cert->tbs.tbsRawDataLen) { return 1; } return memcmp(certOri->tbs.tbsRawData, cert->tbs.tbsRawData, cert->tbs.tbsRawDataLen); } HITLS_X509_StoreCtx *HITLS_X509_StoreCtxNew(void) { HITLS_X509_StoreCtx *ctx = (HITLS_X509_StoreCtx *)BSL_SAL_Malloc(sizeof(HITLS_X509_StoreCtx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } (void)memset_s(ctx, sizeof(HITLS_X509_StoreCtx), 0, sizeof(HITLS_X509_StoreCtx)); ctx->store = BSL_LIST_New(sizeof(HITLS_X509_Cert *)); if (ctx->store == NULL) { BSL_SAL_Free(ctx); BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } ctx->crl = BSL_LIST_New(sizeof(HITLS_X509_Crl *)); if (ctx->crl == NULL) { BSL_SAL_FREE(ctx->store); BSL_SAL_Free(ctx); BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } // Initialize CA paths list ctx->caPaths = BSL_LIST_New(sizeof(char *)); if (ctx->caPaths == NULL) { BSL_SAL_FREE(ctx->store); BSL_SAL_FREE(ctx->crl); BSL_SAL_Free(ctx); BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } ctx->verifyParam.maxDepth = HITLS_X509_MAX_DEPTH; ctx->verifyParam.securityBits = 128; // 128: The default number of secure bits. BSL_SAL_ReferencesInit(&(ctx->references)); return ctx; } static int32_t X509_SetMaxDepth(HITLS_X509_StoreCtx *storeCtx, int32_t *val, uint32_t valLen) { if (valLen != sizeof(int32_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } int32_t depth = *val; if (depth > HITLS_X509_MAX_DEPTH) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } storeCtx->verifyParam.maxDepth = depth; return HITLS_PKI_SUCCESS; } static int32_t X509_GetMaxDepth(HITLS_X509_StoreCtx *storeCtx, int32_t *val, uint32_t valLen) { if (valLen != sizeof(int32_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } *val = storeCtx->verifyParam.maxDepth; return HITLS_PKI_SUCCESS; } static int32_t X509_SetParamFlag(HITLS_X509_StoreCtx *storeCtx, uint64_t *val, uint32_t valLen) { if (valLen != sizeof(uint64_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } storeCtx->verifyParam.flags |= *val; return HITLS_PKI_SUCCESS; } static int32_t X509_GetParamFlag(HITLS_X509_StoreCtx *storeCtx, uint64_t *val, uint32_t valLen) { if (valLen != sizeof(uint64_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } *val = storeCtx->verifyParam.flags; return HITLS_PKI_SUCCESS; } static int32_t X509_SetVerifyTime(HITLS_X509_StoreCtx *storeCtx, int64_t *val, uint32_t valLen) { if (valLen != sizeof(int64_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } storeCtx->verifyParam.time = *val; storeCtx->verifyParam.flags |= HITLS_X509_VFY_FLAG_TIME; return HITLS_PKI_SUCCESS; } static int32_t X509_SetVerifySecurityBits(HITLS_X509_StoreCtx *storeCtx, uint32_t *val, uint32_t valLen) { if (valLen != sizeof(uint32_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } storeCtx->verifyParam.securityBits = *val; storeCtx->verifyParam.flags |= HITLS_X509_VFY_FLAG_SECBITS; return HITLS_PKI_SUCCESS; } static int32_t X509_ClearParamFlag(HITLS_X509_StoreCtx *storeCtx, uint64_t *val, uint32_t valLen) { if (valLen != sizeof(uint64_t)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } storeCtx->verifyParam.flags &= ~(*val); return HITLS_PKI_SUCCESS; } static int32_t X509_CheckCert(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_Cert *cert) { if (!HITLS_X509_CertIsCA(cert)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_NOT_CA); return HITLS_X509_ERR_CERT_NOT_CA; } HITLS_X509_List *certStore = storeCtx->store; HITLS_X509_Cert *tmp = BSL_LIST_SearchEx(certStore, cert, (BSL_LIST_PFUNC_CMP)X509_CertCmp); if (tmp != NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_EXIST); return HITLS_X509_ERR_CERT_EXIST; } return HITLS_PKI_SUCCESS; } static int32_t X509_SetCA(HITLS_X509_StoreCtx *storeCtx, void *val, bool isCopy) { int32_t ret = X509_CheckCert(storeCtx, val); if (ret != HITLS_PKI_SUCCESS) { return ret; } if (isCopy) { int ref; ret = HITLS_X509_CertCtrl(val, HITLS_X509_REF_UP, &ref, sizeof(int)); if (ret != HITLS_PKI_SUCCESS) { return ret; } } ret = BSL_LIST_AddElement(storeCtx->store, val, BSL_LIST_POS_BEFORE); if (ret != HITLS_PKI_SUCCESS) { if (isCopy) { HITLS_X509_CertFree(val); } BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t X509_CheckCRL(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_Crl *crl) { HITLS_X509_List *crlStore = storeCtx->crl; HITLS_X509_Crl *tmp = BSL_LIST_SearchEx(crlStore, crl, (BSL_LIST_PFUNC_CMP)X509_CrlCmp); if (tmp != NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CRL_EXIST); return HITLS_X509_ERR_CRL_EXIST; } return HITLS_PKI_SUCCESS; } static int32_t X509_SetCRL(HITLS_X509_StoreCtx *storeCtx, void *val) { int32_t ret = X509_CheckCRL(storeCtx, val); if (ret != HITLS_PKI_SUCCESS) { return ret; } int ref; ret = HITLS_X509_CrlCtrl(val, HITLS_X509_REF_UP, &ref, sizeof(int)); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = BSL_LIST_AddElement(storeCtx->crl, val, BSL_LIST_POS_BEFORE); if (ret != HITLS_PKI_SUCCESS) { HITLS_X509_CrlFree(val); BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t X509_AddCAPath(HITLS_X509_StoreCtx *storeCtx, const void *val, uint32_t valLen) { if (val == NULL || valLen == 0 || valLen > MAX_PATH_LEN) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } const char *caPath = (const char *)val; char *existPath = BSL_LIST_GET_FIRST(storeCtx->caPaths); while (existPath != NULL) { if (memcmp(existPath, caPath, valLen) == 0 && strlen(existPath) == valLen) { return HITLS_PKI_SUCCESS; } existPath = BSL_LIST_GET_NEXT(storeCtx->caPaths); } // Allocate and copy new path char *pathCopy = BSL_SAL_Calloc(valLen + 1, sizeof(char)); if (pathCopy == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } if (memcpy_s(pathCopy, valLen, caPath, valLen) != EOK) { BSL_SAL_Free(pathCopy); BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } // Add to paths list int32_t ret = BSL_LIST_AddElement(storeCtx->caPaths, pathCopy, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { BSL_SAL_Free(pathCopy); BSL_ERR_PUSH_ERROR(ret); return ret; } return HITLS_PKI_SUCCESS; } static int32_t X509_ClearCRL(HITLS_X509_StoreCtx *storeCtx) { if (storeCtx->crl == NULL) { return HITLS_PKI_SUCCESS; } BSL_LIST_DeleteAll(storeCtx->crl, (BSL_LIST_PFUNC_FREE)HITLS_X509_CrlFree); return HITLS_PKI_SUCCESS; } static int32_t X509_RefUp(HITLS_X509_StoreCtx *storeCtx, void *val, uint32_t valLen) { if (valLen != sizeof(int)) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } return BSL_SAL_AtomicUpReferences(&storeCtx->references, val); } int32_t HITLS_X509_StoreCtxCtrl(HITLS_X509_StoreCtx *storeCtx, int32_t cmd, void *val, uint32_t valLen) { if (storeCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } // Allow val to be NULL only for specific commands like CLEAR_CRL if (val == NULL && cmd != HITLS_X509_STORECTX_CLEAR_CRL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } switch (cmd) { case HITLS_X509_STORECTX_SET_PARAM_DEPTH: return X509_SetMaxDepth(storeCtx, val, valLen); case HITLS_X509_STORECTX_SET_PARAM_FLAGS: return X509_SetParamFlag(storeCtx, val, valLen); case HITLS_X509_STORECTX_SET_TIME: return X509_SetVerifyTime(storeCtx, val, valLen); case HITLS_X509_STORECTX_SET_SECBITS: return X509_SetVerifySecurityBits(storeCtx, val, valLen); case HITLS_X509_STORECTX_CLR_PARAM_FLAGS: return X509_ClearParamFlag(storeCtx, val, valLen); case HITLS_X509_STORECTX_DEEP_COPY_SET_CA: return X509_SetCA(storeCtx, val, true); case HITLS_X509_STORECTX_SHALLOW_COPY_SET_CA: return X509_SetCA(storeCtx, val, false); case HITLS_X509_STORECTX_SET_CRL: return X509_SetCRL(storeCtx, val); case HITLS_X509_STORECTX_CLEAR_CRL: return X509_ClearCRL(storeCtx); case HITLS_X509_STORECTX_REF_UP: return X509_RefUp(storeCtx, val, valLen); #ifdef HITLS_CRYPTO_SM2 case HITLS_X509_STORECTX_SET_VFY_SM2_USERID: return HITLS_X509_SetSm2UserId(&storeCtx->verifyParam.sm2UserId, val, valLen); #endif case HITLS_X509_STORECTX_GET_PARAM_DEPTH: return X509_GetMaxDepth(storeCtx, val, valLen); case HITLS_X509_STORECTX_GET_PARAM_FLAGS: return X509_GetParamFlag(storeCtx, val, valLen); case HITLS_X509_STORECTX_ADD_CA_PATH: return X509_AddCAPath(storeCtx, val, valLen); default: BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } } int32_t HITLS_X509_CheckTime(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_ValidTime *validTime) { int64_t start = 0; int64_t end = 0; if ((storeCtx->verifyParam.flags & HITLS_X509_VFY_FLAG_TIME) == 0) { return HITLS_PKI_SUCCESS; } int32_t ret = BSL_SAL_DateToUtcTimeConvert(&validTime->start, &start); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (start > storeCtx->verifyParam.time) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_TIME_FUTURE); return HITLS_X509_ERR_TIME_FUTURE; } if ((validTime->flag & BSL_TIME_AFTER_SET) == 0) { return HITLS_PKI_SUCCESS; } ret = BSL_SAL_DateToUtcTimeConvert(&validTime->end, &end); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (end < storeCtx->verifyParam.time) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_TIME_EXPIRED); return HITLS_X509_ERR_TIME_EXPIRED; } return HITLS_PKI_SUCCESS; } static int32_t X509_AddCertToChain(HITLS_X509_List *chain, HITLS_X509_Cert *cert) { int ref; int32_t ret = HITLS_X509_CertCtrl(cert, HITLS_X509_REF_UP, &ref, sizeof(int)); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = BSL_LIST_AddElement(chain, cert, BSL_LIST_POS_END); if (ret != HITLS_PKI_SUCCESS) { HITLS_X509_CertFree(cert); BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t X509_GetIssueFromChain(HITLS_X509_List *certChain, HITLS_X509_Cert *cert, HITLS_X509_Cert **issue) { int32_t ret; for (HITLS_X509_Cert *tmp = BSL_LIST_GET_FIRST(certChain); tmp != NULL; tmp = BSL_LIST_GET_NEXT(certChain)) { bool res = false; ret = HITLS_X509_CheckIssued(tmp, cert, &res); if (ret != HITLS_PKI_SUCCESS) { return ret; } if (!res) { continue; } *issue = tmp; return HITLS_PKI_SUCCESS; } BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND); return HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND; } static int32_t CheckAndAddIssuerCert(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_Cert *candidateCert, HITLS_X509_Cert *cert, HITLS_X509_Cert **issue, bool *issueInTrust) { bool res = false; int32_t ret = HITLS_X509_CheckIssued(candidateCert, cert, &res); if (ret == HITLS_PKI_SUCCESS && res) { *issue = candidateCert; *issueInTrust = true; ret = X509_SetCA(storeCtx, candidateCert, false); if (ret == HITLS_PKI_SUCCESS) { return HITLS_PKI_SUCCESS; } } return HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND; } static int32_t HITLS_X509_GetCertBySubjectDer(HITLS_X509_StoreCtx *storeCtx, const BSL_ASN1_Buffer *subjectDerData, HITLS_X509_Cert *cert, HITLS_X509_Cert **issue, bool *issueInTrust) { // Only try on-demand loading from CA paths using hash-based lookup if (storeCtx->caPaths == NULL || BSL_LIST_COUNT(storeCtx->caPaths) <= 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND); return HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND; } // Calculate hash from canon-encoded subject DN uint32_t hash = 0; uint8_t digest[CRYPT_SHA1_DIGESTSIZE]; uint32_t digestLen = CRYPT_SHA1_DIGESTSIZE; int32_t ret = HITLS_PKI_SUCCESS; CRYPT_EAL_MdCTX *mdCtx = CRYPT_EAL_ProviderMdNewCtx(storeCtx->libCtx, CRYPT_MD_SHA1, storeCtx->attrName); if (mdCtx != NULL) { if (CRYPT_EAL_MdInit(mdCtx) == CRYPT_SUCCESS && CRYPT_EAL_MdUpdate(mdCtx, subjectDerData->buff, subjectDerData->len) == CRYPT_SUCCESS) { if (CRYPT_EAL_MdFinal(mdCtx, digest, &digestLen) == CRYPT_SUCCESS && digestLen >= 4) { hash = (uint32_t)digest[0] | ((uint32_t)digest[1] << 8) | ((uint32_t)digest[2] << 16) | ((uint32_t)digest[3] << 24); } } CRYPT_EAL_MdFreeCtx(mdCtx); } if (hash == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND); return HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND; } // Try to load certificate using hash-based file lookup from CA paths char *caPath = BSL_LIST_GET_FIRST(storeCtx->caPaths); while (caPath != NULL) { int32_t seq = 0; while (1) { char filename[MAX_PATH_LEN] = {0}; if (snprintf_s(filename, sizeof(filename), sizeof(filename) - 1, "%s/%08x.%d", caPath, hash, seq) < 0) { break; } HITLS_X509_Cert *candidateCert = NULL; ret = HITLS_X509_CertParseFile(BSL_FORMAT_PEM, filename, &candidateCert); if (ret != HITLS_PKI_SUCCESS) { break; } if (CheckAndAddIssuerCert(storeCtx, candidateCert, cert, issue, issueInTrust) == HITLS_PKI_SUCCESS) { return HITLS_PKI_SUCCESS; } HITLS_X509_CertFree(candidateCert); seq++; } caPath = BSL_LIST_GET_NEXT(storeCtx->caPaths); } BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND); return HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND; } static int32_t FindIssuerByDer(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_Cert *cert, HITLS_X509_Cert **issue, bool *issueInTrust) { BslList *rawIssuer = NULL; BSL_ASN1_Buffer issuerDerData = {0}; int32_t ret = HITLS_X509_CertCtrl(cert, HITLS_X509_GET_ISSUER_DN, &rawIssuer, sizeof(BslList *)); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = HITLS_X509_EncodeCanonNameList(rawIssuer, &issuerDerData); if (ret != HITLS_PKI_SUCCESS) { return ret; } if (issuerDerData.buff != NULL && issuerDerData.len > 0) { ret = HITLS_X509_GetCertBySubjectDer(storeCtx, &issuerDerData, cert, issue, issueInTrust); BSL_SAL_FREE(issuerDerData.buff); if (ret != HITLS_PKI_SUCCESS) { return ret; } } return HITLS_PKI_SUCCESS; } int32_t X509_FindIssueCert(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *certChain, HITLS_X509_Cert *cert, HITLS_X509_Cert **issue, bool *issueInTrust) { // First try to find issuer in explicitly loaded store HITLS_X509_List *store = storeCtx->store; int32_t ret = X509_GetIssueFromChain(store, cert, issue); if (ret == HITLS_PKI_SUCCESS) { *issueInTrust = true; return ret; } // Then try the certificate chain if provided if (certChain != NULL) { ret = X509_GetIssueFromChain(certChain, cert, issue); if (ret == HITLS_PKI_SUCCESS) { *issueInTrust = false; return ret; } } // If we have CA paths set, try on-demand loading based on issuer DER-encoded DN if (BSL_LIST_COUNT(storeCtx->caPaths) > 0) { ret = FindIssuerByDer(storeCtx, cert, issue, issueInTrust); if (ret == HITLS_PKI_SUCCESS) { return HITLS_PKI_SUCCESS; } } BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND); return HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND; } int32_t X509_BuildChain(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *certChain, HITLS_X509_Cert *cert, HITLS_X509_List *chain, HITLS_X509_Cert **root) { HITLS_X509_Cert *cur = cert; int32_t ret; while (cur != NULL) { HITLS_X509_Cert *issue = NULL; bool isTrustCa = false; ret = X509_FindIssueCert(storeCtx, certChain, cur, &issue, &isTrustCa); if (ret != HITLS_PKI_SUCCESS) { return ret; } // depth if (BSL_LIST_COUNT(chain) + 1 > storeCtx->verifyParam.maxDepth) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CHAIN_DEPTH_UP_LIMIT); return HITLS_X509_ERR_CHAIN_DEPTH_UP_LIMIT; } bool selfSigned = false; ret = HITLS_X509_CheckIssued(issue, issue, &selfSigned); if (ret != HITLS_PKI_SUCCESS) { return ret; } if (selfSigned) { if (root != NULL && isTrustCa) { *root = issue; } break; } ret = X509_AddCertToChain(chain, issue); if (ret != HITLS_PKI_SUCCESS) { return ret; } cur = issue; } return HITLS_PKI_SUCCESS; } static HITLS_X509_List *X509_NewCertChain(HITLS_X509_Cert *cert) { HITLS_X509_List *tmpChain = BSL_LIST_New(sizeof(HITLS_X509_Cert *)); if (tmpChain == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } int32_t ret = X509_AddCertToChain(tmpChain, cert); if (ret != HITLS_PKI_SUCCESS) { BSL_SAL_Free(tmpChain); BSL_ERR_PUSH_ERROR(ret); return NULL; } return tmpChain; } static int32_t HITLS_X509_CertChainBuildWithRoot(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_Cert *cert, HITLS_X509_List **chain) { HITLS_X509_List *tmpChain = X509_NewCertChain(cert); if (tmpChain == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } HITLS_X509_Cert *root = NULL; int32_t ret = X509_BuildChain(storeCtx, NULL, cert, tmpChain, &root); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } if (root == NULL) { BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return HITLS_X509_ERR_ROOT_CERT_NOT_FOUND; } if (X509_CertCmp(cert, root) != 0) { ret = X509_AddCertToChain(tmpChain, root); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } } *chain = tmpChain; return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_CertChainBuild(HITLS_X509_StoreCtx *storeCtx, bool isWithRoot, HITLS_X509_Cert *cert, HITLS_X509_List **chain) { if (storeCtx == NULL || cert == NULL || chain == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (isWithRoot) { return HITLS_X509_CertChainBuildWithRoot(storeCtx, cert, chain); } HITLS_X509_List *tmpChain = X509_NewCertChain(cert); if (tmpChain == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } bool selfSigned = false; int32_t ret = HITLS_X509_CheckIssued(cert, cert, &selfSigned); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } if (selfSigned) { *chain = tmpChain; return HITLS_PKI_SUCCESS; } (void)X509_BuildChain(storeCtx, NULL, cert, tmpChain, NULL); *chain = tmpChain; return HITLS_PKI_SUCCESS; } static int32_t HITLS_X509_SecBitsCheck(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_Cert *cert) { uint32_t secBits = CRYPT_EAL_PkeyGetSecurityBits(cert->tbs.ealPubKey); if (secBits < storeCtx->verifyParam.securityBits) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_CHECK_SECBITS); return HITLS_X509_ERR_VFY_CHECK_SECBITS; } return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_CheckVerifyParam(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *chain) { if ((storeCtx->verifyParam.flags & HITLS_X509_VFY_FLAG_SECBITS) != 0) { return HITLS_X509_TrvList(chain, (HITLS_X509_TrvListCallBack)HITLS_X509_SecBitsCheck, storeCtx); } return HITLS_PKI_SUCCESS; } static int32_t HITLS_X509_CheckCertExtNode(void *ctx, HITLS_X509_ExtEntry *extNode) { (void)ctx; if (extNode->cid != BSL_CID_CE_KEYUSAGE && extNode->cid != BSL_CID_CE_BASICCONSTRAINTS && extNode->critical == true) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_PROCESS_CRITICALEXT); return HITLS_X509_ERR_PROCESS_CRITICALEXT; // not process critical ext } return HITLS_PKI_SUCCESS; } static int32_t HITLS_X509_CheckCertExt(void *ctx, HITLS_X509_Cert *cert) { (void) ctx; if (cert->tbs.version != 2) { // no ext v1 cert return HITLS_PKI_SUCCESS; } return HITLS_X509_TrvList(cert->tbs.ext.extList, (HITLS_X509_TrvListCallBack)HITLS_X509_CheckCertExtNode, NULL); } int32_t HITLS_X509_VerifyParamAndExt(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *chain) { int32_t ret = HITLS_X509_CheckVerifyParam(storeCtx, chain); if (ret != HITLS_PKI_SUCCESS) { return ret; } return HITLS_X509_TrvList(chain, (HITLS_X509_TrvListCallBack)HITLS_X509_CheckCertExt, NULL); } int32_t HITLS_X509_CheckCertRevoked(HITLS_X509_Cert *cert, HITLS_X509_CrlEntry *crlEntry) { if (cert->tbs.serialNum.tag == crlEntry->serialNumber.tag && cert->tbs.serialNum.len == crlEntry->serialNumber.len && memcmp(cert->tbs.serialNum.buff, crlEntry->serialNumber.buff, crlEntry->serialNumber.len) == 0) { return HITLS_X509_ERR_VFY_CERT_REVOKED; } return HITLS_PKI_SUCCESS; } static int32_t X509_StoreCheckSignature(const BSL_Buffer *sm2UserId, const CRYPT_EAL_PkeyCtx *pubKey, uint8_t *rawData, uint32_t rawDataLen, HITLS_X509_Asn1AlgId *alg, BSL_ASN1_BitString *signature) { #ifdef HITLS_CRYPTO_SM2 bool isHasUserId = true; if (alg->sm2UserId.data == NULL) { alg->sm2UserId = *sm2UserId; isHasUserId = false; } #else (void)sm2UserId; #endif int32_t ret = HITLS_X509_CheckSignature(pubKey, rawData, rawDataLen, alg, signature); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } #ifdef HITLS_CRYPTO_SM2 if (!isHasUserId) { alg->sm2UserId.data = NULL; alg->sm2UserId.dataLen = 0; } #endif return ret; } int32_t HITLS_X509_CheckCertCrl(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_Cert *cert, HITLS_X509_Cert *parent) { int32_t ret = HITLS_X509_ERR_CRL_NOT_FOUND; HITLS_X509_Crl *crl = BSL_LIST_GET_FIRST(storeCtx->crl); HITLS_X509_CertExt *certExt = (HITLS_X509_CertExt *)parent->tbs.ext.extData; if ((certExt->extFlags & HITLS_X509_EXT_FLAG_KUSAGE) != 0) { if ((certExt->keyUsage & HITLS_X509_EXT_KU_CRL_SIGN) == 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_VFY_KU_NO_CRLSIGN); return HITLS_X509_ERR_VFY_KU_NO_CRLSIGN; } } while (crl != NULL) { if (HITLS_X509_CmpNameNode(crl->tbs.issuerName, parent->tbs.subjectName) != 0) { crl = BSL_LIST_GET_NEXT(storeCtx->crl); continue; } if (cert->tbs.version == HITLS_X509_VERSION_3 && crl->tbs.version == 1) { if (HITLS_X509_CheckAki(&parent->tbs.ext, &crl->tbs.crlExt, parent->tbs.issuerName, &parent->tbs.serialNum) != HITLS_PKI_SUCCESS) { crl = BSL_LIST_GET_NEXT(storeCtx->crl); continue; } } if (HITLS_X509_CheckTime(storeCtx, &(crl->tbs.validTime)) != HITLS_PKI_SUCCESS) { crl = BSL_LIST_GET_NEXT(storeCtx->crl); continue; } ret = HITLS_X509_TrvList(crl->tbs.crlExt.extList, (HITLS_X509_TrvListCallBack)HITLS_X509_CheckCertExtNode, NULL); if (ret != HITLS_PKI_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } #ifdef HITLS_CRYPTO_SM2 ret = X509_StoreCheckSignature(&storeCtx->verifyParam.sm2UserId, parent->tbs.ealPubKey, crl->tbs.tbsRawData, crl->tbs.tbsRawDataLen, &(crl->signAlgId), &(crl->signature)); #else ret = X509_StoreCheckSignature(NULL, parent->tbs.ealPubKey, crl->tbs.tbsRawData, crl->tbs.tbsRawDataLen, &(crl->signAlgId), &(crl->signature)); #endif if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = HITLS_X509_TrvList(crl->tbs.revokedCerts, (HITLS_X509_TrvListCallBack)HITLS_X509_CheckCertRevoked, cert); if (ret != HITLS_PKI_SUCCESS) { return ret; } crl = BSL_LIST_GET_NEXT(storeCtx->crl); } return ret; } int32_t HITLS_X509_VerifyCrl(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *chain) { // Only the self-signed certificate, and the CRL is not verified if (BSL_LIST_COUNT(chain) == 1) { return HITLS_PKI_SUCCESS; } if ((storeCtx->verifyParam.flags & HITLS_X509_VFY_FLAG_CRL_ALL) != 0) { // Device certificate check is included return HITLS_X509_TrvListWithParent(chain, (HITLS_X509_TrvListWithParentCallBack)HITLS_X509_CheckCertCrl, storeCtx); } if ((storeCtx->verifyParam.flags & HITLS_X509_VFY_FLAG_CRL_DEV) != 0) { HITLS_X509_Cert *cert = BSL_LIST_GET_FIRST(chain); HITLS_X509_Cert *parent = BSL_LIST_GET_NEXT(chain); return HITLS_X509_CheckCertCrl(storeCtx, cert, parent); } return HITLS_PKI_SUCCESS; } int32_t X509_VerifyChainCert(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *chain) { HITLS_X509_Cert *issue = BSL_LIST_GET_LAST(chain); HITLS_X509_Cert *cur = issue; int32_t ret; while (cur != NULL) { if ((storeCtx->verifyParam.flags & HITLS_X509_VFY_FLAG_TIME) != 0) { ret = HITLS_X509_CheckTime(storeCtx, &cur->tbs.validTime); if (ret != HITLS_PKI_SUCCESS) { return ret; } } #ifdef HITLS_CRYPTO_SM2 ret = X509_StoreCheckSignature(&storeCtx->verifyParam.sm2UserId, issue->tbs.ealPubKey, cur->tbs.tbsRawData, cur->tbs.tbsRawDataLen, &cur->signAlgId, &cur->signature); #else ret = X509_StoreCheckSignature(NULL, issue->tbs.ealPubKey, cur->tbs.tbsRawData, cur->tbs.tbsRawDataLen, &cur->signAlgId, &cur->signature); #endif if (ret != HITLS_PKI_SUCCESS) { return ret; } issue = cur; cur = BSL_LIST_GET_PREV(chain); }; return HITLS_PKI_SUCCESS; } static int32_t X509_GetVerifyCertChain(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *chain, HITLS_X509_List **comChain) { HITLS_X509_Cert *cert = BSL_LIST_GET_FIRST(chain); if (cert == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } HITLS_X509_List *tmpChain = X509_NewCertChain(cert); if (tmpChain == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } HITLS_X509_Cert *root = NULL; int32_t ret = X509_BuildChain(storeCtx, chain, cert, tmpChain, &root); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); BSL_ERR_PUSH_ERROR(ret); return ret; } if (root == NULL) { BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_ROOT_CERT_NOT_FOUND); return HITLS_X509_ERR_ROOT_CERT_NOT_FOUND; } if (X509_CertCmp(cert, root) != 0) { ret = X509_AddCertToChain(tmpChain, root); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } } *comChain = tmpChain; return HITLS_PKI_SUCCESS; } int32_t HITLS_X509_CertVerify(HITLS_X509_StoreCtx *storeCtx, HITLS_X509_List *chain) { if (storeCtx == NULL || chain == NULL) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_INVALID_PARAM); return HITLS_X509_ERR_INVALID_PARAM; } if (BSL_LIST_COUNT(chain) <= 0) { BSL_ERR_PUSH_ERROR(HITLS_X509_ERR_CERT_CHAIN_COUNT_IS0); return HITLS_X509_ERR_CERT_CHAIN_COUNT_IS0; } HITLS_X509_List *tmpChain = NULL; int32_t ret = X509_GetVerifyCertChain(storeCtx, chain, &tmpChain); if (ret != HITLS_PKI_SUCCESS) { return ret; } ret = HITLS_X509_VerifyParamAndExt(storeCtx, tmpChain); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } ret = HITLS_X509_VerifyCrl(storeCtx, tmpChain); if (ret != HITLS_PKI_SUCCESS) { BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } ret = X509_VerifyChainCert(storeCtx, tmpChain); BSL_LIST_FREE(tmpChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } HITLS_X509_StoreCtx *HITLS_X509_ProviderStoreCtxNew(HITLS_PKI_LibCtx *libCtx, const char *attrName) { HITLS_X509_StoreCtx *storeCtx = HITLS_X509_StoreCtxNew(); if (storeCtx == NULL) { return NULL; } storeCtx->libCtx = libCtx; storeCtx->attrName = attrName; return storeCtx; } #endif // HITLS_PKI_X509_VFY
2401_83913325/openHiTLS-examples_2461
pki/x509_verify/src/hitls_x509_verify.c
C
unknown
34,228
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. import sys sys.dont_write_bytecode = True import json import os import re sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__)))) from methods import trans2list, unique_list, save_json_file class Feature: def __init__(self, name, target, is_lib, parent, children, deps, opts, impl, ins_set): self.name = name self.target = target self.is_lib = is_lib # Indicates whether the target file is a lib or exe file. self.parent = parent self.children = children self.deps = deps self.opts = opts self.impl = impl # Implementation mode self.ins_set = ins_set # Instruction Set @classmethod def simple(cls, name, target, is_lib, parent, impl): return Feature(name, target, is_lib, parent, [], [], [], impl, []) class FeatureParser: """ Parsing feature files """ lib_dir_map = { "hitls_bsl": "bsl", "hitls_crypto": "crypto", "hitls_tls": "tls", "hitls_pki": "pki", "hitls_auth": "auth" } def __init__(self, file_path): self._fp = file_path with open(file_path, 'r', encoding='utf-8') as f: self._cfg = json.loads(f.read()) self._file_check() # Features and related information. self._feas_info = self._get_feas_info() # Assembly type supported by the openHiTLS. self._asm_types = self._get_asm_types() @property def libs(self): return self._cfg['libs'] @property def executes(self): return self._cfg['executes'] @property def modules(self): return self._cfg['modules'] @property def asm_types(self): return self._asm_types @property def feas_info(self): return self._feas_info def _file_check(self): if 'libs' not in self._cfg or 'modules' not in self._cfg: raise FileNotFoundError("The format of file %s is incorrect." % self._fp) @staticmethod def _add_key_value(obj, key, value): if value: obj[key] = value def _add_fea(self, feas_info, feature: Feature): fea_name = feature.name feas_info.setdefault(fea_name, {}) if feature.is_lib: self._add_key_value(feas_info[fea_name], 'lib', feature.target) else: self._add_key_value(feas_info[fea_name], 'execute', feature.target) self._add_key_value(feas_info[fea_name], 'parent', feature.parent) self._add_key_value(feas_info[fea_name], 'children', feature.children) self._add_key_value(feas_info[fea_name], 'opts', feature.opts) self._add_key_value(feas_info[fea_name], 'deps', feature.deps) feas_info[fea_name].setdefault('impl', {}) feas_info[fea_name]['impl'][feature.impl] = feature.ins_set if feature.ins_set else [] def _parse_fea_obj(self, name, target, is_lib, parent, impl, fea_obj, feas_info): feature = Feature.simple(name, target, is_lib, parent, impl) if not fea_obj: self._add_fea(feas_info, feature) return feature.deps = fea_obj.get('deps', None) feature.opts = fea_obj.get('opts', None) feature.ins_set = fea_obj.get('ins_set', None) non_sub_keys = ['opts', 'deps', 'ins_set', 'help'] for key, obj in fea_obj.items(): if key not in non_sub_keys: feature.children.append(key) self._parse_fea_obj(key, target, is_lib, name, impl, obj, feas_info) self._add_fea(feas_info, feature) def parse_fearuers(self, all_feas, tmp_feas_info, target, target_obj, is_lib): tmp_feas_info[target] = {} for impl, impl_obj in target_obj['features'].items(): for fea, fea_obj in impl_obj.items(): self._parse_fea_obj(fea, target, is_lib, None, impl, fea_obj, tmp_feas_info[target]) # Check that feature names in different target are unique. tgt_feas = set(tmp_feas_info[target].keys()) repeat_feas = all_feas.intersection(tgt_feas) if len(repeat_feas) != 0: raise ValueError("Error: feature '%s' has been defined in other target." % (repeat_feas)) all_feas.update(tgt_feas) def _get_feas_info(self): """ description: Parse the feature.json file to obtain feature information and check that feature names in different libraries are unique. return: feas_info: { "children":[], "parent":[], "deps":[], "opts":[[],[]], "lib":"", "execute":"" "impl":{"c":[], "armv8:[], ...}, # [] lists the instruction sets supported by the feature. } """ all_feas = set() tmp_feas_info = {} for lib, lib_obj in self._cfg['libs'].items(): self.parse_fearuers(all_feas, tmp_feas_info, lib, lib_obj, True) for exe, exe_obj in self._cfg['executes'].items(): self.parse_fearuers(all_feas, tmp_feas_info, exe, exe_obj, False) feas_info = {} for obj in tmp_feas_info.values(): feas_info.update(obj) self._fill_fea_modules(feas_info) self._correct_impl(feas_info) return feas_info def _fill_fea_modules(self, feas_info): for top_mod in self.modules: for mod, mod_obj in self.modules[top_mod].items(): formated_mod = "{}::{}".format(top_mod, mod) for fea in mod_obj.get('.features', []): if fea not in feas_info: raise ValueError("Unrecognized '%s' in '.features' of '%s::%s'" % (fea, top_mod, mod)) if 'modules' not in feas_info[fea]: feas_info[fea]['modules'] = [formated_mod] else: feas_info[fea]['modules'].append(formated_mod) @staticmethod def _correct_impl(feas_info): """Updated the implementation modes of sub-features based on the parent feature.""" for fea in feas_info.keys(): parent = feas_info[fea].get('parent', '') if not parent: continue if len(feas_info[fea]['impl'].keys()) == 1 and 'c' in feas_info[fea]['impl']: feas_info[fea]['impl'] = feas_info[parent]['impl'] def _get_asm_types(self): asm_type_set = set() [asm_type_set.update(self.libs[lib]['features'].keys()) for lib in self.libs.keys()] asm_type_set.discard('c') asm_type_set.add('no_asm') return asm_type_set def get_module_deps(self, module, dep_list, result): return self._get_module_deps(module, dep_list, result) def _get_module_deps(self, module, dep_list, result): """ Recursively obtains the modules on which the modules depend. module: [IN] module name, such as crypto::sha2 dep_list: [OUT] Dependency list, which is an intermediate variable result: [OUT] result """ top_module, sub_module = module.split('::') mod_obj = self.modules[top_module][sub_module] if '.deps' not in mod_obj: result.update(dep_list) return for dep_mod in mod_obj['.deps']: if dep_mod in dep_list: # A dependency that already exists in a dependency chain is a circular dependency. raise Exception("Cyclic dependency") dep_list.append(dep_mod) self._get_module_deps(dep_mod, dep_list, result) dep_list.pop() def get_mod_srcs(self, top_mod, sub_mod, mod_obj): srcs = self._cfg['modules'][top_mod][sub_mod]['.srcs'] asm_type = mod_obj.get('asmType', 'c') inc = mod_obj.get('incSet', '') blurred_srcs = [] if not isinstance(srcs, dict): blurred_srcs.extend(trans2list(srcs)) return blurred_srcs blurred_srcs.extend(trans2list(srcs.get('public', []))) if asm_type == 'c': blurred_srcs.extend(trans2list(srcs.get('no_asm', []))) return blurred_srcs if asm_type not in srcs: raise ValueError("Missing '.srcs[%s]' in modules '%s::%s'" % (asm_type, top_mod, sub_mod)) if not isinstance(srcs[asm_type], dict): blurred_srcs.extend(trans2list(srcs[asm_type])) return blurred_srcs if inc: blurred_srcs.extend(trans2list(srcs[asm_type][inc])) else: first_key = list(srcs[asm_type].keys())[0] blurred_srcs.extend(trans2list(srcs[asm_type][first_key])) return blurred_srcs class FeatureConfigParser: """ Parses the user feature configuration file. """ # Specifications of keys and values in the file. key_value = { "system": {"require": False, "type": str, "choices": ["linux", ""], "default": "linux"}, "bits": {"require": False, "type": int, "choices": [32, 64], "default": 64}, "endian": {"require": True, "type": str, "choices": ["little", "big"], "default": "little"}, "libType": { "require": True, "type": list, "choices": ["static", "shared", "object"], "default": ["static", "shared", "object"] }, "asmType":{"require": True, "type": str, "choices": [], "default": "no_asm"}, "libs":{"require": True, "type": dict, "choices": [], "default": {}}, "bundleLibs":{"require": False, "type": bool, "choices": [True, False], "default": False}, "securecLib":{"require": False, "type": str, "choices": ["boundscheck", "securec", "sec_shared.z", ""], "default": "boundscheck"}, "executes":{"require": False, "type": dict, "default": {}} } def __init__(self, features: FeatureParser, file_path): self._features = features self._config_file = file_path with open(file_path, 'r', encoding='utf-8') as f: self._cfg = json.loads(f.read()) self.key_value['asmType']['choices'] = list(features.asm_types) self.key_value['libs']['choices'] = list(features.libs) self._file_check() @classmethod def default_cfg(cls): config = {} for key in cls.key_value.keys(): if cls.key_value[key]["require"]: config[key] = cls.key_value[key]["default"] return config @property def libs(self): return self._cfg['libs'] @property def executes(self): return self._cfg.get('executes', {}) @property def lib_type(self): return trans2list(self._cfg['libType']) @property def asm_type(self): return self._cfg['asmType'] @property def bundle_libs(self): if 'bundleLibs' in self._cfg: return self._cfg['bundleLibs'] return self.key_value['bundleLibs']['default'] @property def securec_lib(self): if 'securecLib' in self._cfg: return self._cfg['securecLib'] return self.key_value['securecLib']['default'] @staticmethod def _get_fea_and_inc(asm_fea): if '::' in asm_fea: return asm_fea.split('::') else: return asm_fea, '' def enable_executes(self, targets): for target in targets: if 'executes' not in self._cfg: self._cfg['executes'] = {target: {}} else: self._cfg['executes'][target] = {} exe_objs = [] for fea, fea_obj in self._features.feas_info.items(): if fea_obj.get('execute', '') != target: continue for i in fea_obj['impl'].keys(): self._cfg['executes'][target].setdefault(i, []) self._cfg['executes'][target][i].append(fea) def _asm_fea_check(self, asm_fea, asm_type, info): fea, inc = self._get_fea_and_inc(asm_fea) feas_info = self._features.feas_info if fea not in feas_info: raise ValueError("Unsupported '%s' in %s" % (fea, info)) if asm_type not in feas_info[fea]['impl']: raise ValueError("Feature '%s' has no assembly implementation of type '%s' in %s" % (fea, asm_type, info)) if inc: if inc not in feas_info[fea]['impl'] and inc not in feas_info[fea]['impl'][asm_type]: raise ValueError("Unsupported instruction set of '%s' in %s" % (asm_fea, info)) return fea, inc def _file_check(self): for key, value in self.key_value.items(): if value['require']: if key not in self._cfg.keys(): raise ValueError("Error feature_config file: missing '%s'" % key) for key, value in self._cfg.items(): if key not in self.key_value.keys(): raise ValueError("Error feature_config file: unsupported config '%s'" % key) if not isinstance(value, self.key_value.get(key).get("type")): raise ValueError("Error feature_config file: wrong type of '%s'" % key) value_type = type(value) if value_type == str or value_type == str: if value not in self.key_value.get(key).get("choices"): if key == "system": print("Info: There is no {} implementation by default, you should set its SAL callbacks to make it work.".format(value)) continue raise ValueError("Error feature_config file: wrong value of '%s'" % key) elif value_type == list: choices = set(self.key_value[key]["choices"]) if not set(value).issubset(choices): raise ValueError("Error feature_config file: wrong value of '%s'" % key) for lib, lib_obj in self._cfg['libs'].items(): if lib not in self._features.libs: raise ValueError("Error feature_config file: unsupported lib '%s'" % lib) for fea in lib_obj.get('c', []): if fea not in self._features.feas_info: raise ValueError("Error feature_config file: unsupported fea '%s' in lib '%s'" % (fea, lib)) asm_feas = [] for asm_fea in lib_obj.get('asm', []): fea, _ = self._asm_fea_check(asm_fea, self.asm_type, 'feature_config file') if fea in asm_feas: raise ValueError("Error feature_config file: duplicate assembly feature '%s'" % fea) asm_feas.append(fea) def set_param(self, key, value, set_default=True): if key == 'bundleLibs': self._cfg[key] = value return if value: self._cfg[key] = value return if not set_default: return if key not in self._cfg or not self._cfg[key]: print("Warning: Configuration item '{}' is missing and has been set to the default value '{}'.".format( key, self.key_value.get(key).get('default'))) self._cfg[key] = self.key_value.get(key).get('default') def _get_related_feas(self, fea, feas_info, related: set): related.add(fea) if 'parent' in feas_info[fea]: parent = feas_info[fea]['parent'] for dep in feas_info[parent].get('deps', []): self._get_related_feas(dep, feas_info, related) if 'children' in feas_info[fea]: for child in feas_info[fea]['children']: self._get_related_feas(child, feas_info, related) if 'deps' in feas_info[fea]: for dep in feas_info[fea]['deps']: self._get_related_feas(dep, feas_info, related) def _get_parents(self, disables): parents = set() for d in disables: relation = self._features.feas_info.get(d) if relation and 'parent' in relation: parents.add(relation['parent']) return parents def _add_depend_feas(self, enable_feas, feas_info): related = set() for f in enable_feas: fea, inc = self._get_fea_and_inc(f) self._get_related_feas(fea, feas_info, related) enable_feas.update(related) def _check_asm_fea_enable(self, enable_feas, feas, feas_info): not_in_enable = [] for f in feas: fea, _ = self._get_fea_and_inc(f) if fea in enable_feas: # This feature is already in the enable list. continue rel = feas_info[fea] is_enable = False while('parent' in rel): parent = rel['parent'] if parent in enable_feas: # This feature is already in the enable list. is_enable = True break rel = feas_info[parent] if not is_enable: not_in_enable.append(fea) if not_in_enable: raise ValueError("To add '%s' assembly requires add it to 'enable' list" % not_in_enable) def get_enable_feas(self, arg_enable, arg_asm): """ Get the enabled features form: 1. build/feature_config.json 2. argument: enable list 3. argument: asm list """ enable_feas = set() enable_asm_feas = set() # 1. Exist feas in build/feature_config.json for _, lib_obj in self._cfg['libs'].items(): enable_feas.update(lib_obj.get('c', [])) enable_asm_feas.update(lib_obj.get('asm', [])) # 2. Obtains the properties from the input parameter: enable list. feas_info = self._features.feas_info if 'all' in arg_enable: # all features enable_feas.update(set(x for x in feas_info.keys())) else: for enable in arg_enable: if enable in self._features.libs: # features in a lib enable_feas.update(set(x for x, y in feas_info.items() if enable == y.get('lib', ''))) else: # The feature is not lib and needs to be added separately. enable_feas.add(enable) enable_feas.update(enable_asm_feas) self._add_depend_feas(enable_feas, feas_info) self._check_asm_fea_enable(enable_feas, arg_asm, feas_info) enable_asm_feas.update(arg_asm) return enable_feas, enable_asm_feas def _add_feature(self, fea, impl_type, inc=''): add_fea = fea if inc == '' else '{}::{}'.format(fea, inc) lib = self._features.feas_info[fea]['lib'] if lib not in self._cfg['libs']: self._cfg['libs'][lib] = {impl_type: [add_fea]} elif impl_type not in self._cfg['libs'][lib]: self._cfg['libs'][lib][impl_type] = [add_fea] elif fea not in self._cfg['libs'][lib][impl_type]: self._cfg['libs'][lib][impl_type].append(add_fea) def set_asm_type(self, asm_type): if self._cfg['asmType'] == 'no_asm': self._cfg['asmType'] = asm_type elif self._cfg['asmType'] != asm_type: raise ValueError('Error asmType: %s is different from feature_config file.' % (asm_type)) def set_asm_features(self, enable_feas, asm_feas, asm_type): feas_info = self._features.feas_info # Clear the assembly features first. for lib in self._cfg['libs']: if 'asm' in self._cfg['libs'][lib]: self._cfg['libs'][lib]['asm'] = [] # Add assembly features. if asm_feas: for asm_feature in asm_feas: fea, inc = self._asm_fea_check(asm_feature, asm_type, 'input asm list') if inc and inc != asm_type: raise ValueError("Input instruction '%s' is not the same as 'asm_type' '%s'" % (inc, asm_type)) self._add_feature(fea, 'asm', inc) else: for fea in enable_feas: if asm_type not in feas_info[fea]['impl']: continue self._add_feature(fea, 'asm') def set_c_features(self, enable_feas): for f in enable_feas: fea, _ = self._get_fea_and_inc(f) if self._features.feas_info[fea].get('execute'): continue if 'c' in self._features.feas_info[fea]['impl']: self._add_feature(fea, 'c') def _update_enable_feature(self, features, disables): """ The sub-feature macro is derived from the parent feature macro in the code. Therefore, the sub-feature is removed and the parent feature is retained. """ disable_parents = self._get_parents(disables) tmp_feas = features.copy() enable_set = set() feas_info = self._features.feas_info for f in tmp_feas: fea, _ = self._get_fea_and_inc(f) rel = feas_info[fea] if fea in disable_parents: if 'children' in rel: enable_set.update(rel['children']) enable_set.discard(fea) else: is_fea_contained = False while 'parent' in rel: if rel['parent'] in disables: raise Exception("The 'disables' features {} and 'enables' featrues {} conflict".format(fea, disables)) if rel['parent'] in features: is_fea_contained = True break rel = feas_info[rel['parent']] if not is_fea_contained: enable_set.add(fea) enable_set.difference_update(set(disables)) return list(enable_set) def check_bn_config(self): lib = 'hitls_crypto' if lib not in self._cfg['libs']: return has_bn = False bn_pattern = "bn_" for impl_type in self._cfg['libs'][lib]: if 'bn' in self._cfg['libs'][lib][impl_type]: has_bn = True break for fea in self._cfg['libs'][lib][impl_type]: if re.match(bn_pattern, fea) : has_bn = True break if has_bn and 'bits' not in self._cfg: raise ValueError("If 'bn' is used, the 'bits' of the system must be configured.") def _re_sort_lib(self): # Change the key sequence of the 'libs' dictionary. Otherwise, the compilation fails. lib_sort = ['hitls_bsl', 'hitls_crypto', 'hitls_tls', "hitls_pki", "hitls_auth"] libs = self.libs.copy() self._cfg['libs'].clear() for lib in lib_sort: if lib in libs: self._cfg['libs'][lib] = libs[lib].copy() def update_feature(self, enables, disables, gen_cmake): ''' update feature: 1. Add the default lib and features: hitls_bsl: sal 2. Delete features based on the relationship between features. ''' libs = self._cfg['libs'] if len(libs) == 0: if gen_cmake: raise ValueError("No features are enabled.") else: return libs.setdefault('hitls_bsl', {'c':['sal']}) if 'hitls_bsl' not in libs: libs['hitls_bsl'] = {'c':['sal']} elif 'c' not in libs['hitls_bsl']: libs['hitls_bsl']['c'] = ['sal'] elif 'sal' not in libs['hitls_bsl']['c']: libs['hitls_bsl']['c'].append('sal') for lib in libs: if 'c' in libs[lib]: libs[lib]['c'] = self._update_enable_feature(libs[lib]['c'], disables) libs[lib]['c'].sort() if 'asm' in libs[lib]: libs[lib]['asm'] = self._update_enable_feature(libs[lib]['asm'], disables) libs[lib]['asm'].sort() self._re_sort_lib() if 'all' in enables: self.set_param('system', None) self.set_param('bits', None) def save(self, path): save_json_file(self._cfg, path) def get_fea_macros(self): macros = set() for lib, lib_value in self.libs.items(): lib_upper = lib.upper() for fea in lib_value.get('c', []): macros.add("-D%s_%s" % (lib_upper, fea.upper())) for fea in lib_value.get('asm', []): fea = fea.split('::')[0] macros.add("-D%s_%s" % (lib_upper, fea.upper())) if 'bn' in fea: macros.add("-D%s_%s_%s" % (lib_upper, 'BN', self.asm_type.upper())) else: macros.add("-D%s_%s_%s" % (lib_upper, fea.upper(), self.asm_type.upper())) if lib_upper not in macros: macros.add("-D%s" % lib_upper) if self._cfg['endian'] == 'big': macros.add("-DHITLS_BIG_ENDIAN") if self._cfg.get('system', "") == "linux": macros.add("-DHITLS_BSL_SAL_LINUX") bits = self._cfg.get('bits', 0) if bits == 32: macros.add("-DHITLS_THIRTY_TWO_BITS") elif bits == 64: macros.add("-DHITLS_SIXTY_FOUR_BITS") return list(macros) def _re_get_fea_modules(self, fea, feas_info, asm_type, inc, modules): """Obtain the modules on which the current feature and subfeature depend.""" for mod in feas_info[fea].get('modules', []): modules.setdefault(mod, {}) modules[mod]["asmType"] = asm_type if inc: modules[mod]["incSet"] = inc for child in feas_info[fea].get('children', []): self._re_get_fea_modules(child, feas_info, asm_type, inc, modules) def _get_target_modules(self, target, is_lib): modules = {} feas_info = self._features.feas_info obj = self.libs if is_lib else self.executes for fea in obj[target].get('c', []): self._re_get_fea_modules(fea, feas_info, 'c', '', modules) for asm_fea in obj[target].get('asm', []): fea, inc = self._get_fea_and_inc(asm_fea) self._re_get_fea_modules(fea, feas_info, self.asm_type, inc, modules) for mod in modules: mod_dep_mods = set() self._features.get_module_deps(mod, [], mod_dep_mods) modules[mod]['deps'] = list(mod_dep_mods) if len(modules.keys()) == 0: raise ValueError("Error: no module is enabled in %s" % target) return modules def get_enable_modules(self): """ Obtain the modules required for compiling each lib features and the modules on which the lib feature depends (for obtaining the include directory). 1. Add modules and their dependent modules based on features. 2. Check whether the dependent modules are enabled. return: {'lib/exe':{"mod1":{"deps":[], "asmType":"", "incSet":""}}} Module format: top_dir::sub_dir """ enable_libs_mods = {} enable_exes_mods = {} enable_mods = set() for lib in self.libs.keys(): enable_libs_mods[lib] = self._get_target_modules(lib, True) enable_mods.update(enable_libs_mods[lib]) for exe in self.executes.keys(): enable_exes_mods[exe] = self._get_target_modules(exe, False) enable_mods.update(enable_exes_mods[exe]) # Check whether the dependent module is enabled. for lib in enable_libs_mods.keys(): for mod in enable_libs_mods[lib]: for dep_mod in enable_libs_mods[lib][mod].get('deps', []): if dep_mod == "platform::Secure_C": continue if dep_mod not in enable_mods: raise ValueError("Error: '%s' depends on '%s', but '%s' is disabled." % (mod, dep_mod, dep_mod)) for exe in enable_exes_mods.keys(): for mod in enable_exes_mods[exe]: for dep_mod in enable_exes_mods[exe][mod].get('deps', []): if dep_mod == "platform::Secure_C": continue if dep_mod not in enable_mods: raise ValueError("Error: '%s' depends on '%s', but '%s' is disabled." % (mod, dep_mod, dep_mod)) return enable_libs_mods, enable_exes_mods def filter_no_asm_config(self): self._cfg['asmType'] = 'no_asm' for lib in self._cfg['libs']: if 'asm' in self._cfg['libs'][lib]: self._cfg['libs'][lib]['asm'] = [] def _check_fea_opts_arr(self, opts, fea, enable_feas): for opt_arr in opts: has_opt = False for opt_fea in opt_arr: if opt_fea in enable_feas: has_opt = True break parent = self._features.feas_info[opt_fea].get('parent', '') while parent: if parent in enable_feas: has_opt = True break parent = self._features.feas_info[parent].get('parent', '') if has_opt: break if not has_opt: raise ValueError("At leaset one fea in %s must be enabled for '%s*'" % (opt_arr, fea)) def _check_opts(self, fea, enable_feas): if 'opts' not in self._features.feas_info[fea]: return opts = self._features.feas_info[fea]['opts'] if not isinstance(opts[0], list): opts = [opts] self._check_fea_opts_arr(opts, fea, enable_feas) def _check_family_opts(self, fea, key, enable_feas): values = self._features.feas_info[fea].get(key, []) if not isinstance(values, list): values = [values] for value in values: self._check_opts(value, enable_feas) self._check_family_opts(value, key, enable_feas) def check_fea_opts(self): enable_feas = set() for _, lib_obj in self.libs.items(): enable_feas.update(lib_obj.get('c', [])) enable_feas.update(lib_obj.get('asm', [])) for fea in enable_feas: fea = fea.split("::")[0] self._check_opts(fea, enable_feas) self._check_family_opts(fea, 'parent', enable_feas) self._check_family_opts(fea, 'children', enable_feas) class CompleteOptionParser: """ Parses all compilation options. """ # Sequence in which compilation options are added, including all compilation option types. option_order = [ "CC_DEBUG_FLAGS", "CC_OPT_LEVEL", # Optimization Level "CC_OVERALL_FLAGS", # Overall Options "CC_WARN_FLAGS", # Warning options "CC_LANGUAGE_FLAGS", # Language Options "CC_CDG_FLAGS", # Code Generation Options "CC_MD_DEPENDENT_FLAGS", # Machine-Dependent Options "CC_OPT_FLAGS", # Optimization Options "CC_SEC_FLAGS", # Secure compilation options "CC_DEFINE_FLAGS", # Custom Macro "CC_USER_DEFINE_FLAGS", # User-defined compilation options are reserved. ] def __init__(self, file_path): self._fp = file_path with open(file_path, 'r') as f: self._cfg = json.loads(f.read()) self._file_check() self._option_type_map = {} for option_type in self._cfg['compileFlag']: for option in trans2list(self._cfg['compileFlag'][option_type]): self._option_type_map[option] = option_type @property def option_type_map(self): return self._option_type_map @property def type_options_map(self): return self._cfg['compileFlag'] def _file_check(self): if 'compileFlag' not in self._cfg or 'linkFlag' not in self._cfg: raise FileNotFoundError("The format of file %s is incorrect." % self._fp) for option_type in self._cfg['compileFlag']: if option_type not in self.option_order: raise FileNotFoundError("The format of file %s is incorrect." % self._fp) class CompileConfigParser: """ Parse the user compilation configuration file. """ def __init__(self, all_options: CompleteOptionParser, file_path=''): with open(file_path, 'r') as f: self._cfg = json.loads(f.read()) self._all_options = all_options @property def options(self): return self._cfg['compileFlag'] @property def link_flags(self): return self._cfg['linkFlag'] @classmethod def default_cfg(cls): config = { 'compileFlag': {}, 'linkFlag': {} } return config def save(self, path): save_json_file(self._cfg, path) def change_options(self, options, is_add): option_op = 'CC_FLAGS_ADD' if is_add else 'CC_FLAGS_DEL' for option in options: option_type = 'CC_USER_DEFINE_FLAGS' if option in self._all_options.option_type_map: option_type = self._all_options.option_type_map[option] if option_type not in self._cfg['compileFlag']: self._cfg['compileFlag'][option_type] = {} flags = self._cfg['compileFlag'][option_type] flags[option_op] = unique_list(flags.get(option_op, []) + [option]) def change_link_flags(self, flags, is_add): link_op = 'LINK_FLAG_ADD' if is_add else 'LINK_FLAG_DEL' new_flags = self._cfg['linkFlag'].get(link_op, []) + flags self._cfg['linkFlag'][link_op] = unique_list(new_flags) def add_debug_options(self): flags_add = {'CC_FLAGS_ADD': ['-g3', '-gdwarf-2']} flags_del = {'CC_FLAGS_DEL': ['-O2', '-D_FORTIFY_SOURCE=2']} self._cfg['compileFlag']['CC_DEBUG_FLAGS'] = flags_add self._cfg['compileFlag']['CC_OPT_LEVEL'] = flags_del def filter_hitls_defines(self): for flag in list(self.link_flags.keys()): del self.link_flags[flag] for flag in list(self.options.keys()): if flag != 'CC_USER_DEFINE_FLAGS' and flag != 'CC_DEFINE_FLAGS': del self.options[flag] class CompileParser: """ Parse the compile.json file. json key and value: compileFlag: compilation options linkFlag: link option """ def __init__(self, all_options: CompleteOptionParser, file_path): self._fp = file_path self._all_options = all_options with open(file_path, 'r') as f: self._cfg = json.loads(f.read()) self._file_check() @property def options(self): return self._cfg["compileFlag"] @property def link_flags(self): return self._cfg["linkFlag"] def _file_check(self): if 'compileFlag' not in self._cfg or 'linkFlag' not in self._cfg: raise FileNotFoundError("Error compile file: missing 'compileFlag' or 'linkFlag'") for option_type in self.options: if option_type == 'CC_USER_DEFINE_FLAGS': continue if option_type not in self._all_options.type_options_map: raise ValueError("no '{}' option type in complete_options.json".format(option_type)) for option in self.options[option_type]: if option not in self._all_options.type_options_map[option_type]: raise ValueError("unrecognized option '{}' in type {}.".format(option, option_type)) for option_type in self._cfg['linkFlag']: if option_type not in ['PUBLIC', 'SHARED', 'EXE']: raise FileNotFoundError('Incorrect file format: %s' % self._fp) def union_options(self, custom_cfg: CompileConfigParser): options = [] for option_type in CompleteOptionParser.option_order: options.extend(self.options.get(option_type, [])) if option_type not in custom_cfg.options: continue for option in custom_cfg.options[option_type].get('CC_FLAGS_ADD', []): if option not in options: options.append(option) for option in custom_cfg.options[option_type].get('CC_FLAGS_DEL', []): if option in options: options.remove(option) flags = self.link_flags for flag in custom_cfg.link_flags.get('LINK_FLAG_ADD', []): if flag not in flags['PUBLIC']: flags['PUBLIC'].append(flag) if flag not in flags['EXE']: flags['EXE'].append(flag) if flag not in flags['SHARED']: flags['SHARED'].append(flag) for flag in custom_cfg.link_flags.get('LINK_FLAG_DEL', []): if flag in flags['PUBLIC']: flags['PUBLIC'].remove(flag) if flag in flags['EXE']: flags['EXE'].remove(flag) if flag in flags['SHARED']: flags['SHARED'].remove(flag) return options, flags
2401_83913325/openHiTLS-examples_2461
script/config_parser.py
Python
unknown
37,566
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. import shutil import sys sys.dont_write_bytecode = True import os import json # Convert x to list def trans2list(x): if x == None: return [] if type(x) == list: return x if type(x) == set: return x if type(x) == str: return [x] raise ValueError('Unsupported type: "%s"' % type(x)) def unique_list(x): """ Deduplicate the list. """ return list(dict.fromkeys(x)) def copy_file(src_file, dest_file, isCoverd=True): if not os.path.exists(src_file): raise FileNotFoundError('Src file not found: ' + src_file) if os.path.exists(dest_file): if isCoverd: shutil.copy2(src_file, dest_file) else: shutil.copy2(src_file, dest_file) def save_json_file(content, path): with open(path, 'w') as f: f.write(json.dumps(content, indent=4))
2401_83913325/openHiTLS-examples_2461
script/methods.py
Python
unknown
1,386
# This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. cmake_minimum_required(VERSION 3.16 FATAL_ERROR) PROJECT(openHiTLS_TEST) set(openHiTLS_SRC "${PROJECT_SOURCE_DIR}/..") if(CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64") option(__x86_64__ "x86" ON) endif() set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -Werror -Wformat=2 -Wno-format-nonliteral -Wno-deprecated-declarations -Wno-unused-but-set-variable -Wl,--wrap=REC_Read -Wl,--wrap=REC_Write") message(STATUS "System processor :${CMAKE_SYSTEM_PROCESSOR}") message(STATUS "Enable bsl uio sctp :${ENABLE_UIO_SCTP}") if(CMAKE_SIZEOF_VOID_P EQUAL 8) message(STATUS "System architecture: 64") else() message(STATUS "System architecture: 32") endif() if(ENABLE_GCOV) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage -lgcov") endif() if(ENABLE_ASAN) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=address -fno-stack-protector -fno-omit-frame-pointer") endif() if(CUSTOM_CFLAGS) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CUSTOM_CFLAGS}") endif() if(DEBUG) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0 -g") endif() if(PRINT_TO_TERMINAL) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DPRINT_TO_TERMINAL=${PRINT_TO_TERMINAL}") endif() if(ENABLE_FAIL_REPEAT) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DENABLE_FAIL_REPEAT=${ENABLE_FAIL_REPEAT}") endif() if(OS_BIG_ENDIAN) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mbig-endian") endif() set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D_FILE_OFFSET_BITS=64") string(FIND "${CUSTOM_CFLAGS}" "-DHITLS_PKI" BUILD_PKI) string(FIND "${CUSTOM_CFLAGS}" "-DHITLS_AUTH" BUILD_AUTH) string(FIND "${CUSTOM_CFLAGS}" "-DHITLS_CRYPTO" BUILD_CRYPTO) string(FIND "${CUSTOM_CFLAGS}" "-DHITLS_TLS" BUILD_TLS) include(ExternalProject) ExternalProject_Add(gen_testcase SOURCE_DIR ${openHiTLS_SRC} PREFIX "" BINARY_DIR ${openHiTLS_SRC}/testcode/framework/gen_test/build/ INSTALL_DIR "" UPDATE_COMMAND "" CONFIGURE_COMMAND cmake -DCMAKE_C_FLAGS=${CMAKE_C_FLAGS} -DPRINT_TO_TERMINAL=${ENABLE_PRINT} .. BUILD_COMMAND make INSTALL_COMMAND "" BUILD_ALWAYS FALSE LOG_BUILD TRUE LOG_DOWNLOAD TRUE EXCLUDE_FROM_ALL TRUE LOG_OUTPUT_ON_FAILURE TRUE ) add_subdirectory(${openHiTLS_SRC}/testcode/sdv) if(ENABLE_TLS AND ${BUILD_TLS} GREATER -1) add_subdirectory(${openHiTLS_SRC}/testcode/framework/tls) add_subdirectory(${openHiTLS_SRC}/testcode/framework/process) add_dependencies(gen_testcase process) endif()
2401_83913325/openHiTLS-examples_2461
testcode/CMakeLists.txt
CMake
unknown
3,043
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_md.h" #include "benchmark.h" static int32_t X25519SetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { (void)paraId; CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(ops->algId); if (pkeyCtx == NULL) { printf("Failed to create pkey context\n"); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = CRYPT_EAL_PkeyGen(pkeyCtx); if (ret != CRYPT_SUCCESS) { printf("Failed to gen curve25519 key.\n"); return ret; } *ctx = pkeyCtx; return CRYPT_SUCCESS; } static void X25519TearDown(void *ctx) { CRYPT_EAL_PkeyFreeCtx(ctx); } static int32_t X25519KeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; BENCH_TIMES(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "X25519 keyGen"); return rc; } static int32_t Ed25519SetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { return X25519SetUp(ctx, bench, ops, paraId); } static void Ed25519TearDown(void *ctx) { X25519TearDown(ctx); } static int32_t Ed25519KeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; BENCH_TIMES(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "Ed25519 keyGen"); return rc; } static int32_t X25519KeyDerive(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; CRYPT_EAL_PkeyCtx *peerCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_X25519); if (peerCtx == NULL) { printf("Failed to create peer context\n"); return CRYPT_MEM_ALLOC_FAIL; } rc = CRYPT_EAL_PkeyGen(peerCtx); if (rc != CRYPT_SUCCESS) { printf("Failed to gen peer key.\n"); CRYPT_EAL_PkeyFreeCtx(peerCtx); return rc; } uint8_t sharedKey[32]; uint32_t sharedKeyLen = sizeof(sharedKey); BENCH_TIMES(CRYPT_EAL_PkeyComputeShareKey(ctx, peerCtx, sharedKey, &sharedKeyLen), rc, CRYPT_SUCCESS, -1, opts->times, "X25519 keyDerive"); CRYPT_EAL_PkeyFreeCtx(peerCtx); return rc; } static int32_t GetHashId(BenchCtx *bench, BenchOptions *opts) { int32_t hashId = bench->ctxOps->hashId; if (opts->hashId != -1) { if (opts->hashId != CRYPT_MD_SHA512) { printf("Wrong Hash Algorithm Id for Ed25519. Must be SHA512."); return -1; } hashId = opts->hashId; } return hashId; } static int32_t Ed25519SignInner(void *ctx, int32_t hashId) { uint8_t plainText[32]; uint8_t signature[64]; uint32_t signatureLen = sizeof(signature); return CRYPT_EAL_PkeySign(ctx, hashId, plainText, sizeof(plainText), signature, &signatureLen); } static int32_t Ed25519Sign(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } BENCH_TIMES(Ed25519SignInner(ctx, hashId), rc, CRYPT_SUCCESS, -1, opts->times, "ed25519 sign"); return rc; } static int32_t Ed25519Verify(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } uint8_t plainText[32]; uint8_t signature[64]; uint32_t signatureLen = sizeof(signature); rc = CRYPT_EAL_PkeySign(ctx, hashId, plainText, sizeof(plainText), signature, &signatureLen); if (rc != CRYPT_SUCCESS) { printf("Failed to sign\n"); return rc; } BENCH_TIMES(CRYPT_EAL_PkeyVerify(ctx, hashId, plainText, sizeof(plainText), signature, signatureLen), rc, CRYPT_SUCCESS, -1, opts->times, "ed25519 verify"); return rc; } DEFINE_OPS_KX(X25519, CRYPT_PKEY_X25519); DEFINE_BENCH_CTX_FIXLEN(X25519); DEFINE_OPS_SIGN(Ed25519, CRYPT_PKEY_ED25519, CRYPT_MD_SHA512); DEFINE_BENCH_CTX_FIXLEN(Ed25519);
2401_83913325/openHiTLS-examples_2461
testcode/benchmark/25519_bench.c
C
unknown
4,462
# This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. cmake_minimum_required(VERSION 3.16 FATAL_ERROR) PROJECT(openHiTLS_BENCHMARK) set(OPENHITLS_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../..) set(BENCHS sm2_bench.c slh_dsa_bench.c ecdsa_bench.c md_bench.c cipher_bench.c mac_bench.c dh_bench.c ecdh_bench.c 25519_bench.c mldsa_bench.c mlkem_bench.c) add_compile_options(-g) add_link_options(-z noexecstack) add_executable(openhitls_benchmark benchmark.c ${BENCHS}) # target_link_options(openhitls_benchmark PRIVATE -fsanitize=address) target_link_directories(openhitls_benchmark PRIVATE ${OPENHITLS_ROOT}/build ${OPENHITLS_ROOT}/platform/Secure_C/lib) target_include_directories(openhitls_benchmark PRIVATE ${OPENHITLS_ROOT}/include/crypto ${OPENHITLS_ROOT}/include/bsl ${OPENHITLS_ROOT}/platform/Secure_C/include) target_link_libraries(openhitls_benchmark PRIVATE hitls_crypto hitls_bsl boundscheck)
2401_83913325/openHiTLS-examples_2461
testcode/benchmark/CMakeLists.txt
CMake
unknown
1,542
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <string.h> #include "crypt_errno.h" #include "crypt_algid.h" #include "crypt_eal_rand.h" #include "benchmark.h" extern BenchCtx Sm2BenchCtx; extern BenchCtx SlhDsaBenchCtx; extern BenchCtx EcdsaBenchCtx; extern BenchCtx MdBenchCtx; extern BenchCtx CipherBenchCtx; extern BenchCtx MacBenchCtx; extern BenchCtx DhBenchCtx; extern BenchCtx EcdhBenchCtx; extern BenchCtx RsaBenchCtx; extern BenchCtx X25519BenchCtx; extern BenchCtx Ed25519BenchCtx; extern BenchCtx MldsaBenchCtx; extern BenchCtx MlkemBenchCtx; BenchCtx *g_benchs[] = { &Sm2BenchCtx, &SlhDsaBenchCtx, &EcdsaBenchCtx, &MdBenchCtx, &CipherBenchCtx, &MacBenchCtx, &DhBenchCtx, &EcdhBenchCtx, &X25519BenchCtx, &Ed25519BenchCtx, &MldsaBenchCtx, &MlkemBenchCtx, }; typedef struct { const char *s; int32_t id; } StrIdMap; static StrIdMap g_strIdMap[] = { {"md5", CRYPT_MD_MD5}, {"sha1", CRYPT_MD_SHA1}, {"sha224", CRYPT_MD_SHA224}, {"sha256", CRYPT_MD_SHA256}, {"sha384", CRYPT_MD_SHA384}, {"sha512", CRYPT_MD_SHA512}, {"sha3-224", CRYPT_MD_SHA3_224}, {"sha3-256", CRYPT_MD_SHA3_256}, {"sha3-384", CRYPT_MD_SHA3_384}, {"sha3-512", CRYPT_MD_SHA3_512}, {"shake128", CRYPT_MD_SHAKE128}, {"shake256", CRYPT_MD_SHAKE256}, {"sm3", CRYPT_MD_SM3}, {"SLH-DSA-SHA2-128S", CRYPT_SLH_DSA_SHA2_128S}, {"SLH-DSA-SHAKE-128S", CRYPT_SLH_DSA_SHAKE_128S}, {"SLH-DSA-SHA2-128F", CRYPT_SLH_DSA_SHA2_128F}, {"SLH-DSA-SHAKE-128F", CRYPT_SLH_DSA_SHAKE_128F}, {"SLH-DSA-SHA2-192S", CRYPT_SLH_DSA_SHA2_192S}, {"SLH-DSA-SHAKE-192S", CRYPT_SLH_DSA_SHAKE_192S}, {"SLH-DSA-SHA2-192F", CRYPT_SLH_DSA_SHA2_192F}, {"SLH-DSA-SHAKE-192F", CRYPT_SLH_DSA_SHAKE_192F}, {"SLH-DSA-SHA2-256S", CRYPT_SLH_DSA_SHA2_256S}, {"SLH-DSA-SHAKE-256S", CRYPT_SLH_DSA_SHAKE_256S}, {"SLH-DSA-SHA2-256F", CRYPT_SLH_DSA_SHA2_256F}, {"SLH-DSA-SHAKE-256F", CRYPT_SLH_DSA_SHAKE_256F}, {"nistp224", CRYPT_ECC_NISTP224}, {"nistp256", CRYPT_ECC_NISTP256}, {"nistp384", CRYPT_ECC_NISTP384}, {"nistp521", CRYPT_ECC_NISTP521}, {"brainpoolP256r1", CRYPT_ECC_BRAINPOOLP256R1}, {"brainpoolP384r1", CRYPT_ECC_BRAINPOOLP384R1}, {"brainpoolP512r1", CRYPT_ECC_BRAINPOOLP512R1}, {"aes128-cbc", CRYPT_CIPHER_AES128_CBC}, {"aes128-ctr", CRYPT_CIPHER_AES128_CTR}, {"aes128-ecb", CRYPT_CIPHER_AES128_ECB}, {"aes128-xts", CRYPT_CIPHER_AES128_XTS}, {"aes128-ccm", CRYPT_CIPHER_AES128_CCM}, {"aes128-gcm", CRYPT_CIPHER_AES128_GCM}, {"aes128-cfb", CRYPT_CIPHER_AES128_CFB}, {"aes128-ofb", CRYPT_CIPHER_AES128_OFB}, {"aes192-cbc", CRYPT_CIPHER_AES192_CBC}, {"aes192-ctr", CRYPT_CIPHER_AES192_CTR}, {"aes192-ecb", CRYPT_CIPHER_AES192_ECB}, {"aes192-ccm", CRYPT_CIPHER_AES192_CCM}, {"aes192-gcm", CRYPT_CIPHER_AES192_GCM}, {"aes192-cfb", CRYPT_CIPHER_AES192_CFB}, {"aes192-ofb", CRYPT_CIPHER_AES192_OFB}, {"aes256-cbc", CRYPT_CIPHER_AES256_CBC}, {"aes256-ctr", CRYPT_CIPHER_AES256_CTR}, {"aes256-ecb", CRYPT_CIPHER_AES256_ECB}, {"aes256-xts", CRYPT_CIPHER_AES256_XTS}, {"aes256-ccm", CRYPT_CIPHER_AES256_CCM}, {"aes256-gcm", CRYPT_CIPHER_AES256_GCM}, {"aes256-cfb", CRYPT_CIPHER_AES256_CFB}, {"aes256-ofb", CRYPT_CIPHER_AES256_OFB}, {"sm4-cbc", CRYPT_CIPHER_SM4_CBC}, {"sm4-ecb", CRYPT_CIPHER_SM4_ECB}, {"sm4-ctr", CRYPT_CIPHER_SM4_CTR}, {"sm4-gcm", CRYPT_CIPHER_SM4_GCM}, {"sm4-cfb", CRYPT_CIPHER_SM4_CFB}, {"sm4-ofb", CRYPT_CIPHER_SM4_OFB}, {"sm4-xts", CRYPT_CIPHER_SM4_XTS}, {"chacha20-poly1305", CRYPT_CIPHER_CHACHA20_POLY1305}, {"hmac-md5", CRYPT_MAC_HMAC_MD5}, {"hmac-sha1", CRYPT_MAC_HMAC_SHA1}, {"hmac-sha224", CRYPT_MAC_HMAC_SHA224}, {"hmac-sha256", CRYPT_MAC_HMAC_SHA256}, {"hmac-sha384", CRYPT_MAC_HMAC_SHA384}, {"hmac-sha512", CRYPT_MAC_HMAC_SHA512}, {"hmac-sha3-224", CRYPT_MAC_HMAC_SHA3_224}, {"hmac-sha3-256", CRYPT_MAC_HMAC_SHA3_256}, {"hmac-sha3-384", CRYPT_MAC_HMAC_SHA3_384}, {"hmac-sha3-512", CRYPT_MAC_HMAC_SHA3_512}, {"hmac-sha3-224", CRYPT_MAC_HMAC_SHA3_224}, {"hmac-sha3-256", CRYPT_MAC_HMAC_SHA3_256}, {"hmac-sm3", CRYPT_MAC_HMAC_SM3}, {"cmac-aes128", CRYPT_MAC_CMAC_AES128}, {"cmac-aes192", CRYPT_MAC_CMAC_AES192}, {"cmac-aes256", CRYPT_MAC_CMAC_AES256}, {"cmac-sm4", CRYPT_MAC_CMAC_SM4}, {"cbc-mac-sm4", CRYPT_MAC_CBC_MAC_SM4}, {"gmac-aes128", CRYPT_MAC_GMAC_AES128}, {"gmac-aes192", CRYPT_MAC_GMAC_AES192}, {"gmac-aes256", CRYPT_MAC_GMAC_AES256}, {"siphash64", CRYPT_MAC_SIPHASH64}, {"siphash128", CRYPT_MAC_SIPHASH128}, {"dh-rfc2409-768", CRYPT_DH_RFC2409_768}, {"dh-rfc2409-1024", CRYPT_DH_RFC2409_1024}, {"dh-rfc3526-1536", CRYPT_DH_RFC3526_1536}, {"dh-rfc3526-2048", CRYPT_DH_RFC3526_2048}, {"dh-rfc3526-3072", CRYPT_DH_RFC3526_3072}, {"dh-rfc3526-4096", CRYPT_DH_RFC3526_4096}, {"dh-rfc3526-6144", CRYPT_DH_RFC3526_6144}, {"dh-rfc3526-8192", CRYPT_DH_RFC3526_8192}, {"dh-rfc7919-2048", CRYPT_DH_RFC7919_2048}, {"dh-rfc7919-3072", CRYPT_DH_RFC7919_3072}, {"dh-rfc7919-4096", CRYPT_DH_RFC7919_4096}, {"dh-rfc7919-6144", CRYPT_DH_RFC7919_6144}, {"dh-rfc7919-8192", CRYPT_DH_RFC7919_8192}, }; static int32_t AlgStr2Id(char *str) { for (int i = 0; i < SIZEOF(g_strIdMap); i++) { if (strncasecmp(g_strIdMap[i].s, str, strlen(g_strIdMap[i].s)) == 0) { return g_strIdMap[i].id; } } return -1; } const char *GetAlgName(int32_t algId) { for (int i = 0; i < SIZEOF(g_strIdMap); i++) { if (g_strIdMap[i].id == algId) { return g_strIdMap[i].s; } } return ""; } static void PrintUsage(void) { printf("Usage: openhitls_benchmark [options]\n"); printf("Options:\n"); printf(" -a <algorithm> Specify algorithm to benchmark (e.g., sm2*, sm2-KeyGen, *KeyGen)\n"); printf(" -t <times> Number of times to run each benchmark\n"); printf(" -s <seconds> Number of seconds to run each benchmark\n"); printf(" -l <len> Length of the payload to benchmark\n"); printf(" -d <digest id> Digest algorithm id before sign\n"); printf(" -p <para id> Parameter id to benchmark\n"); printf(" -h Show this help message\n"); } static void ParseOptions(int argc, char **argv, BenchOptions *opts) { int c; while ((c = getopt(argc, argv, "a:t:s:l:d:p:h")) != -1) { switch (c) { case 'a': opts->algorithm = optarg; break; case 't': opts->times = (uint32_t)atoi(optarg); break; case 's': opts->seconds = (uint32_t)atoi(optarg); break; case 'l': opts->len = (uint32_t)atoi(optarg); break; case 'd': opts->hashId = AlgStr2Id(optarg); break; case 'p': opts->paraId = AlgStr2Id(optarg); break; case 'h': PrintUsage(); exit(0); default: PrintUsage(); exit(1); } } } bool MatchAlgorithm(const char *pattern, const char *name) { if (pattern == NULL) { return true; } // it's operation benchmark if (strncmp(pattern, "*-", 2) == 0) { return true; } size_t patternLen = strlen(pattern); size_t nameLen = strlen(name); const char *asterisk = strchr(pattern, '*'); if (asterisk != NULL) { // Process prefix wildcard "*XXX" if (pattern[0] == '*') { // Check if pattern is "*XXX" return (nameLen >= patternLen - 1) && (strcasecmp(name + nameLen - (patternLen - 1), pattern + 1) == 0); } // Process suffix wildcard "XXX*" if (pattern[patternLen - 1] == '*') { return strncasecmp(name, pattern, patternLen - 1) == 0; } return false; } return strncasecmp(pattern, name, strlen(name)) == 0; } static uint32_t MatchOperation(const char *pattern, BenchCtx *bench) { uint32_t re = 0; for (uint32_t i = 0; i < bench->opsNum; i++) { const Operation *op = &bench->ctxOps->ops[i]; const char *hyphen = strchr(pattern, '-'); if (hyphen != NULL) { size_t algoLen = strlen(bench->name); const char *operation = hyphen + 1; // Match algorithm part before hyphen if (strncasecmp(operation, op->name + algoLen, strlen(operation)) == 0) { re |= op->id; } } else { // not match a operation, config default supported operation re |= op->id; } } return re; } static int32_t InstantOperation(const Operation *op, void *ctx, BenchCtx *bench, BenchOptions *opts) { if (op->id & KEY_GEN_ID) { return ((KeyGen)op->oper)(ctx, bench, opts); } if (op->id & KEY_DERIVE_ID) { return ((KeyDerive)op->oper)(ctx, bench, opts); } if (op->id & ENC_ID) { return ((Enc)op->oper)(ctx, bench, opts); } if (op->id & DEC_ID) { return ((Dec)op->oper)(ctx, bench, opts); } if (op->id & SIGN_ID) { return ((Sign)op->oper)(ctx, bench, opts); } if (op->id & VERIFY_ID) { return ((Verify)op->oper)(ctx, bench, opts); } if (op->id & ONESHOT_ID) { return ((OneShot)op->oper)(ctx, bench, opts); } if (op->id & ENCAPS_ID) { return ((Encaps)op->oper)(ctx, bench, opts); } if (op->id & DECAPS_ID) { return ((Decaps)op->oper)(ctx, bench, opts); } return CRYPT_NOT_SUPPORT; } static void ResetOptions(BenchOptions *opts, BenchCtx *benchCtx) { if (opts->seconds == 0) { opts->seconds = benchCtx->seconds; } if (opts->times == 0) { opts->times = benchCtx->times; } } static void DoBenchTest(BenchCtx *benchs, const CtxOps *ctxOps, const Operation *op, BenchOptions *algOpts) { void *ctx = NULL; BENCH_SETUP(ctx, benchs, ctxOps, algOpts->paraId); if (op->id & KEY_GEN_ID || op->id & KEY_DERIVE_ID) { // keygen and keyderive just do one fixed len. int32_t ret = InstantOperation(op, ctx, benchs, algOpts); if (ret != CRYPT_SUCCESS) { printf("Failed to %s, ret = %08x\n", op->name, ret); } } else { bool is_match = false; for (int i = 0; i < benchs->lensNum; i++) { if (algOpts->len != -1 && algOpts->len != benchs->lens[i]) { continue; } BENCH_SETUP(ctx, benchs, ctxOps, algOpts->paraId); BenchOptions tmpOpts = *algOpts; tmpOpts.len = benchs->lens[i]; int32_t ret = InstantOperation(op, ctx, benchs, &tmpOpts); if (ret != CRYPT_SUCCESS) { printf("Failed to %s, ret = %08x\n", op->name, ret); } is_match = true; } if (algOpts->len != -1 && !is_match) { int32_t ret = InstantOperation(op, ctx, benchs, algOpts); if (ret != CRYPT_SUCCESS) { printf("Failed to %s, ret = %08x\n", op->name, ret); } } } BENCH_TEARDOWN(ctx, ctxOps); } int main(int argc, char **argv) { int32_t ret; BenchOptions opts = {0}; // default options opts.algorithm = "*"; // all algorithms opts.filteredOps = 0x3F; // all operations opts.paraId = -1; // fake hash id opts.hashId = -1; // fake hash id opts.len = -1; // fake len ParseOptions(argc, argv, &opts); ret = CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_SHA256, "provider=default", NULL, 0, NULL); if (ret != CRYPT_SUCCESS) { printf("Failed to initialize random number generator\n"); return -1; } printf("%-35s, %10s, %15s, %15s, %20s\n", "algorithm operation", "len", "run times", "time elapsed(ms)", "ops/s"); for (int i = 0; i < SIZEOF(g_benchs); i++) { const CtxOps *ctxOps = g_benchs[i]->ctxOps; BenchOptions algOpts = opts; ResetOptions(&algOpts, g_benchs[i]); // filtering benchmark test if (!MatchAlgorithm(opts.algorithm, g_benchs[i]->name)) { continue; } opts.filteredOps = MatchOperation(opts.algorithm, g_benchs[i]); for (int j = 0; j < g_benchs[i]->opsNum; j++) { const Operation *op = &ctxOps->ops[j]; if ((uint32_t)(op->id & opts.filteredOps) == 0U) { continue; } BenchOptions tmpOpts = algOpts; if (tmpOpts.paraId != -1 || g_benchs[i]->paraIdsNum == 0) { DoBenchTest(g_benchs[i], ctxOps, op, &tmpOpts); } else { for (int k = 0; k < g_benchs[i]->paraIdsNum; k++) { tmpOpts.paraId = g_benchs[i]->paraIds[k]; DoBenchTest(g_benchs[i], ctxOps, op, &tmpOpts); } } } } return 0; }
2401_83913325/openHiTLS-examples_2461
testcode/benchmark/benchmark.c
C
unknown
13,679
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef BENCHMARK_H #define BENCHMARK_H #include <stdint.h> #include <string.h> #include <stdio.h> #include <time.h> #include <sys/time.h> #define BENCH_TIMES(func, rc, ok, len, times, header) \ { \ struct timespec start, end; \ clock_gettime(CLOCK_REALTIME, &start); \ for (int i = 0; i < times; i++) { \ rc = func; \ if (rc != ok) { \ printf("Error: %s, ret = %08x\n", #func, rc); \ break; \ } \ } \ clock_gettime(CLOCK_REALTIME, &end); \ uint64_t elapsedTime = (end.tv_sec - start.tv_sec) * 1000000000 + (end.tv_nsec - start.tv_nsec); \ printf("%-35s, %10d, %15d, %16.2f, %20.2f\n", header, len, times, (double)elapsedTime / 1000000, \ ((double)times * 1000000000) / elapsedTime); \ } #define BENCH_TIMES_VA(func, rc, ok, len, times, headerFmt, ...) \ { \ char header[256] = {0}; \ snprintf(header, sizeof(header), headerFmt, ##__VA_ARGS__); \ BENCH_TIMES(func, rc, ok, len, times, header); \ } #define BENCH_SECONDS(func, rc, ok, len, secs, header) \ { \ struct timespec start, end; \ uint64_t totalTime = secs * 1000000000; \ uint64_t elapsedTime = 0; \ uint64_t cnt = 0; \ while (elapsedTime < totalTime) { \ clock_gettime(CLOCK_REALTIME, &start); \ rc = func; \ if (rc != ok) { \ printf("Error: %s, ret = %08x\n", #func, rc); \ break; \ } \ clock_gettime(CLOCK_REALTIME, &end); \ elapsedTime += (end.tv_sec - start.tv_sec) * 1000000000 + (end.tv_nsec - start.tv_nsec); \ cnt++; \ } \ printf("%-35s, %10d, %15d, %16.2f, %20.2f\n", header, len, cnt, elapsedTime / 1000000, \ ((double)times * 1000000000) / elapsedTime); \ } #define BENCH_SETUP(ctx, bench, ops, id) \ do { \ int32_t ret; \ ret = ops->setUp(&ctx, bench, ops, id); \ if (ret != CRYPT_SUCCESS) { \ printf("Failed to setup benchmark testcase: %08x\n", ret); \ return; \ } \ } while (0) #define BENCH_TEARDOWN(ctx, ops) \ do { \ ops->tearDown(ctx); \ } while (0) // sizeof array #define SIZEOF(a) (sizeof(a) / sizeof(a[0])) static inline void Hex2Bin(const char *hex, uint8_t *bin, uint32_t *len) { *len = strlen(hex) / 2; for (uint32_t i = 0; i < *len; i++) { sscanf(hex + i * 2, "%2hhx", &bin[i]); } } // 定义命令行选项结构 typedef struct { char *algorithm; // -a 选项指定的算法 uint32_t filteredOps; uint32_t times; // -t 选项指定的运行次数 uint32_t seconds; // -s 选项指定的运行时间 uint32_t len; int32_t paraId; int32_t hashId; } BenchOptions; typedef struct BenchCtx_ BenchCtx; typedef struct CtxOps_ CtxOps; // every benchmark testcase should define "NewCtx" and "FreeCtx" typedef int32_t (*SetUp)(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t id); typedef void (*TearDown)(void *ctx); typedef int32_t (*KeyGen)(void *ctx, BenchCtx *bench, BenchOptions *opts); typedef int32_t (*KeyDerive)(void *ctx, BenchCtx *bench, BenchOptions *opts); typedef int32_t (*Enc)(void *ctx, BenchCtx *bench, BenchOptions *opts); typedef int32_t (*Dec)(void *ctx, BenchCtx *bench, BenchOptions *opts); typedef int32_t (*Sign)(void *ctx, BenchCtx *bench, BenchOptions *opts); typedef int32_t (*Verify)(void *ctx, BenchCtx *bench, BenchOptions *opts); typedef int32_t (*OneShot)(void *ctx, BenchCtx *bench, BenchOptions *opts); typedef int32_t (*Encaps)(void *ctx, BenchCtx *bench, BenchOptions *opts); typedef int32_t (*Decaps)(void *ctx, BenchCtx *bench, BenchOptions *opts); // return true if not be filetered; else return false. typedef bool (*ParaFilterCb)(BenchOptions *opts, int32_t paraId); typedef struct { uint32_t id; const char *name; void *oper; } Operation; struct CtxOps_ { int32_t algId; int32_t hashId; SetUp setUp; TearDown tearDown; Operation ops[]; }; #define KEY_GEN_ID 1U #define KEY_DERIVE_ID 2U #define ENC_ID 4U #define DEC_ID 8U #define SIGN_ID 16U #define VERIFY_ID 32U #define ONESHOT_ID 64U #define ENCAPS_ID 128U #define DECAPS_ID 256U static int32_t g_lens[] = {16, 64, 256, 1024, 8192, 16384}; static uint8_t g_plain[16384]; static uint8_t g_out[16384]; static uint8_t g_key[32] = {1}; static uint8_t g_iv[16]; #define DEFINE_OPER(id, oper) {id, #oper, oper} #define DEFINE_OPS(alg, id, hId) \ static const CtxOps alg##CtxOps = { \ .algId = id, \ .hashId = hId, \ .setUp = alg##SetUp, \ .tearDown = alg##TearDown, \ .ops = \ { \ DEFINE_OPER(KEY_GEN_ID, alg##KeyGen), \ DEFINE_OPER(KEY_DERIVE_ID, alg##KeyDerive), \ DEFINE_OPER(ENC_ID, alg##Enc), \ DEFINE_OPER(DEC_ID, alg##Dec), \ DEFINE_OPER(SIGN_ID, alg##Sign), \ DEFINE_OPER(VERIFY_ID, alg##Verify), \ }, \ } #define DEFINE_OPS_SIGN(alg, id, hId) \ static const CtxOps alg##CtxOps = { \ .algId = id, \ .hashId = hId, \ .setUp = alg##SetUp, \ .tearDown = alg##TearDown, \ .ops = \ { \ DEFINE_OPER(KEY_GEN_ID, alg##KeyGen), \ DEFINE_OPER(SIGN_ID, alg##Sign), \ DEFINE_OPER(VERIFY_ID, alg##Verify), \ }, \ } #define DEFINE_OPS_CIPHER(alg, id) \ static const CtxOps alg##CtxOps = { \ .algId = id, \ .hashId = id, \ .setUp = alg##SetUp, \ .tearDown = alg##TearDown, \ .ops = \ { \ DEFINE_OPER(ENC_ID, alg##Enc), \ DEFINE_OPER(DEC_ID, alg##Dec), \ }, \ } #define DEFINE_OPS_MD(alg) \ static const CtxOps alg##CtxOps = { \ .algId = CRYPT_MD_MAX, \ .hashId = CRYPT_MD_MAX, \ .setUp = alg##SetUp, \ .tearDown = alg##TearDown, \ .ops = \ { \ DEFINE_OPER(ONESHOT_ID, alg##OneShot), \ }, \ } #define DEFINE_OPS_KX(alg, id) \ static const CtxOps alg##CtxOps = { \ .algId = id, \ .hashId = CRYPT_MD_MAX, \ .setUp = alg##SetUp, \ .tearDown = alg##TearDown, \ .ops = \ { \ DEFINE_OPER(KEY_GEN_ID, alg##KeyGen), \ DEFINE_OPER(KEY_DERIVE_ID, alg##KeyDerive), \ }, \ } #define DEFINE_OPS_KEM(alg, id) \ static const CtxOps alg##CtxOps = { \ .algId = id, \ .hashId = CRYPT_MD_MAX, \ .setUp = alg##SetUp, \ .tearDown = alg##TearDown, \ .ops = \ { \ DEFINE_OPER(KEY_GEN_ID, alg##KeyGen), \ DEFINE_OPER(ENCAPS_ID, alg##Encaps), \ DEFINE_OPER(DECAPS_ID, alg##Decaps), \ }, \ } typedef struct BenchCtx_ { const char *name; const char *desc; const CtxOps *ctxOps; int32_t opsNum; int32_t *paraIds; uint32_t paraIdsNum; int32_t *lens; uint32_t lensNum; int32_t times; int32_t seconds; } BenchCtx; #define DEFINE_BENCH_CTX_PARA_TIMES_LEN(alg, pId, pIdNum, ts, l, ln) \ BenchCtx alg##BenchCtx = { \ .name = #alg, \ .desc = #alg " benchmark", \ .ctxOps = &alg##CtxOps, \ .opsNum = SIZEOF(alg##CtxOps.ops), \ .paraIds = pId, \ .paraIdsNum = pIdNum, \ .lens = l, \ .lensNum = ln, \ .times = ts, \ .seconds = 0, \ } #define DEFINE_BENCH_CTX_PARA_TIMES(alg, pId, pIdNum, ts) \ DEFINE_BENCH_CTX_PARA_TIMES_LEN(alg, pId, pIdNum, ts, g_lens, SIZEOF(g_lens)) #define DEFINE_BENCH_CTX_PARA_TIMES_FIXLEN(alg, pId, pIdNum, ts) \ DEFINE_BENCH_CTX_PARA_TIMES_LEN(alg, pId, pIdNum, ts, g_lens, 1) // default to run 10000 times #define DEFINE_BENCH_CTX_PARA(alg, pId, pIdNum) DEFINE_BENCH_CTX_PARA_TIMES(alg, pId, pIdNum, 10000) #define DEFINE_BENCH_CTX_PARA_FIXLEN(alg, pId, pIdNum) DEFINE_BENCH_CTX_PARA_TIMES_FIXLEN(alg, pId, pIdNum, 10000) #define DEFINE_BENCH_CTX(alg) DEFINE_BENCH_CTX_PARA(alg, NULL, 0) #define DEFINE_BENCH_CTX_FIXLEN(alg) DEFINE_BENCH_CTX_PARA_FIXLEN(alg, NULL, 0) bool MatchAlgorithm(const char *pattern, const char *name); const char *GetAlgName(int32_t hashId); #endif /* BENCHMARK_H */
2401_83913325/openHiTLS-examples_2461
testcode/benchmark/benchmark.h
C
unknown
13,697
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_cipher.h" #include "benchmark.h" static int32_t CipherSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { *ctx = CRYPT_EAL_CipherNewCtx(paraId); if (*ctx == NULL) { printf("Failed to new cipher ctx\n"); return CRYPT_ERR_ALGID; } return CRYPT_SUCCESS; } static void CipherTearDown(void *ctx) { if (ctx != NULL) { CRYPT_EAL_CipherFreeCtx(ctx); } } static int32_t DoCipherEnc(void *ctx, BenchOptions *opts) { uint8_t out[16384]; // Maximum output size uint32_t outLen = sizeof(out); return CRYPT_EAL_CipherUpdate(ctx, g_plain, opts->len, out, &outLen); } static CRYPT_EAL_CipherCtx *InitCipherCtx(int32_t paraId, uint32_t keyLen, uint32_t ivLen, bool isEnc) { int rc; CRYPT_EAL_CipherCtx *cipher = CRYPT_EAL_CipherNewCtx(paraId); if (cipher == NULL) { return NULL; } // the iv len of ccm is in [7, 13] rc = CRYPT_EAL_CipherInit(cipher, g_key, keyLen, g_iv, ivLen, isEnc); if (rc != CRYPT_SUCCESS) { printf("init ccm cipher failed\n"); return NULL; } return cipher; } static int32_t DoCcmEnc(void *ctx, BenchOptions *opts, uint32_t keyLen, uint32_t ivLen) { // aead do a complete init->ctrl->update->final process. (void)ctx; int rc; int32_t paraId = opts->paraId; uint32_t aad[32] = {1, 2, 3}; uint64_t msgLen = opts->len; uint32_t outLen = sizeof(g_out); uint8_t tag[16]; uint32_t tagLen = sizeof(tag); CRYPT_EAL_CipherCtx *cipher = InitCipherCtx(paraId, keyLen, ivLen, true); if (cipher == NULL) { return CRYPT_ERR_ALGID; } if ((rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen))) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_SET_MSGLEN, &msgLen, sizeof(msgLen))) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_SET_AAD, aad, sizeof(aad))) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherUpdate(cipher, g_plain, opts->len, g_out, &outLen)) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_GET_TAG, tag, tagLen)) != CRYPT_SUCCESS) { printf("do ccm enc failed\n"); goto ERR; } ERR: CRYPT_EAL_CipherFreeCtx(cipher); return rc; } static int32_t DoCcmDec(void *ctx, BenchOptions *opts, uint32_t keyLen, uint32_t ivLen) { // aead do a complete init->ctrl->update->final process. (void)ctx; int rc; int32_t paraId = opts->paraId; uint32_t aad[32] = {1, 2, 3}; uint64_t msgLen = opts->len; uint32_t outLen = sizeof(g_out); CRYPT_EAL_CipherCtx *cipher = InitCipherCtx(paraId, keyLen, ivLen, false); if (cipher == NULL) { return CRYPT_ERR_ALGID; } if ((rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_SET_MSGLEN, &msgLen, sizeof(msgLen))) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_SET_AAD, aad, sizeof(aad))) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherUpdate(cipher, g_plain, opts->len, g_out, &outLen)) != CRYPT_SUCCESS) { printf("do ccm dec failed\n"); goto ERR; } ERR: CRYPT_EAL_CipherFreeCtx(cipher); return rc; } static int32_t DoGcmEnc(void *ctx, BenchOptions *opts, uint32_t keyLen, uint32_t ivLen) { // aead do a complete init->ctrl->update->final process. (void)ctx; int rc; int32_t paraId = opts->paraId; uint32_t aad[32] = {1, 2, 3}; uint8_t tag[16]; uint32_t tagLen = sizeof(tag); uint32_t outLen = sizeof(g_out); CRYPT_EAL_CipherCtx *cipher = InitCipherCtx(paraId, keyLen, ivLen, true); if (cipher == NULL) { return CRYPT_ERR_ALGID; } if ((rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_SET_TAGLEN, &tagLen, sizeof(tagLen))) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_SET_AAD, aad, sizeof(aad))) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherUpdate(cipher, g_plain, opts->len, g_out, &outLen)) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_GET_TAG, tag, sizeof(tag))) != CRYPT_SUCCESS) { printf("do gcm enc failed\n"); goto ERR; } ERR: CRYPT_EAL_CipherFreeCtx(cipher); return rc; } static int32_t DoGcmDec(void *ctx, BenchOptions *opts, uint32_t keyLen, uint32_t ivLen) { // aead do a complete init->ctrl->update->final process. (void)ctx; int rc; int32_t paraId = opts->paraId; uint32_t aad[32] = {1, 2, 3}; uint8_t tag[16]; uint32_t tagLen = sizeof(tag); uint32_t outLen = sizeof(g_out); CRYPT_EAL_CipherCtx *cipher = InitCipherCtx(paraId, keyLen, ivLen, false); if (cipher == NULL) { return CRYPT_ERR_ALGID; } if ((rc = CRYPT_EAL_CipherCtrl(cipher, CRYPT_CTRL_SET_AAD, aad, sizeof(aad))) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherUpdate(cipher, g_plain, opts->len, g_out, &outLen)) != CRYPT_SUCCESS) { printf("do gcm enc failed\n"); goto ERR; } ERR: CRYPT_EAL_CipherFreeCtx(cipher); return rc; } static int32_t CipherEnc(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t paraId = opts->paraId; const char *cipherName = GetAlgName(paraId); uint32_t keyLen = 16; uint32_t ivLen = 16; if ((rc = CRYPT_EAL_CipherGetInfo(paraId, CRYPT_INFO_KEY_LEN, &keyLen)) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherGetInfo(paraId, CRYPT_INFO_IV_LEN, &ivLen)) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherInit(ctx, g_key, keyLen, g_iv, ivLen, true)) != CRYPT_SUCCESS) { return rc; } // aead if (paraId == CRYPT_CIPHER_AES128_CCM || paraId == CRYPT_CIPHER_AES192_CCM || paraId == CRYPT_CIPHER_AES256_CCM) { BENCH_TIMES_VA(DoCcmEnc(ctx, opts, keyLen, ivLen), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s encrypt", cipherName); } else if (paraId == CRYPT_CIPHER_AES128_GCM || paraId == CRYPT_CIPHER_AES192_GCM || paraId == CRYPT_CIPHER_AES256_GCM || paraId == CRYPT_CIPHER_SM4_GCM) { BENCH_TIMES_VA(DoGcmEnc(ctx, opts, keyLen, ivLen), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s encrypt", cipherName); } else { BENCH_TIMES_VA(DoCipherEnc(ctx, opts), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s encrypt", cipherName); } return rc; } static int32_t CipherDec(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t paraId = opts->paraId; const char *cipherName = GetAlgName(paraId); uint32_t keyLen = 16; uint32_t ivLen = 16; if ((rc = CRYPT_EAL_CipherGetInfo(paraId, CRYPT_INFO_KEY_LEN, &keyLen)) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherGetInfo(paraId, CRYPT_INFO_IV_LEN, &ivLen)) != CRYPT_SUCCESS || (rc = CRYPT_EAL_CipherInit(ctx, g_key, keyLen, g_iv, ivLen, false)) != CRYPT_SUCCESS) { return rc; } // aead if (paraId == CRYPT_CIPHER_AES128_CCM || paraId == CRYPT_CIPHER_AES192_CCM || paraId == CRYPT_CIPHER_AES256_CCM) { BENCH_TIMES_VA(DoCcmDec(ctx, opts, keyLen, ivLen), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s decrypt", cipherName); } else if (paraId == CRYPT_CIPHER_AES128_GCM || paraId == CRYPT_CIPHER_AES192_GCM || paraId == CRYPT_CIPHER_AES256_GCM || paraId == CRYPT_CIPHER_SM4_GCM) { BENCH_TIMES_VA(DoGcmDec(ctx, opts, keyLen, ivLen), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s decrypt", cipherName); } else { BENCH_TIMES_VA(DoCipherEnc(ctx, opts), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s decrypt", cipherName); } return rc; } static int32_t g_paraIds[] = { // AES-128 modes CRYPT_CIPHER_AES128_CBC, CRYPT_CIPHER_AES128_CTR, CRYPT_CIPHER_AES128_ECB, CRYPT_CIPHER_AES128_XTS, CRYPT_CIPHER_AES128_CCM, CRYPT_CIPHER_AES128_GCM, CRYPT_CIPHER_AES128_CFB, CRYPT_CIPHER_AES128_OFB, // AES-192 modes CRYPT_CIPHER_AES192_CBC, CRYPT_CIPHER_AES192_CTR, CRYPT_CIPHER_AES192_ECB, CRYPT_CIPHER_AES192_CCM, CRYPT_CIPHER_AES192_GCM, CRYPT_CIPHER_AES192_CFB, CRYPT_CIPHER_AES192_OFB, // AES-256 modes CRYPT_CIPHER_AES256_CBC, CRYPT_CIPHER_AES256_CTR, CRYPT_CIPHER_AES256_ECB, CRYPT_CIPHER_AES256_XTS, CRYPT_CIPHER_AES256_CCM, CRYPT_CIPHER_AES256_GCM, CRYPT_CIPHER_AES256_CFB, CRYPT_CIPHER_AES256_OFB, // SM4 modes CRYPT_CIPHER_SM4_XTS, CRYPT_CIPHER_SM4_CBC, CRYPT_CIPHER_SM4_ECB, CRYPT_CIPHER_SM4_CTR, CRYPT_CIPHER_SM4_GCM, CRYPT_CIPHER_SM4_CFB, CRYPT_CIPHER_SM4_OFB, // ChaCha20-Poly1305 CRYPT_CIPHER_CHACHA20_POLY1305, }; DEFINE_OPS_CIPHER(Cipher, CRYPT_PKEY_MAX); DEFINE_BENCH_CTX_PARA(Cipher, g_paraIds, SIZEOF(g_paraIds));
2401_83913325/openHiTLS-examples_2461
testcode/benchmark/cipher_bench.c
C
unknown
9,405
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_md.h" #include "benchmark.h" static int32_t DhSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { int32_t ret; CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(ops->algId); if (pkeyCtx == NULL) { printf("Failed to create pkey context\n"); return CRYPT_MEM_ALLOC_FAIL; } ret = CRYPT_EAL_PkeySetParaById(pkeyCtx, paraId); if (ret != CRYPT_SUCCESS) { printf("Failed to set para: %d.\n", paraId); return ret; } ret = CRYPT_EAL_PkeyGen(pkeyCtx); if (ret != CRYPT_SUCCESS) { printf("Failed to gen dh key.\n"); return ret; } *ctx = pkeyCtx; return CRYPT_SUCCESS; } static void DhTearDown(void *ctx) { CRYPT_EAL_PkeyFreeCtx(ctx); } static int32_t DhKeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; int32_t paraId = opts->paraId; const char *group = GetAlgName(paraId); BENCH_TIMES_VA(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "%s dh keyGen", group); return rc; } static int32_t DhKeyDerive(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t paraId = opts->paraId; const char *group = GetAlgName(paraId); // Create a peer context for key exchange CRYPT_EAL_PkeyCtx *peerCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_DH); if (peerCtx == NULL) { printf("Failed to create peer context\n"); return CRYPT_MEM_ALLOC_FAIL; } rc = CRYPT_EAL_PkeySetParaById(peerCtx, paraId); if (rc != CRYPT_SUCCESS) { printf("Failed to set peer para: %d.\n", paraId); CRYPT_EAL_PkeyFreeCtx(peerCtx); return rc; } rc = CRYPT_EAL_PkeyGen(peerCtx); if (rc != CRYPT_SUCCESS) { printf("Failed to gen peer key.\n"); CRYPT_EAL_PkeyFreeCtx(peerCtx); return rc; } uint8_t sharedKey[4096]; // DH can have larger key sizes uint32_t sharedKeyLen = sizeof(sharedKey); BENCH_TIMES_VA(CRYPT_EAL_PkeyComputeShareKey(ctx, peerCtx, sharedKey, &sharedKeyLen), rc, CRYPT_SUCCESS, -1, opts->times, "%s dh keyDervie", group); CRYPT_EAL_PkeyFreeCtx(peerCtx); return rc; } static int32_t g_paraIds[] = { CRYPT_DH_RFC2409_768, CRYPT_DH_RFC2409_1024, CRYPT_DH_RFC3526_1536, CRYPT_DH_RFC3526_2048, CRYPT_DH_RFC3526_3072, CRYPT_DH_RFC3526_4096, CRYPT_DH_RFC3526_6144, CRYPT_DH_RFC3526_8192, CRYPT_DH_RFC7919_2048, CRYPT_DH_RFC7919_3072, CRYPT_DH_RFC7919_4096, CRYPT_DH_RFC7919_6144, CRYPT_DH_RFC7919_8192, }; DEFINE_OPS_KX(Dh, CRYPT_PKEY_DH); DEFINE_BENCH_CTX_PARA_TIMES_FIXLEN(Dh, g_paraIds, SIZEOF(g_paraIds), 1000);
2401_83913325/openHiTLS-examples_2461
testcode/benchmark/dh_bench.c
C
unknown
3,319
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_md.h" #include "benchmark.h" static int32_t EcdhSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { int32_t ret; CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(ops->algId); if (pkeyCtx == NULL) { printf("Failed to create pkey context\n"); return CRYPT_MEM_ALLOC_FAIL; } ret = CRYPT_EAL_PkeySetParaById(pkeyCtx, paraId); if (ret != CRYPT_SUCCESS) { printf("Failed to set para: %d.\n", paraId); return ret; } ret = CRYPT_EAL_PkeyGen(pkeyCtx); if (ret != CRYPT_SUCCESS) { printf("Failed to gen ecdh key.\n"); return ret; } *ctx = pkeyCtx; return CRYPT_SUCCESS; } static void EcdhTearDown(void *ctx) { CRYPT_EAL_PkeyFreeCtx(ctx); } static int32_t EcdhKeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; int32_t paraId = opts->paraId; const char *curve = GetAlgName(paraId); BENCH_TIMES_VA(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "%s ecdh keyGen", curve); return rc; } static int32_t EcdhKeyDerive(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t paraId = opts->paraId; const char *curve = GetAlgName(paraId); // Create a peer context for key exchange CRYPT_EAL_PkeyCtx *peerCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ECDH); if (peerCtx == NULL) { printf("Failed to create peer context\n"); return CRYPT_MEM_ALLOC_FAIL; } rc = CRYPT_EAL_PkeySetParaById(peerCtx, paraId); if (rc != CRYPT_SUCCESS) { printf("Failed to set peer para: %d.\n", paraId); CRYPT_EAL_PkeyFreeCtx(peerCtx); return rc; } rc = CRYPT_EAL_PkeyGen(peerCtx); if (rc != CRYPT_SUCCESS) { printf("Failed to gen peer key.\n"); CRYPT_EAL_PkeyFreeCtx(peerCtx); return rc; } uint8_t sharedKey[256]; uint32_t sharedKeyLen = sizeof(sharedKey); BENCH_TIMES_VA(CRYPT_EAL_PkeyComputeShareKey(ctx, peerCtx, sharedKey, &sharedKeyLen), rc, CRYPT_SUCCESS, -1, opts->times, "%s ecdh keyDerive", curve); CRYPT_EAL_PkeyFreeCtx(peerCtx); return rc; } static int32_t g_paraIds[] = { CRYPT_ECC_NISTP224, CRYPT_ECC_NISTP256, CRYPT_ECC_NISTP384, CRYPT_ECC_NISTP521, CRYPT_ECC_BRAINPOOLP256R1, CRYPT_ECC_BRAINPOOLP384R1, CRYPT_ECC_BRAINPOOLP512R1, }; DEFINE_OPS_KX(Ecdh, CRYPT_PKEY_ECDH); DEFINE_BENCH_CTX_PARA_FIXLEN(Ecdh, g_paraIds, SIZEOF(g_paraIds));
2401_83913325/openHiTLS-examples_2461
testcode/benchmark/ecdh_bench.c
C
unknown
3,175
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_md.h" #include "benchmark.h" static int32_t EcdsaSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { int32_t ret; CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(ops->algId); if (pkeyCtx == NULL) { printf("Failed to create pkey context\n"); return CRYPT_MEM_ALLOC_FAIL; } ret = CRYPT_EAL_PkeySetParaById(pkeyCtx, paraId); if (ret != CRYPT_SUCCESS) { printf("Failed to set para: %d.\n", paraId); return ret; } ret = CRYPT_EAL_PkeyGen(pkeyCtx); if (ret != CRYPT_SUCCESS) { printf("Failed to gen ecdsa key.\n"); return ret; } *ctx = pkeyCtx; return CRYPT_SUCCESS; } static void EcdsaTearDown(void *ctx) { CRYPT_EAL_PkeyFreeCtx(ctx); } static int32_t EcdsaKeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; int32_t paraId = opts->paraId; const char *curve = GetAlgName(paraId); BENCH_TIMES_VA(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "%s keyGen", curve); return rc; } static int32_t GetHashId(BenchCtx *bench, BenchOptions *opts) { int32_t hashId = bench->ctxOps->hashId; if (opts->hashId != -1) { hashId = opts->hashId; } return hashId; } static int32_t EcdsaSignInner(void *ctx, int32_t hashId, int32_t len) { uint8_t signature[256]; uint32_t signatureLen = sizeof(signature); return CRYPT_EAL_PkeySign(ctx, hashId, g_plain, len, signature, &signatureLen); } static int32_t EcdsaSign(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t paraId = opts->paraId; const char *curve = GetAlgName(paraId); int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } const char *mdName = GetAlgName(hashId); BENCH_TIMES_VA(EcdsaSignInner(ctx, hashId, opts->len), rc, CRYPT_SUCCESS, -1, opts->times, "%s-%s sign", curve, mdName); return rc; } static int32_t EcdsaVerify(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t paraId = opts->paraId; const char *curve = GetAlgName(paraId); int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } uint8_t signature[256]; uint32_t signatureLen = sizeof(signature); rc = CRYPT_EAL_PkeySign(ctx, hashId, g_plain, opts->len, signature, &signatureLen); if (rc != CRYPT_SUCCESS) { printf("Failed to sign\n"); return rc; } const char *mdName = GetAlgName(hashId); BENCH_TIMES_VA(CRYPT_EAL_PkeyVerify(ctx, hashId, g_plain, opts->len, signature, signatureLen), rc, CRYPT_SUCCESS, -1, opts->times, "%s-%s verify", curve, mdName); return rc; } static int32_t g_paraIds[] = { CRYPT_ECC_NISTP224, CRYPT_ECC_NISTP256, CRYPT_ECC_NISTP384, CRYPT_ECC_NISTP521, CRYPT_ECC_BRAINPOOLP256R1, CRYPT_ECC_BRAINPOOLP384R1, CRYPT_ECC_BRAINPOOLP512R1, }; DEFINE_OPS_SIGN(Ecdsa, CRYPT_PKEY_ECDSA, CRYPT_MD_SHA256); DEFINE_BENCH_CTX_PARA_FIXLEN(Ecdsa, g_paraIds, SIZEOF(g_paraIds));
2401_83913325/openHiTLS-examples_2461
testcode/benchmark/ecdsa_bench.c
C
unknown
3,761
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_mac.h" #include "benchmark.h" static int32_t MacSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { (void)ctx; (void)bench; (void)ops; (void)paraId; return CRYPT_SUCCESS; } static void MacTearDown(void *ctx) { (void)ctx; } static int32_t DoMacCtrl(CRYPT_EAL_MacCtx *mac, int32_t paraId) { if (paraId == CRYPT_MAC_CBC_MAC_SM4) { // cbc-mac-sm4 only support zeros padding CRYPT_PaddingType padType = CRYPT_PADDING_ZEROS; return CRYPT_EAL_MacCtrl(mac, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padType, sizeof(padType)); } return CRYPT_SUCCESS; } static int32_t DoMac(void *ctx, BenchCtx *bench, BenchOptions *opts, uint32_t keyLen, uint32_t digestLen) { (void)ctx; (void)bench; int32_t rc = CRYPT_SUCCESS; int32_t paraId = opts->paraId; uint8_t digest[256]; CRYPT_EAL_MacCtx *mac = CRYPT_EAL_MacNewCtx(paraId); if (mac == NULL) { return CRYPT_ERR_ALGID; } if ((rc = CRYPT_EAL_MacInit(mac, g_key, keyLen)) != CRYPT_SUCCESS || (rc = DoMacCtrl(mac, paraId)) != CRYPT_SUCCESS || (rc = CRYPT_EAL_MacUpdate(mac, g_plain, opts->len)) != CRYPT_SUCCESS || (rc = CRYPT_EAL_MacFinal(mac, digest, &digestLen)) != CRYPT_SUCCESS) { printf("do mac init failed\n"); goto ERR; } ERR: CRYPT_EAL_MacFreeCtx(mac); return rc; } static int32_t MacOneShot(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t paraId = opts->paraId; const char *macName = GetAlgName(paraId); uint32_t keyLen = 16; uint32_t digestLen = 256; if (paraId == CRYPT_MAC_CMAC_AES192 || paraId == CRYPT_MAC_GMAC_AES192) { keyLen = 24; } if (paraId == CRYPT_MAC_CMAC_AES256 || paraId == CRYPT_MAC_GMAC_AES256) { keyLen = 32; } if (paraId == CRYPT_MAC_GMAC_AES128 || paraId == CRYPT_MAC_GMAC_AES192 || paraId == CRYPT_MAC_GMAC_AES256) { digestLen = 16; } BENCH_TIMES_VA(DoMac(ctx, bench, opts, keyLen, digestLen), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s mac", macName); return rc; } static int32_t g_paraIds[] = { CRYPT_MAC_HMAC_MD5, CRYPT_MAC_HMAC_SHA1, CRYPT_MAC_HMAC_SHA224, CRYPT_MAC_HMAC_SHA256, CRYPT_MAC_HMAC_SHA384, CRYPT_MAC_HMAC_SHA512, CRYPT_MAC_HMAC_SHA3_224, CRYPT_MAC_HMAC_SHA3_256, CRYPT_MAC_HMAC_SHA3_384, CRYPT_MAC_HMAC_SHA3_512, CRYPT_MAC_HMAC_SM3, CRYPT_MAC_CMAC_AES128, CRYPT_MAC_CMAC_AES192, CRYPT_MAC_CMAC_AES256, CRYPT_MAC_CMAC_SM4, CRYPT_MAC_CBC_MAC_SM4, CRYPT_MAC_GMAC_AES128, CRYPT_MAC_GMAC_AES192, CRYPT_MAC_GMAC_AES256, CRYPT_MAC_SIPHASH64, CRYPT_MAC_SIPHASH128, }; DEFINE_OPS_MD(Mac); DEFINE_BENCH_CTX_PARA(Mac, g_paraIds, SIZEOF(g_paraIds));
2401_83913325/openHiTLS-examples_2461
testcode/benchmark/mac_bench.c
C
unknown
3,424
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_md.h" #include "benchmark.h" static int32_t MdSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { (void)ctx; (void)bench; (void)ops; (void)paraId; return CRYPT_SUCCESS; } static void MdTearDown(void *ctx) { (void)ctx; } static int32_t MdOneShot(void *ctx, BenchCtx *bench, BenchOptions *opts) { (void)ctx; int rc; int32_t paraId = opts->paraId; const char *mdName = GetAlgName(paraId); uint8_t digest[64]; // Maximum digest size for supported algorithms uint32_t digestLen = sizeof(digest); BENCH_TIMES_VA(CRYPT_EAL_Md(paraId, g_plain, opts->len, digest, &digestLen), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s digest", mdName); return rc; } static int32_t g_paraIds[] = { CRYPT_MD_MD5, CRYPT_MD_SHA1, CRYPT_MD_SHA224, CRYPT_MD_SHA256, CRYPT_MD_SHA384, CRYPT_MD_SHA512, CRYPT_MD_SHA3_224, CRYPT_MD_SHA3_256, CRYPT_MD_SHA3_384, CRYPT_MD_SHA3_512, CRYPT_MD_SHAKE128, CRYPT_MD_SHAKE256, CRYPT_MD_SM3, }; DEFINE_OPS_MD(Md); DEFINE_BENCH_CTX_PARA(Md, g_paraIds, SIZEOF(g_paraIds));
2401_83913325/openHiTLS-examples_2461
testcode/benchmark/md_bench.c
C
unknown
1,763
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_md.h" #include "benchmark.h" const char *GetParaName(int32_t paraId) { switch (paraId) { case CRYPT_MLDSA_TYPE_MLDSA_44: return "mldsa-44"; case CRYPT_MLDSA_TYPE_MLDSA_65: return "mldsa-65"; case CRYPT_MLDSA_TYPE_MLDSA_87: return "mldsa-87"; default: break; } return ""; } static int32_t MldsaSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { (void)paraId; CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(ops->algId); if (pkeyCtx == NULL) { printf("Failed to create pkey context\n"); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_PARA_BY_ID, &paraId, sizeof(paraId)); if (ret != CRYPT_SUCCESS) { printf("Failed to set mldsa alg info.\n"); return ret; } ret = CRYPT_EAL_PkeyGen(pkeyCtx); if (ret != CRYPT_SUCCESS) { printf("Failed to gen mldsa key.\n"); return ret; } *ctx = pkeyCtx; return CRYPT_SUCCESS; } static void MldsaTearDown(void *ctx) { CRYPT_EAL_PkeyFreeCtx(ctx); } static int32_t MldsaKeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; BENCH_TIMES_VA(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "%s keyGen", GetParaName(opts->paraId)); return rc; } static int32_t GetHashId(BenchCtx *bench, BenchOptions *opts) { int32_t hashId = bench->ctxOps->hashId; if (opts->hashId != -1) { hashId = opts->hashId; } return hashId; } static int32_t MldsaSignInner(void *ctx, int32_t hashId) { uint8_t plainText[32]; uint8_t signature[5120]; // ML-DSA can have larger signatures uint32_t signatureLen = sizeof(signature); return CRYPT_EAL_PkeySign(ctx, hashId, plainText, sizeof(plainText), signature, &signatureLen); } static int32_t MldsaSign(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } BENCH_TIMES_VA(MldsaSignInner(ctx, hashId), rc, CRYPT_SUCCESS, -1, opts->times, "%s sign", GetParaName(opts->paraId)); return rc; } static int32_t MldsaVerify(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } uint8_t plainText[32]; uint8_t signature[5120]; // ML-DSA can have larger signatures uint32_t signatureLen = sizeof(signature); rc = CRYPT_EAL_PkeySign(ctx, hashId, plainText, sizeof(plainText), signature, &signatureLen); if (rc != CRYPT_SUCCESS) { printf("Failed to sign\n"); return rc; } BENCH_TIMES_VA(CRYPT_EAL_PkeyVerify(ctx, hashId, plainText, sizeof(plainText), signature, signatureLen), rc, CRYPT_SUCCESS, -1, opts->times, "%s verify", GetParaName(opts->paraId)); return rc; } static int32_t g_paraIds[] = { CRYPT_MLDSA_TYPE_MLDSA_44, CRYPT_MLDSA_TYPE_MLDSA_65, CRYPT_MLDSA_TYPE_MLDSA_87, }; DEFINE_OPS_SIGN(Mldsa, CRYPT_PKEY_ML_DSA, CRYPT_MD_SHA256); DEFINE_BENCH_CTX_PARA_FIXLEN(Mldsa, g_paraIds, SIZEOF(g_paraIds));
2401_83913325/openHiTLS-examples_2461
testcode/benchmark/mldsa_bench.c
C
unknown
3,893
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_md.h" #include "benchmark.h" static const char *GetParaName(int32_t paraId) { switch (paraId) { case CRYPT_KEM_TYPE_MLKEM_512: return "mlkem-512"; case CRYPT_KEM_TYPE_MLKEM_768: return "mlkem-768"; case CRYPT_KEM_TYPE_MLKEM_1024: return "mlkem-1024"; default: return "unknown"; } return ""; } static int32_t MlkemSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { (void)paraId; CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(ops->algId); if (pkeyCtx == NULL) { printf("Failed to create pkey context\n"); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_PARA_BY_ID, &paraId, sizeof(paraId)); if (ret != CRYPT_SUCCESS) { printf("Failed to set mldsa alg info.\n"); return ret; } ret = CRYPT_EAL_PkeyGen(pkeyCtx); if (ret != CRYPT_SUCCESS) { printf("Failed to gen mlkem key.\n"); return ret; } *ctx = pkeyCtx; return CRYPT_SUCCESS; } static void MlkemTearDown(void *ctx) { CRYPT_EAL_PkeyFreeCtx(ctx); } static int32_t MlkemKeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; BENCH_TIMES_VA(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "%s keyGen", GetParaName(opts->paraId)); return rc; } static int32_t MlkemEncaps(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; uint8_t ciphertext[2048]; // ML-KEM can have larger ciphertexts uint32_t ciphertextLen = sizeof(ciphertext); uint8_t sharedKey[32]; uint32_t sharedKeyLen = sizeof(sharedKey); BENCH_TIMES_VA(CRYPT_EAL_PkeyEncaps(ctx, ciphertext, &ciphertextLen, sharedKey, &sharedKeyLen), rc, CRYPT_SUCCESS, -1, opts->times, "%s encaps", GetParaName(opts->paraId)); return rc; } static int32_t MlkemDecaps(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; uint8_t ciphertext[2048]; // ML-KEM can have larger ciphertexts uint32_t ciphertextLen = sizeof(ciphertext); uint8_t sharedKey[32]; uint32_t sharedKeyLen = sizeof(sharedKey); // First encap to get a valid ciphertext rc = CRYPT_EAL_PkeyEncaps(ctx, ciphertext, &ciphertextLen, sharedKey, &sharedKeyLen); if (rc != CRYPT_SUCCESS) { printf("Failed to encap\n"); return rc; } BENCH_TIMES_VA(CRYPT_EAL_PkeyDecaps(ctx, ciphertext, ciphertextLen, sharedKey, &sharedKeyLen), rc, CRYPT_SUCCESS, -1, opts->times, "%s decaps", GetParaName(opts->paraId)); return rc; } static int32_t g_paraIds[] = { CRYPT_KEM_TYPE_MLKEM_512, CRYPT_KEM_TYPE_MLKEM_768, CRYPT_KEM_TYPE_MLKEM_1024, }; DEFINE_OPS_KEM(Mlkem, CRYPT_PKEY_ML_KEM); DEFINE_BENCH_CTX_PARA_FIXLEN(Mlkem, g_paraIds, SIZEOF(g_paraIds));
2401_83913325/openHiTLS-examples_2461
testcode/benchmark/mlkem_bench.c
C
unknown
3,535
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_md.h" #include "benchmark.h" static int32_t RsaSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { (void)paraId; CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(ops->algId); if (pkeyCtx == NULL) { printf("Failed to create pkey context\n"); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = CRYPT_EAL_PkeyGen(pkeyCtx); if (ret != CRYPT_SUCCESS) { printf("Failed to gen rsa key.\n"); return ret; } *ctx = pkeyCtx; return CRYPT_SUCCESS; } static void RsaTearDown(void *ctx) { CRYPT_EAL_PkeyFreeCtx(ctx); } static int32_t RsaKeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; BENCH_TIMES(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "rsa keyGen"); return rc; } static int32_t RsaEncInner(void *ctx) { uint8_t plainText[32]; uint8_t cipherText[512]; // RSA can have larger output uint32_t outLen = sizeof(cipherText); return CRYPT_EAL_PkeyEncrypt(ctx, plainText, sizeof(plainText), cipherText, &outLen); } static int32_t RsaEnc(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; BENCH_TIMES(RsaEncInner(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "rsa enc"); return rc; } static int32_t RsaDec(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; uint8_t plainText[32]; uint32_t plainTextLen = sizeof(plainText); uint8_t cipherText[512]; // RSA can have larger output uint32_t outLen = sizeof(cipherText); rc = CRYPT_EAL_PkeyEncrypt(ctx, plainText, sizeof(plainText), cipherText, &outLen); if (rc != CRYPT_SUCCESS) { printf("Failed to encrypt\n"); return rc; } BENCH_TIMES(CRYPT_EAL_PkeyDecrypt(ctx, cipherText, outLen, plainText, &plainTextLen), rc, CRYPT_SUCCESS, -1, opts->times, "rsa dec"); return rc; } static int32_t GetHashId(BenchCtx *bench, BenchOptions *opts) { int32_t hashId = bench->ctxOps->hashId; if (opts->hashId != -1) { hashId = opts->hashId; } return hashId; } static int32_t RsaSignInner(void *ctx, int32_t hashId) { uint8_t plainText[32]; uint8_t signature[512]; // RSA can have larger signatures uint32_t signatureLen = sizeof(signature); return CRYPT_EAL_PkeySign(ctx, hashId, plainText, sizeof(plainText), signature, &signatureLen); } static int32_t RsaSign(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } BENCH_TIMES(RsaSignInner(ctx, hashId), rc, CRYPT_SUCCESS, -1, opts->times, "rsa sign"); return rc; } static int32_t RsaVerify(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } uint8_t plainText[32]; uint8_t signature[512]; // RSA can have larger signatures uint32_t signatureLen = sizeof(signature); rc = CRYPT_EAL_PkeySign(ctx, hashId, plainText, sizeof(plainText), signature, &signatureLen); if (rc != CRYPT_SUCCESS) { printf("Failed to sign\n"); return rc; } BENCH_TIMES(CRYPT_EAL_PkeyVerify(ctx, hashId, plainText, sizeof(plainText), signature, signatureLen), rc, CRYPT_SUCCESS, -1, opts->times, "rsa verify"); return rc; } DEFINE_OPS(Rsa, CRYPT_PKEY_RSA, CRYPT_MD_SHA256); DEFINE_BENCH_CTX_FIXLEN(Rsa);
2401_83913325/openHiTLS-examples_2461
testcode/benchmark/rsa_bench.c
C
unknown
4,123
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "benchmark.h" static int32_t SlhDsaSetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(ops->algId); if (pkeyCtx == NULL) { printf("Failed to create pkey context\n"); return CRYPT_MEM_ALLOC_FAIL; } int rc = CRYPT_SUCCESS; CRYPT_PKEY_ParaId algId = paraId; rc = CRYPT_EAL_PkeyCtrl(pkeyCtx, CRYPT_CTRL_SET_PARA_BY_ID, (void *)&algId, sizeof(algId)); if (rc != CRYPT_SUCCESS) { return rc; } rc = CRYPT_EAL_PkeyGen(pkeyCtx); if (rc != CRYPT_SUCCESS) { printf("Failed to gen slhdsa key.\n"); return rc; } *ctx = pkeyCtx; return CRYPT_SUCCESS; } static void SlhDsaTearDown(void *ctx) { CRYPT_EAL_PkeyFreeCtx(ctx); } static int32_t SlhDsaKeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; CRYPT_PKEY_ParaId paraId = opts->paraId; rc = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_PARA_BY_ID, (void *)&paraId, sizeof(paraId)); if (rc != CRYPT_SUCCESS) { return rc; } BENCH_TIMES_VA(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "%s keyGen", GetAlgName(paraId)); return rc; } static int32_t GetHashId(BenchCtx *bench, BenchOptions *opts) { int32_t hashId = bench->ctxOps->hashId; if (opts->hashId != -1) { hashId = opts->hashId; } return hashId; } static int32_t SlhDsaSignInner(void *ctx, int32_t hashId, int32_t len) { static uint8_t sign[51200]; // maximum len is 49856 uint32_t signLen = sizeof(sign); return CRYPT_EAL_PkeySign(ctx, hashId, g_plain, len, sign, &signLen); } static int32_t SlhDsaSign(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t hashId = GetHashId(bench, opts); BENCH_TIMES_VA(SlhDsaSignInner(ctx, hashId, opts->len), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s sign", GetAlgName(opts->paraId)); return rc; } static int32_t SlhDsaVerify(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; static uint8_t sign[51200]; // maximum len is 49856 uint32_t signLen = sizeof(sign); int32_t hashId = GetHashId(bench, opts); rc = CRYPT_EAL_PkeySign(ctx, hashId, g_plain, opts->len, sign, &signLen); if (rc != CRYPT_SUCCESS) { printf("Failed to sign\n"); return rc; } BENCH_TIMES_VA(CRYPT_EAL_PkeyVerify(ctx, hashId, g_plain, opts->len, sign, signLen), rc, CRYPT_SUCCESS, opts->len, opts->times, "%s verify", GetAlgName(opts->paraId)); return rc; } static int32_t g_paraIds[] = { CRYPT_SLH_DSA_SHA2_128S, CRYPT_SLH_DSA_SHAKE_128S, CRYPT_SLH_DSA_SHA2_128F, CRYPT_SLH_DSA_SHAKE_128F, CRYPT_SLH_DSA_SHA2_192S, CRYPT_SLH_DSA_SHAKE_192S, CRYPT_SLH_DSA_SHA2_192F, CRYPT_SLH_DSA_SHAKE_192F, CRYPT_SLH_DSA_SHA2_256S, CRYPT_SLH_DSA_SHAKE_256S, CRYPT_SLH_DSA_SHA2_256F, CRYPT_SLH_DSA_SHAKE_256F, }; DEFINE_OPS_SIGN(SlhDsa, CRYPT_PKEY_SLH_DSA, CRYPT_MD_SHA256); DEFINE_BENCH_CTX_PARA_FIXLEN(SlhDsa, g_paraIds, SIZEOF(g_paraIds));
2401_83913325/openHiTLS-examples_2461
testcode/benchmark/slh_dsa_bench.c
C
unknown
3,723
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stddef.h> #include <string.h> #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_pkey.h" #include "crypt_eal_md.h" #include "benchmark.h" static int32_t Sm2SetUp(void **ctx, BenchCtx *bench, const CtxOps *ops, int32_t paraId) { (void)paraId; CRYPT_EAL_PkeyCtx *pkeyCtx = CRYPT_EAL_PkeyNewCtx(ops->algId); if (pkeyCtx == NULL) { printf("Failed to create pkey context\n"); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = CRYPT_EAL_PkeyGen(pkeyCtx); if (ret != CRYPT_SUCCESS) { printf("Failed to gen sm2 key.\n"); return ret; } *ctx = pkeyCtx; return CRYPT_SUCCESS; } static void Sm2TearDown(void *ctx) { CRYPT_EAL_PkeyFreeCtx(ctx); } static int32_t Sm2KeyGen(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; BENCH_TIMES(CRYPT_EAL_PkeyGen(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "sm2 keyGen"); return rc; } static int32_t Sm2KeyDeriveInner(void *ctx, void *peerCtx) { int rc = CRYPT_SUCCESS; uint8_t localR[128] = {0}; rc = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GENE_SM2_R, localR, sizeof(localR)); if (rc != CRYPT_SUCCESS) { printf("Failed to generate R\n"); return rc; } uint8_t shareKey[64] = {0}; uint32_t shareKeyLen = sizeof(shareKey); rc = CRYPT_EAL_PkeyComputeShareKey(ctx, peerCtx, shareKey, &shareKeyLen); if (rc != CRYPT_SUCCESS) { printf("Failed to compute share key\n"); return rc; } return CRYPT_SUCCESS; } static int32_t Sm2KeyDerive(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; CRYPT_EAL_PkeyCtx *peerCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SM2); if (peerCtx == NULL || CRYPT_EAL_PkeyGen(peerCtx) != CRYPT_SUCCESS) { printf("Failed to create pkey context\n"); CRYPT_EAL_PkeyFreeCtx(peerCtx); rc = CRYPT_MEM_ALLOC_FAIL; goto ERR_OUT; } char *peerRHex = "04acc27688a6f7b706098bc91ff3ad1bff7dc2802cdb14ccccdb0a90471f9bd7072fedac0494b2ffc4d6853876c79b8f301c6573ad0aa50f39fc87181e1a1b46fe"; uint8_t peerR[128] = {0}; uint32_t peerRLen = sizeof(peerR); Hex2Bin(peerRHex, peerR, &peerRLen); rc = CRYPT_EAL_PkeyCtrl(peerCtx, CRYPT_CTRL_SET_SM2_R, peerR, peerRLen); if (rc != CRYPT_SUCCESS) { printf("Failed to set R\n"); goto ERR_OUT; } BENCH_TIMES(Sm2KeyDeriveInner(ctx, peerCtx), rc, CRYPT_SUCCESS, -1, opts->times, "sm2 keyDerive"); ERR_OUT: CRYPT_EAL_PkeyFreeCtx(peerCtx); return rc; } static int32_t Sm2EncInner(void *ctx) { uint8_t plainText[32]; uint8_t cipherText[256]; // > 32 + 97 + 12 uint32_t outLen = sizeof(cipherText); return CRYPT_EAL_PkeyEncrypt(ctx, plainText, sizeof(plainText), cipherText, &outLen); } static int32_t Sm2Enc(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc = CRYPT_SUCCESS; BENCH_TIMES(Sm2EncInner(ctx), rc, CRYPT_SUCCESS, -1, opts->times, "sm2 enc"); return rc; } static int32_t Sm2Dec(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; uint8_t plainText[32]; uint32_t plainTextLen = sizeof(plainText); uint8_t cipherText[256]; // > 32 + 97 + 12 uint32_t outLen = sizeof(cipherText); rc = CRYPT_EAL_PkeyEncrypt(ctx, plainText, sizeof(plainText), cipherText, &outLen); if (rc != CRYPT_SUCCESS) { printf("Failed to encrypt\n"); return rc; } BENCH_TIMES(CRYPT_EAL_PkeyDecrypt(ctx, cipherText, outLen, plainText, &plainTextLen), rc, CRYPT_SUCCESS, -1, opts->times, "sm2 dec"); return rc; } static int32_t GetHashId(BenchCtx *bench, BenchOptions *opts) { int32_t hashId = bench->ctxOps->hashId; if (opts->hashId != -1) { if (CRYPT_EAL_MdGetDigestSize(opts->hashId) != 32) { printf("Wrong Hash Algorithm Id for Sm2."); return -1; } hashId = opts->hashId; } return hashId; } static int32_t Sm2SignInner(void *ctx, int32_t hashId) { uint8_t plainText[32]; uint8_t signature[256]; uint32_t signatureLen = sizeof(signature); return CRYPT_EAL_PkeySign(ctx, hashId, plainText, sizeof(plainText), signature, &signatureLen); } static int32_t Sm2Sign(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } BENCH_TIMES(Sm2SignInner(ctx, hashId), rc, CRYPT_SUCCESS, -1, opts->times, "sm2 sign"); return rc; } static int32_t Sm2Verify(void *ctx, BenchCtx *bench, BenchOptions *opts) { int rc; int32_t hashId = GetHashId(bench, opts); if (hashId == -1) { return -1; } uint8_t plainText[32]; uint8_t signature[256]; uint32_t signatureLen = sizeof(signature); rc = CRYPT_EAL_PkeySign(ctx, hashId, plainText, sizeof(plainText), signature, &signatureLen); if (rc != CRYPT_SUCCESS) { printf("Failed to sign\n"); return rc; } BENCH_TIMES(CRYPT_EAL_PkeyVerify(ctx, hashId, plainText, sizeof(plainText), signature, signatureLen), rc, CRYPT_SUCCESS, -1, opts->times, "sm2 verify"); return rc; } DEFINE_OPS(Sm2, CRYPT_PKEY_SM2, CRYPT_MD_SM3); DEFINE_BENCH_CTX_FIXLEN(Sm2);
2401_83913325/openHiTLS-examples_2461
testcode/benchmark/sm2_bench.c
C
unknown
5,785
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <signal.h> #include <stdarg.h> #include <unistd.h> #include "securec.h" #define BUF_SIZE (65536 * 17) #define MAX_RAND_SIZE (1024 * 16) #define MAX_PATH 1024 #define MAX_FILE_NAME 200 #define MAX_IN_CASES 100000 #define OUTPUT_LINE_LENGTH 60 #ifdef FAIL_REPEAT_RUN #define FAIL_TRY_TIMES 3 #else #define FAIL_TRY_TIMES 0 #endif #define FUNCTION_LOG_FORMAT "./log/%s.%s.log" #define SUITE_LOG_FORMAT "./log/%s.log" #define LOCAL_DIR "./" typedef struct { char buf[MAX_DATA_LINE_LEN]; char *arg[MAX_ARGUMENT_COUNT]; char testVectorName[MAX_FILE_NAME]; uint32_t argLen; } TestArgs; typedef struct { void *param[MAX_ARGUMENT_COUNT]; int paramCount; int intParam[MAX_ARGUMENT_COUNT]; int intParamCount; Hex hexParam[MAX_ARGUMENT_COUNT]; int hexParamCount; } TestParam; static TestArgs *g_executeCases[MAX_IN_CASES]; static int g_executeCount = 0; static int ConvertStringCase(const TestArgs *arg) { for (uint32_t i = 1; i < arg->argLen; i += 2) { if (strcmp(arg->arg[i], "char") == 0 || strcmp(arg->arg[i], "Hex") == 0) { if (ConvertString((char **)&(arg->arg[i+1])) != 0) { return 1; } } } return 0; } static int LoadDataFile(const char *fileName) { if (g_executeCount > 0) { return 0; } FILE *fpDatax = fopen(fileName, "r"); if (fpDatax == NULL) { Print("Error opening file\n"); return (-1); } int rt = 0; for (int i = 0; i < MAX_IN_CASES; i++) { g_executeCases[i] = (TestArgs *)malloc(sizeof(TestArgs)); if (g_executeCases[i] == NULL) { rt = -1; goto EXIT; } g_executeCases[i]->argLen = MAX_ARGUMENT_COUNT; if (ReadLine(fpDatax, g_executeCases[i]->testVectorName, MAX_FILE_NAME, 1, 1) != 0) { free(g_executeCases[i]); goto EXIT; } if (ReadLine(fpDatax, g_executeCases[i]->buf, MAX_DATA_LINE_LEN, 1, 1) != 0) { free(g_executeCases[i]); Print("Read vector failed, test vector should have 2 lines, here there's only one\n"); rt = -1; goto EXIT; } if (SplitArguments(g_executeCases[i]->buf, strlen(g_executeCases[i]->buf), g_executeCases[i]->arg, &(g_executeCases[i]->argLen)) != 0) { free(g_executeCases[i]); rt = -1; goto EXIT; } if (ConvertStringCase(g_executeCases[i]) == 1) { free(g_executeCases[i]); rt = -1; goto EXIT; } g_executeCount += 1; } char tmpName[MAX_FILE_NAME]; if (ReadLine(fpDatax, tmpName, MAX_FILE_NAME, 1, 1) == 0) { Print("More test cases than max case num %d\n", MAX_IN_CASES); rt = -1; } EXIT: if (rt != 0) { for (int i = 0; i < g_executeCount; i++) { free(g_executeCases[i]); } g_executeCount = 0; } (void)fclose(fpDatax); return rt; }
2401_83913325/openHiTLS-examples_2461
testcode/common/execute_base.c
C
unknown
3,546
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <setjmp.h> #include <time.h> #include <sys/time.h> static jmp_buf env; static int isSubProc = 0; int *GetJmpAddress(void) { return &isSubProc; } void handleSignal() { siglongjmp(env, 1); } static void PrintCaseName(FILE *logFile, bool showDetail, const char *name) { // print a minimum of 4 dots int32_t dotCount = (OUTPUT_LINE_LENGTH - (int32_t)strlen(name) >= 4) ? (OUTPUT_LINE_LENGTH - (int32_t)strlen(name)) : 4; if (showDetail) { Print("%s", name); for (int32_t j = 0; j < dotCount; j++) { Print("."); } } (void)fprintf(logFile, "%s", name); for (int32_t j = 0; j < dotCount; j++) { (void)fprintf(logFile, "."); } } static int ParseArgs(const TestArgs *arg, TestParam *info) { info->hexParamCount = 0; info->intParamCount = 0; info->paramCount = 0; for (uint32_t i = 1; i < arg->argLen; i += 2) { // 2 if (strcmp(arg->arg[i], "int") == 0) { if (ConvertInt(arg->arg[i + 1], &(info->intParam[info->intParamCount])) == 0) { info->param[info->paramCount] = &(info->intParam[info->intParamCount]); info->intParamCount++; } else { Print("\nERROR: Int param conversion failed for:\n\"%s\"\n", arg->arg[i + 1]); return 1; } } else if (strcmp(arg->arg[i], "char") == 0) { info->param[info->paramCount] = arg->arg[i+1]; } else if (strcmp(arg->arg[i], "Hex") == 0) { if (ConvertHex(arg->arg[i + 1], &(info->hexParam[info->hexParamCount])) != 0) { Print("\nERROR: Hex param conversion failed for:\n\"%s\"\n", arg->arg[i + 1]); return 1; } info->param[info->paramCount] = &(info->hexParam[info->hexParamCount]); info->hexParamCount++; } else if (strcmp(arg->arg[i], "exp") == 0) { int expId = 0; if (ConvertInt(arg->arg[i + 1], &expId) != 0 || getExpression(expId, &(info->intParam[info->intParamCount])) != 0) { Print("\nERROR: Macro param conversion failed\n"); return 1; } info->param[info->paramCount] = &(info->intParam[info->intParamCount]); info->intParamCount++; } else { return 1; } info->paramCount++; } return 0; } static int PrintCaseNameResult(FILE *logFile, int vectorCount, int skipCount, int passCount, time_t beginTime) { char suitePrefix[OUTPUT_LINE_LENGTH] = {0}; (void)snprintf_truncated_s(suitePrefix, sizeof(suitePrefix), "%s", suiteName); size_t leftSize = sizeof(suitePrefix) - 1 - strlen(suitePrefix); if (leftSize > 0) { (void)memset_s(suitePrefix + strlen(suitePrefix), sizeof(suitePrefix) - strlen(suitePrefix), '.', leftSize); } int failCount = vectorCount - passCount - skipCount; if (failCount == 0) { Print("%sPASS || Run %-6d testcases, passed: %-6d, skipped: %-6d, failed: %-6d useSec:%-5lu\n", suitePrefix, vectorCount, passCount, skipCount, failCount, time(NULL) - beginTime); } else { Print("%sFAIL || Run %-6d testcases, passed: %-6d, skipped: %-6d, failed: %-6d useSec:%-5lu\n", suitePrefix, vectorCount, passCount, skipCount, failCount, time(NULL) - beginTime); } time_t rawtime; struct tm *timeinfo; (void)time(&rawtime); timeinfo = localtime(&rawtime); (void)fprintf(logFile, "End time: %s", asctime(timeinfo)); (void)fprintf(logFile, "Result: Run %d tests, Passed: %d, Skipped: %d, Failed: %d\n", vectorCount, passCount, skipCount, failCount); return failCount; } static int ProcessCases(FILE *logFile, bool showDetail, int targetFuncId) { (void)logFile; volatile int vectorCount = 0; volatile int passCount = 0; volatile int skipCount = 0; volatile int tryNum; time_t beginTime = time(NULL); struct timespec start, end; for (volatile int i = 0; i < g_executeCount; i++) { int funcId = strtoul(g_executeCases[i]->arg[0], NULL, 10); // 10 if (funcId < 0 || funcId > ((int)(sizeof(test_funcs)/sizeof(TestWrapper)))) { Print("funcId false!\n"); return 1; } if ((targetFuncId != -1) && (funcId != targetFuncId)) { continue; } (void)fprintf(logFile, "%s ", funcName[funcId]); PrintCaseName(logFile, showDetail, g_executeCases[i]->testVectorName); TestParam io; if (ParseArgs(g_executeCases[i], &io) != 0) { return -1; } TestWrapper fp = test_funcs[funcId]; g_testResult.result = TEST_RESULT_SUCCEED; tryNum = 0; clock_gettime(CLOCK_REALTIME, &start); do { if (tryNum > 0) { sleep(10); g_testResult.result = TEST_RESULT_SUCCEED; } tryNum++; #ifdef ASAN fp(io.param); #else // Executing Function if (signal(SIGSEGV, handleSignal) == SIG_ERR) { return -1; } int r = sigsetjmp(env, 1); if (r == 0) { fp(io.param); } else if (r == 1){ g_testResult.result = TEST_RESULT_FAILED; } if (isSubProc != 0) { break; } #endif } while ((g_testResult.result == TEST_RESULT_FAILED) && (tryNum < FAIL_TRY_TIMES)); if (g_testResult.result == TEST_RESULT_SUCCEED) { passCount++; } else if (g_testResult.result == TEST_RESULT_SKIPPED) { skipCount++; } vectorCount++; clock_gettime(CLOCK_REALTIME, &end); uint64_t elapsedms = (end.tv_sec - start.tv_sec) * 1000 + (end.tv_nsec - start.tv_nsec) / 1000000; PrintResult(showDetail, g_executeCases[i]->testVectorName, elapsedms); PrintLog(logFile); for (int j = 0; j < io.hexParamCount; j++) { FreeHex(&io.hexParam[j]); } if (isSubProc != 0) { break; } } return PrintCaseNameResult(logFile, vectorCount, skipCount, passCount, beginTime); } static int ExecuteTest(const char *fileName, bool showDetail, int targetFuncId) { if (LoadDataFile(fileName) != 0) { return -1; } FILE *logFile = NULL; char logFileName[MAX_FILE_NAME] = {0}; if (targetFuncId == -1) { if (sprintf_s(logFileName, MAX_FILE_NAME, SUITE_LOG_FORMAT, suiteName) <= 0) { Print("An error occurred while creating the log file\n"); return (-1); } } else { if (sprintf_s(logFileName, MAX_FILE_NAME, FUNCTION_LOG_FORMAT, suiteName, funcName[targetFuncId]) <= 0) { Print("An error occurred while creating the log file\n"); return (-1); } } time_t rawtime = time(NULL); if (rawtime == 0) { return -1; } logFile = fopen(logFileName, "w"); if (logFile != NULL) { struct tm *timeinfo; timeinfo = localtime(&rawtime); if (fprintf(logFile, "Begin time: %s", asctime(timeinfo)) <= 0) { fclose(logFile); return -1; } } int rt = ProcessCases(logFile, showDetail, targetFuncId); if (logFile != NULL) { fclose(logFile); } return rt; } int ProcessMutiArgs(int argc, char **argv, const char *fileName) { int printDetail = 1; int curTestCnt = 0; int ret = -1; int testCnt = sizeof(test_funcs) / sizeof(test_funcs[0]); int *funcIndex = malloc(sizeof(int) * testCnt); int found; if (funcIndex == NULL) { return ret; } for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "NO_DETAIL") == 0) { printDetail = 0; continue; } found = 0; for (int j = 0; j < testCnt; j++) { if (strcmp(argv[i], funcName[j]) == 0) { funcIndex[curTestCnt++] = j; found = 1; break; } } if (found != 1) { Print("test function '%s' do not exist\n", argv[i]); goto EXIT; } } if (curTestCnt == 0) { ret = ExecuteTest(fileName, printDetail, -1); goto EXIT; } for (int i = 0; i < curTestCnt; i++) { if (ExecuteTest(fileName, printDetail, funcIndex[i]) != 0) { goto EXIT; } } ret = 0; EXIT: free(funcIndex); return ret; } int main(int argc, char **argv) { signal(SIGTTOU, SIG_IGN); signal(SIGTTIN, SIG_IGN); int ret = 0; #ifndef PRINT_TO_TERMINAL char testOutputName[MAX_FILE_NAME] = {0}; if (sprintf_s(testOutputName, MAX_FILE_NAME, "%s.output", suiteName) <= 0) { return 0; } FILE *fp = fopen(testOutputName, "w"); if (fp == NULL) { return 1; } SetOutputFile(fp); #endif char testName[MAX_FILE_PATH_LEN]; if (sprintf_s(testName, MAX_FILE_PATH_LEN, "%s.datax", suiteName) <= 0) { goto EXIT; } if (argc == 1) { ret = ExecuteTest(testName, 1, -1); } else { ret = ProcessMutiArgs(argc, argv, testName); } if (ret != 0) { Print("execute test failed\n"); } for (int i = 0; i < g_executeCount; i++) { free(g_executeCases[i]); } EXIT: #ifndef PRINT_TO_TERMINAL (void)fclose(fp); #endif return ret; }
2401_83913325/openHiTLS-examples_2461
testcode/common/execute_test.c
C
unknown
9,964
# This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. cmake_minimum_required(VERSION 3.16 FATAL_ERROR) project(demo) message(status "HITLS_ROOT: ${HITLS_ROOT}") set(HITLS_ROOT ../..) set(HITLS_INCLUDE ${HITLS_ROOT}/include/bsl ${HITLS_ROOT}/include/crypto ${HITLS_ROOT}/include/tls ${HITLS_ROOT}/include/pki ${HITLS_ROOT}/include/auth ${HITLS_ROOT}/config/macro_config ${HITLS_ROOT}/platform/Secure_C/include) if(CUSTOM_CFLAGS) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CUSTOM_CFLAGS}") endif() if(ENABLE_GCOV) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage -lgcov") endif() if(ENABLE_ASAN) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=address -fno-stack-protector -fno-omit-frame-pointer") endif() add_library(DEMO_INTF INTERFACE) target_compile_options(DEMO_INTF INTERFACE -g) target_link_directories(DEMO_INTF INTERFACE ${HITLS_ROOT}/build ${HITLS_ROOT}/platform/Secure_C/lib/) target_link_libraries(DEMO_INTF INTERFACE hitls_tls hitls_pki hitls_auth hitls_crypto hitls_bsl boundscheck pthread dl) target_include_directories(DEMO_INTF INTERFACE ${HITLS_INCLUDE}) file(GLOB TESTS "*.c") foreach(testcase ${TESTS}) get_filename_component(testname ${testcase} NAME_WLE) add_executable(${testname} ${testcase}) target_link_libraries(${testname} PRIVATE DEMO_INTF) endforeach()
2401_83913325/openHiTLS-examples_2461
testcode/demo/CMakeLists.txt
CMake
unknown
1,948
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "securec.h" #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_eal_init.h" #include "crypt_algid.h" #include "crypt_eal_rand.h" #include "hitls_error.h" #include "hitls_config.h" #include "hitls.h" #include "hitls_cert_init.h" #include "hitls_cert.h" #include "hitls_crypt_init.h" #include "hitls_pki_cert.h" #include "crypt_errno.h" #define CERTS_PATH "../../../testcode/testdata/tls/certificate/der/ecdsa_sha256/" #define HTTP_BUF_MAXLEN (18 * 1024) /* 18KB */ int main(int32_t argc, char *argv[]) { int32_t exitValue = -1; int32_t ret = 0; HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; BSL_UIO *uio = NULL; int fd = 0; HITLS_X509_Cert *rootCA = NULL; HITLS_X509_Cert *subCA = NULL; ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_Init: error code is %x\n", ret); return ret; } HITLS_CertMethodInit(); HITLS_CryptMethodInit(); fd = socket(AF_INET, SOCK_STREAM, 0); if (fd == -1) { printf("Create socket failed.\n"); goto EXIT; } int option = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)) < 0) { close(fd); printf("setsockopt SO_REUSEADDR failed.\n"); goto EXIT; } // Set the protocol and port number struct sockaddr_in serverAddr; (void)memset_s(&serverAddr, sizeof(serverAddr), 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(12345); serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); if (connect(fd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) != 0) { printf("connect failed.\n"); goto EXIT; } config = HITLS_CFG_NewTLS12Config(); if (config == NULL) { printf("HITLS_CFG_NewTLS12Config failed.\n"); goto EXIT; } ret = HITLS_CFG_SetCheckKeyUsage(config, false); // disable cert keyusage check if (ret != HITLS_SUCCESS) { printf("Disable check KeyUsage failed.\n"); goto EXIT; } /* 加载证书:需要用户实现 */ ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, CERTS_PATH "ca.der", &rootCA); if (ret != HITLS_SUCCESS) { printf("Parse ca failed.\n"); goto EXIT; } ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, CERTS_PATH "inter.der", &subCA); if (ret != HITLS_SUCCESS) { printf("Parse subca failed.\n"); goto EXIT; } HITLS_CFG_AddCertToStore(config, rootCA, TLS_CERT_STORE_TYPE_DEFAULT, true); HITLS_CFG_AddCertToStore(config, subCA, TLS_CERT_STORE_TYPE_DEFAULT, true); /* 新建openHiTLS上下文 */ ctx = HITLS_New(config); if (ctx == NULL) { printf("HITLS_New failed.\n"); goto EXIT; } uio = BSL_UIO_New(BSL_UIO_TcpMethod()); if (uio == NULL) { printf("BSL_UIO_New failed.\n"); goto EXIT; } ret = BSL_UIO_Ctrl(uio, BSL_UIO_SET_FD, (int32_t)sizeof(fd), &fd); if (ret != HITLS_SUCCESS) { BSL_UIO_Free(uio); printf("BSL_UIO_SET_FD failed, fd = %u.\n", fd); goto EXIT; } ret = HITLS_SetUio(ctx, uio); if (ret != HITLS_SUCCESS) { BSL_UIO_Free(uio); printf("HITLS_SetUio failed. ret = 0x%x.\n", ret); goto EXIT; } /* 进行TLS连接、用户需按实际场景考虑返回值 */ ret = HITLS_Connect(ctx); if (ret != HITLS_SUCCESS) { printf("HITLS_Connect failed, ret = 0x%x.\n", ret); goto EXIT; } /* 向对端发送报文、用户需按实际场景考虑返回值 */ const uint8_t sndBuf[] = "Hi, this is client\n"; uint32_t writeLen = 0; ret = HITLS_Write(ctx, sndBuf, sizeof(sndBuf), &writeLen); if (ret != HITLS_SUCCESS) { printf("HITLS_Write error:error code:%d\n", ret); goto EXIT; } /* 读取对端报文、用户需按实际场景考虑返回值 */ uint8_t readBuf[HTTP_BUF_MAXLEN + 1] = {0}; uint32_t readLen = 0; ret = HITLS_Read(ctx, readBuf, HTTP_BUF_MAXLEN, &readLen); if (ret != HITLS_SUCCESS) { printf("HITLS_Read failed, ret = 0x%x.\n", ret); goto EXIT; } printf("get from server size:%u :%s\n", readLen, readBuf); exitValue = 0; EXIT: HITLS_Close(ctx); HITLS_Free(ctx); HITLS_CFG_FreeConfig(config); close(fd); HITLS_X509_CertFree(rootCA); HITLS_X509_CertFree(subCA); BSL_UIO_Free(uio); return exitValue; }
2401_83913325/openHiTLS-examples_2461
testcode/demo/client.c
C
unknown
4,608
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "crypt_types.h" #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_algid.h" #include "crypt_eal_init.h" #include "crypt_errno.h" #include "crypt_eal_rand.h" void PrintLastError(void) { const char *file = NULL; uint32_t line = 0; BSL_ERR_GetLastErrorFileLine(&file, &line); printf("failed at file %s at line %d\n", file, line); } int main(void) { int ret; uint8_t output[100] = {0}; uint32_t len = 100; ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_Init: error code is %x\n", ret); return ret; } // Obtain the random number sequence of the **len** value. ret = CRYPT_EAL_RandbytesEx(NULL, output, len); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_Randbytes: error code is %x\n", ret); PrintLastError(); goto EXIT; } printf("random value is: "); // Output the random number. for (uint32_t i = 0; i < len; i++) { printf("%02x", output[i]); } printf("\n"); // Reseeding ret = CRYPT_EAL_RandSeedEx(NULL); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_RandSeed: error code is %x\n", ret); PrintLastError(); goto EXIT; } // Obtain the random number sequence of the **len** value. ret = CRYPT_EAL_RandbytesEx(NULL, output, len); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_Randbytes: error code is %x\n", ret); PrintLastError(); goto EXIT; } printf("random value is: "); // Output the random number. for (uint32_t i = 0; i < len; i++) { printf("%02x", output[i]); } printf("\n"); EXIT: // Release the context memory. CRYPT_EAL_RandDeinit(); BSL_ERR_DeInit(); return 0; }
2401_83913325/openHiTLS-examples_2461
testcode/demo/drbg.c
C
unknown
2,396
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "crypt_types.h" #include "crypt_eal_pkey.h" // Header file for key exchange. #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_eal_init.h" #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_rand.h" void PrintLastError(void) { const char *file = NULL; uint32_t line = 0; BSL_ERR_GetLastErrorFileLine(&file, &line); printf("failed at file %s at line %d\n", file, line); } int main(void) { int ret; uint8_t prikey[] = {0x7d, 0x7d, 0xc5, 0xf7, 0x1e, 0xb2, 0x9d, 0xda, 0xf8, 0x0d, 0x62, 0x14, 0x63, 0x2e, 0xea, 0xe0, 0x3d, 0x90, 0x58, 0xaf, 0x1f, 0xb6, 0xd2, 0x2e, 0xd8, 0x0b, 0xad, 0xb6, 0x2b, 0xc1, 0xa5, 0x34}; uint8_t pubkey[] = {0x04, 0x70, 0x0c, 0x48, 0xf7, 0x7f, 0x56, 0x58, 0x4c, 0x5c, 0xc6, 0x32, 0xca, 0x65, 0x64, 0x0d, 0xb9, 0x1b, 0x6b, 0xac, 0xce, 0x3a, 0x4d, 0xf6, 0xb4, 0x2c, 0xe7, 0xcc, 0x83, 0x88, 0x33, 0xd2, 0x87, 0xdb, 0x71, 0xe5, 0x09, 0xe3, 0xfd, 0x9b, 0x06, 0x0d, 0xdb, 0x20, 0xba, 0x5c, 0x51, 0xdc, 0xc5, 0x94, 0x8d, 0x46, 0xfb, 0xf6, 0x40, 0xdf, 0xe0, 0x44, 0x17, 0x82, 0xca, 0xb8, 0x5f, 0xa4, 0xac}; uint8_t resSharekey[] = {0x46, 0xfc, 0x62, 0x10, 0x64, 0x20, 0xff, 0x01, 0x2e, 0x54, 0xa4, 0x34, 0xfb, 0xdd, 0x2d, 0x25, 0xcc, 0xc5, 0x85, 0x20, 0x60, 0x56, 0x1e, 0x68, 0x04, 0x0d, 0xd7, 0x77, 0x89, 0x97, 0xbd, 0x7b}; CRYPT_EAL_PkeyPrv prvKey = {0}; CRYPT_EAL_PkeyPub pubKey = {0}; uint32_t shareLen; uint8_t *shareKey; CRYPT_EAL_PkeyCtx *prvCtx = NULL; CRYPT_EAL_PkeyCtx *pubCtx = NULL; CRYPT_PKEY_ParaId id = CRYPT_ECC_NISTP256; ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_Init: error code is %x\n", ret); goto EXIT; } prvCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ECDH); pubCtx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ECDH); if (prvCtx == NULL || pubCtx == NULL) { goto EXIT; } // Set the curve parameters. ret = CRYPT_EAL_PkeySetParaById(prvCtx, id); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Set the private key of one end. prvKey.id = CRYPT_PKEY_ECDH; prvKey.key.eccPrv.len = sizeof(prikey); prvKey.key.eccPrv.data = prikey; ret = CRYPT_EAL_PkeySetPrv(prvCtx, &prvKey); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Set the curve parameters. ret = CRYPT_EAL_PkeySetParaById(pubCtx, id); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Set the public key of the other end. pubKey.id = CRYPT_PKEY_ECDH; pubKey.key.eccPub.len = sizeof(pubkey); pubKey.key.eccPub.data = pubkey; ret = CRYPT_EAL_PkeySetPub(pubCtx, &pubKey); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // The shared key involves only the X axis. The length of the public key is not compressed in the returned results. shareLen = CRYPT_EAL_PkeyGetKeyLen(prvCtx) / 2; shareKey = (uint8_t *)BSL_SAL_Malloc(shareLen); if (shareKey == NULL) { ret = CRYPT_MEM_ALLOC_FAIL; PrintLastError(); goto EXIT; } // Calculate the shared key. ret = CRYPT_EAL_PkeyComputeShareKey(prvCtx, pubCtx, shareKey, &shareLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Compare the calculation result with the expected one. if (shareLen != sizeof(resSharekey) || memcmp(shareKey, resSharekey, shareLen) != 0) { printf("failed to compare test results\n"); ret = -1; goto EXIT; } printf("pass \n"); EXIT: // Release the context memory. CRYPT_EAL_RandDeinit(); CRYPT_EAL_PkeyFreeCtx(prvCtx); CRYPT_EAL_PkeyFreeCtx(pubCtx); BSL_SAL_Free(shareKey); BSL_ERR_DeInit(); return 0; }
2401_83913325/openHiTLS-examples_2461
testcode/demo/ecdh.c
C
unknown
4,715
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "crypt_errno.h" #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_algid.h" #include "crypt_eal_md.h" #define PBKDF2_PARAM_LEN (4) void PrintLastError(void) { const char *file = NULL; uint32_t line = 0; BSL_ERR_GetErrorFileLine(&file, &line); printf("failed at file %s at line %d\n", file, line); } int main(void) { int ret = 0; CRYPT_EAL_MdCTX *ctx = NULL; uint8_t digest[32] = {0}; unsigned int digestLen = 32; uint8_t data[] = {0x1b, 0x50, 0x3f, 0xb9, 0xa7, 0x3b, 0x16, 0xad, 0xa3, 0xfc, 0xf1, 0x04, 0x26, 0x23, 0xae, 0x76, 0x10}; uint8_t expResult[] = {0xd5, 0xc3, 0x03, 0x15, 0xf7, 0x2e, 0xd0, 0x5f, 0xe5, 0x19, 0xa1, 0xbf, 0x75, 0xab, 0x5f, 0xd0, 0xff, 0xec, 0x5a, 0xc1, 0xac, 0xb0, 0xda, 0xf6, 0x6b, 0x6b, 0x76, 0x95, 0x98, 0x59, 0x45, 0x09}; ctx = CRYPT_EAL_MdNewCtx(CRYPT_MD_SHA256); if (ctx == NULL) { PrintLastError(); goto EXIT; } ret = CRYPT_EAL_MdInit(ctx); if (ret != 0) { PrintLastError(); goto EXIT; } ret = CRYPT_EAL_MdUpdate(ctx, data, sizeof(data)); if (ret != 0) { PrintLastError(); goto EXIT; } ret = CRYPT_EAL_MdFinal(ctx, digest, &digestLen); if (ret != 0) { PrintLastError(); goto EXIT; } printf("hash result: "); for (uint32_t i = 0; i < digestLen; i++) { printf("%02x", digest[i]); } printf("\n"); // result compare if (digestLen != sizeof(expResult) || memcmp(expResult, digest, digestLen) != 0) { printf("hash result comparison failed\n"); goto EXIT; } printf("pass \n"); EXIT: BSL_ERR_DeInit(); CRYPT_EAL_MdFreeCtx(ctx); return ret; }
2401_83913325/openHiTLS-examples_2461
testcode/demo/hash.c
C
unknown
2,355
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "crypt_errno.h" #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_algid.h" #include "crypt_eal_kdf.h" #include "bsl_params.h" #include "crypt_params_key.h" #define PBKDF2_PARAM_LEN (4) void PrintLastError(void) { const char *file = NULL; uint32_t line = 0; BSL_ERR_GetLastErrorFileLine(&file, &line); printf("failed at file %s at line %d\n", file, line); } int main(void) { int32_t ret; uint8_t key[] = {0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64}; uint8_t salt[] = {0x4e, 0x61, 0x43, 0x6c}; uint32_t iterations = 80000; uint8_t result[] = { 0x4d, 0xdc, 0xd8, 0xf6, 0x0b, 0x98, 0xbe, 0x21, 0x83, 0x0c, 0xee, 0x5e, 0xf2, 0x27, 0x01, 0xf9, 0x64, 0x1a, 0x44, 0x18, 0xd0, 0x4c, 0x04, 0x14, 0xae, 0xff, 0x08, 0x87, 0x6b, 0x34, 0xab, 0x56, 0xa1, 0xd4, 0x25, 0xa1, 0x22, 0x58, 0x33, 0x54, 0x9a, 0xdb, 0x84, 0x1b, 0x51, 0xc9, 0xb3, 0x17, 0x6a, 0x27, 0x2b, 0xde, 0xbb, 0xa1, 0xd0, 0x78, 0x47, 0x8f, 0x62, 0xb3, 0x97, 0xf3, 0x3c, 0x8d}; uint8_t out[sizeof(result)] = {0}; uint32_t outLen = sizeof(result); CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_PBKDF2); if (ctx == NULL) { PrintLastError(); goto EXIT; } CRYPT_MAC_AlgId id = CRYPT_MAC_HMAC_SHA256; BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END}; (void)BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &id, sizeof(id)); (void)BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, key, sizeof(key)); (void)BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, sizeof(salt)); (void)BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32, &iterations, sizeof(iterations)); ret = CRYPT_EAL_KdfSetParam(ctx, params); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } ret = CRYPT_EAL_KdfDerive(ctx, out, outLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } if (memcmp(out, result, sizeof(result)) != 0) { printf("failed to compare test results\n"); ret = -1; goto EXIT; } printf("pass \n"); EXIT: BSL_ERR_DeInit(); CRYPT_EAL_KdfFreeCtx(ctx); return ret; }
2401_83913325/openHiTLS-examples_2461
testcode/demo/pbkdf2.c
C
unknown
3,047
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include "auth_privpass_token.h" #include "auth_params.h" #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_eal_init.h" #include "crypt_eal_rand.h" #include "auth_errno.h" #include "crypt_errno.h" uint8_t pubKey[] = {0x30, 0x82, 0x01, 0x52, 0x30, 0x3d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0a, 0x30, 0x30, 0xa0, 0x0d, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0xa1, 0x1a, 0x30, 0x18, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x08, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0xa2, 0x03, 0x02, 0x01, 0x30, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xcb, 0x1a, 0xed, 0x6b, 0x6a, 0x95, 0xf5, 0xb1, 0xce, 0x01, 0x3a, 0x4c, 0xfc, 0xab, 0x25, 0xb9, 0x4b, 0x2e, 0x64, 0xa2, 0x30, 0x34, 0xe4, 0x25, 0x0a, 0x7e, 0xab, 0x43, 0xc0, 0xdf, 0x3a, 0x8c, 0x12, 0x99, 0x3a, 0xf1, 0x2b, 0x11, 0x19, 0x08, 0xd4, 0xb4, 0x71, 0xbe, 0xc3, 0x1d, 0x4b, 0x6c, 0x9a, 0xd9, 0xcd, 0xda, 0x90, 0x61, 0x2a, 0x2e, 0xe9, 0x03, 0x52, 0x3e, 0x6d, 0xe5, 0xa2, 0x24, 0xd6, 0xb0, 0x2f, 0x09, 0xe5, 0xc3, 0x74, 0xd0, 0xcf, 0xe0, 0x1d, 0x8f, 0x52, 0x9c, 0x50, 0x0a, 0x78, 0xa2, 0xf6, 0x79, 0x08, 0xfa, 0x68, 0x2b, 0x5a, 0x2b, 0x43, 0x0c, 0x81, 0xea, 0xf1, 0xaf, 0x72, 0xd7, 0xb5, 0xe7, 0x94, 0xfc, 0x98, 0xa3, 0x13, 0x92, 0x76, 0x87, 0x97, 0x57, 0xce, 0x45, 0x3b, 0x52, 0x6e, 0xf9, 0xbf, 0x6c, 0xeb, 0x99, 0x97, 0x9b, 0x84, 0x23, 0xb9, 0x0f, 0x44, 0x61, 0xa2, 0x2a, 0xf3, 0x7a, 0xab, 0x0c, 0xf5, 0x73, 0x3f, 0x75, 0x97, 0xab, 0xe4, 0x4d, 0x31, 0xc7, 0x32, 0xdb, 0x68, 0xa1, 0x81, 0xc6, 0xcb, 0xbe, 0x60, 0x7d, 0x8c, 0x0e, 0x52, 0xe0, 0x65, 0x5f, 0xd9, 0x99, 0x6d, 0xc5, 0x84, 0xec, 0xa0, 0xbe, 0x87, 0xaf, 0xbc, 0xd7, 0x8a, 0x33, 0x7d, 0x17, 0xb1, 0xdb, 0xa9, 0xe8, 0x28, 0xbb, 0xd8, 0x1e, 0x29, 0x13, 0x17, 0x14, 0x4e, 0x7f, 0xf8, 0x9f, 0x55, 0x61, 0x97, 0x09, 0xb0, 0x96, 0xcb, 0xb9, 0xea, 0x47, 0x4c, 0xea, 0xd2, 0x64, 0xc2, 0x07, 0x3f, 0xe4, 0x97, 0x40, 0xc0, 0x1f, 0x00, 0xe1, 0x09, 0x10, 0x60, 0x66, 0x98, 0x3d, 0x21, 0xe5, 0xf8, 0x3f, 0x08, 0x6e, 0x2e, 0x82, 0x3c, 0x87, 0x9c, 0xd4, 0x3c, 0xef, 0x70, 0x0d, 0x2a, 0x35, 0x2a, 0x9b, 0xab, 0xd6, 0x12, 0xd0, 0x3c, 0xad, 0x02, 0xdb, 0x13, 0x4b, 0x7e, 0x22, 0x5a, 0x5f, 0x02, 0x03, 0x01, 0x00, 0x01}; uint8_t privKey[] = {0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x42, 0x45, 0x47, 0x49, 0x4E, 0x20, 0x50, 0x52, 0x49, 0x56, 0x41, 0x54, 0x45, 0x20, 0x4B, 0x45, 0x59, 0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x0A, 0x4D, 0x49, 0x49, 0x45, 0x76, 0x51, 0x49, 0x42, 0x41, 0x44, 0x41, 0x4E, 0x42, 0x67, 0x6B, 0x71, 0x68, 0x6B, 0x69, 0x47, 0x39, 0x77, 0x30, 0x42, 0x41, 0x51, 0x45, 0x46, 0x41, 0x41, 0x53, 0x43, 0x42, 0x4B, 0x63, 0x77, 0x67, 0x67, 0x53, 0x6A, 0x41, 0x67, 0x45, 0x41, 0x41, 0x6F, 0x49, 0x42, 0x41, 0x51, 0x44, 0x4C, 0x47, 0x75, 0x31, 0x72, 0x61, 0x70, 0x58, 0x31, 0x73, 0x63, 0x34, 0x42, 0x0A, 0x4F, 0x6B, 0x7A, 0x38, 0x71, 0x79, 0x57, 0x35, 0x53, 0x79, 0x35, 0x6B, 0x6F, 0x6A, 0x41, 0x30, 0x35, 0x43, 0x55, 0x4B, 0x66, 0x71, 0x74, 0x44, 0x77, 0x4E, 0x38, 0x36, 0x6A, 0x42, 0x4B, 0x5A, 0x4F, 0x76, 0x45, 0x72, 0x45, 0x52, 0x6B, 0x49, 0x31, 0x4C, 0x52, 0x78, 0x76, 0x73, 0x4D, 0x64, 0x53, 0x32, 0x79, 0x61, 0x32, 0x63, 0x33, 0x61, 0x6B, 0x47, 0x45, 0x71, 0x4C, 0x75, 0x6B, 0x44, 0x0A, 0x55, 0x6A, 0x35, 0x74, 0x35, 0x61, 0x49, 0x6B, 0x31, 0x72, 0x41, 0x76, 0x43, 0x65, 0x58, 0x44, 0x64, 0x4E, 0x44, 0x50, 0x34, 0x42, 0x32, 0x50, 0x55, 0x70, 0x78, 0x51, 0x43, 0x6E, 0x69, 0x69, 0x39, 0x6E, 0x6B, 0x49, 0x2B, 0x6D, 0x67, 0x72, 0x57, 0x69, 0x74, 0x44, 0x44, 0x49, 0x48, 0x71, 0x38, 0x61, 0x39, 0x79, 0x31, 0x37, 0x58, 0x6E, 0x6C, 0x50, 0x79, 0x59, 0x6F, 0x78, 0x4F, 0x53, 0x0A, 0x64, 0x6F, 0x65, 0x58, 0x56, 0x38, 0x35, 0x46, 0x4F, 0x31, 0x4A, 0x75, 0x2B, 0x62, 0x39, 0x73, 0x36, 0x35, 0x6D, 0x58, 0x6D, 0x34, 0x51, 0x6A, 0x75, 0x51, 0x39, 0x45, 0x59, 0x61, 0x49, 0x71, 0x38, 0x33, 0x71, 0x72, 0x44, 0x50, 0x56, 0x7A, 0x50, 0x33, 0x57, 0x58, 0x71, 0x2B, 0x52, 0x4E, 0x4D, 0x63, 0x63, 0x79, 0x32, 0x32, 0x69, 0x68, 0x67, 0x63, 0x62, 0x4C, 0x76, 0x6D, 0x42, 0x39, 0x0A, 0x6A, 0x41, 0x35, 0x53, 0x34, 0x47, 0x56, 0x66, 0x32, 0x5A, 0x6C, 0x74, 0x78, 0x59, 0x54, 0x73, 0x6F, 0x4C, 0x36, 0x48, 0x72, 0x37, 0x7A, 0x58, 0x69, 0x6A, 0x4E, 0x39, 0x46, 0x37, 0x48, 0x62, 0x71, 0x65, 0x67, 0x6F, 0x75, 0x39, 0x67, 0x65, 0x4B, 0x52, 0x4D, 0x58, 0x46, 0x45, 0x35, 0x2F, 0x2B, 0x4A, 0x39, 0x56, 0x59, 0x5A, 0x63, 0x4A, 0x73, 0x4A, 0x62, 0x4C, 0x75, 0x65, 0x70, 0x48, 0x0A, 0x54, 0x4F, 0x72, 0x53, 0x5A, 0x4D, 0x49, 0x48, 0x50, 0x2B, 0x53, 0x58, 0x51, 0x4D, 0x41, 0x66, 0x41, 0x4F, 0x45, 0x4A, 0x45, 0x47, 0x42, 0x6D, 0x6D, 0x44, 0x30, 0x68, 0x35, 0x66, 0x67, 0x2F, 0x43, 0x47, 0x34, 0x75, 0x67, 0x6A, 0x79, 0x48, 0x6E, 0x4E, 0x51, 0x38, 0x37, 0x33, 0x41, 0x4E, 0x4B, 0x6A, 0x55, 0x71, 0x6D, 0x36, 0x76, 0x57, 0x45, 0x74, 0x41, 0x38, 0x72, 0x51, 0x4C, 0x62, 0x0A, 0x45, 0x30, 0x74, 0x2B, 0x49, 0x6C, 0x70, 0x66, 0x41, 0x67, 0x4D, 0x42, 0x41, 0x41, 0x45, 0x43, 0x67, 0x67, 0x45, 0x41, 0x4C, 0x7A, 0x43, 0x62, 0x64, 0x7A, 0x69, 0x31, 0x6A, 0x50, 0x64, 0x35, 0x38, 0x4D, 0x6B, 0x56, 0x2B, 0x43, 0x4C, 0x66, 0x79, 0x66, 0x53, 0x51, 0x32, 0x2B, 0x72, 0x66, 0x48, 0x6E, 0x72, 0x66, 0x72, 0x46, 0x65, 0x50, 0x2F, 0x56, 0x63, 0x44, 0x78, 0x72, 0x75, 0x69, 0x0A, 0x32, 0x70, 0x31, 0x61, 0x53, 0x58, 0x4A, 0x59, 0x69, 0x62, 0x65, 0x36, 0x45, 0x53, 0x2B, 0x4D, 0x62, 0x2F, 0x4D, 0x46, 0x55, 0x64, 0x6C, 0x48, 0x50, 0x67, 0x41, 0x4C, 0x77, 0x31, 0x78, 0x51, 0x34, 0x57, 0x65, 0x72, 0x66, 0x36, 0x63, 0x36, 0x44, 0x43, 0x73, 0x68, 0x6C, 0x6C, 0x78, 0x4C, 0x57, 0x53, 0x56, 0x38, 0x47, 0x73, 0x42, 0x73, 0x76, 0x63, 0x38, 0x6F, 0x36, 0x47, 0x50, 0x32, 0x0A, 0x63, 0x59, 0x36, 0x6F, 0x77, 0x70, 0x42, 0x44, 0x77, 0x63, 0x62, 0x61, 0x68, 0x47, 0x4B, 0x55, 0x6B, 0x50, 0x30, 0x45, 0x6B, 0x62, 0x39, 0x53, 0x30, 0x58, 0x4C, 0x4A, 0x57, 0x63, 0x47, 0x53, 0x47, 0x35, 0x61, 0x55, 0x6E, 0x48, 0x4A, 0x58, 0x52, 0x37, 0x69, 0x6E, 0x78, 0x34, 0x63, 0x5A, 0x6C, 0x66, 0x6F, 0x4C, 0x6E, 0x72, 0x45, 0x51, 0x65, 0x36, 0x68, 0x55, 0x78, 0x73, 0x4D, 0x71, 0x0A, 0x62, 0x30, 0x64, 0x48, 0x78, 0x64, 0x48, 0x44, 0x42, 0x4D, 0x64, 0x47, 0x66, 0x56, 0x57, 0x77, 0x67, 0x4B, 0x6F, 0x6A, 0x4F, 0x6A, 0x70, 0x53, 0x2F, 0x39, 0x38, 0x6D, 0x45, 0x55, 0x79, 0x37, 0x56, 0x42, 0x2F, 0x36, 0x61, 0x32, 0x6C, 0x72, 0x65, 0x67, 0x6C, 0x76, 0x6A, 0x63, 0x2F, 0x32, 0x6E, 0x4B, 0x43, 0x4B, 0x74, 0x59, 0x37, 0x37, 0x44, 0x37, 0x64, 0x54, 0x71, 0x6C, 0x47, 0x46, 0x0A, 0x78, 0x7A, 0x41, 0x42, 0x61, 0x57, 0x75, 0x38, 0x36, 0x4D, 0x43, 0x5A, 0x34, 0x2F, 0x51, 0x31, 0x33, 0x4C, 0x76, 0x2B, 0x42, 0x65, 0x66, 0x62, 0x71, 0x74, 0x49, 0x39, 0x73, 0x71, 0x5A, 0x5A, 0x77, 0x6A, 0x72, 0x64, 0x55, 0x68, 0x51, 0x48, 0x38, 0x56, 0x43, 0x78, 0x72, 0x79, 0x32, 0x51, 0x56, 0x4D, 0x51, 0x57, 0x51, 0x69, 0x6E, 0x57, 0x68, 0x41, 0x74, 0x36, 0x4D, 0x71, 0x54, 0x34, 0x0A, 0x53, 0x42, 0x53, 0x54, 0x72, 0x6F, 0x6C, 0x5A, 0x7A, 0x77, 0x72, 0x71, 0x6A, 0x65, 0x38, 0x4D, 0x50, 0x4A, 0x39, 0x31, 0x75, 0x61, 0x4E, 0x4D, 0x64, 0x58, 0x47, 0x4C, 0x63, 0x48, 0x4C, 0x49, 0x32, 0x36, 0x73, 0x58, 0x7A, 0x76, 0x37, 0x4B, 0x53, 0x51, 0x4B, 0x42, 0x67, 0x51, 0x44, 0x76, 0x63, 0x77, 0x73, 0x50, 0x55, 0x55, 0x76, 0x41, 0x39, 0x5A, 0x32, 0x5A, 0x58, 0x39, 0x58, 0x35, 0x0A, 0x6D, 0x49, 0x78, 0x4D, 0x54, 0x42, 0x4E, 0x64, 0x45, 0x46, 0x7A, 0x56, 0x62, 0x55, 0x50, 0x75, 0x4B, 0x4B, 0x41, 0x31, 0x79, 0x57, 0x6E, 0x31, 0x55, 0x4D, 0x44, 0x4E, 0x63, 0x55, 0x6A, 0x71, 0x68, 0x2B, 0x7A, 0x65, 0x2F, 0x37, 0x6B, 0x33, 0x79, 0x46, 0x78, 0x6B, 0x68, 0x30, 0x51, 0x46, 0x33, 0x31, 0x62, 0x71, 0x36, 0x30, 0x65, 0x4C, 0x39, 0x30, 0x47, 0x49, 0x53, 0x69, 0x41, 0x4F, 0x0A, 0x35, 0x4B, 0x4F, 0x57, 0x4D, 0x39, 0x45, 0x4B, 0x6F, 0x2B, 0x78, 0x41, 0x51, 0x32, 0x62, 0x61, 0x4B, 0x31, 0x4D, 0x66, 0x4F, 0x59, 0x31, 0x47, 0x2B, 0x38, 0x6A, 0x7A, 0x42, 0x58, 0x55, 0x70, 0x42, 0x73, 0x39, 0x34, 0x6B, 0x35, 0x33, 0x53, 0x38, 0x38, 0x79, 0x58, 0x6D, 0x4B, 0x36, 0x6E, 0x79, 0x64, 0x67, 0x76, 0x37, 0x30, 0x42, 0x4A, 0x38, 0x5A, 0x68, 0x35, 0x66, 0x6B, 0x55, 0x71, 0x0A, 0x57, 0x32, 0x30, 0x6F, 0x53, 0x62, 0x68, 0x6B, 0x68, 0x6A, 0x52, 0x64, 0x53, 0x7A, 0x48, 0x32, 0x6B, 0x52, 0x47, 0x69, 0x72, 0x67, 0x2B, 0x55, 0x53, 0x77, 0x4B, 0x42, 0x67, 0x51, 0x44, 0x5A, 0x4A, 0x4D, 0x6E, 0x72, 0x79, 0x32, 0x45, 0x78, 0x61, 0x2F, 0x33, 0x45, 0x71, 0x37, 0x50, 0x62, 0x6F, 0x73, 0x78, 0x41, 0x50, 0x4D, 0x69, 0x59, 0x6E, 0x6B, 0x35, 0x4A, 0x41, 0x50, 0x53, 0x47, 0x0A, 0x79, 0x32, 0x7A, 0x30, 0x5A, 0x37, 0x54, 0x55, 0x62, 0x2B, 0x75, 0x48, 0x51, 0x4F, 0x2F, 0x2B, 0x78, 0x50, 0x4D, 0x37, 0x6E, 0x43, 0x30, 0x75, 0x79, 0x4C, 0x49, 0x4D, 0x44, 0x39, 0x6C, 0x61, 0x54, 0x4D, 0x48, 0x77, 0x6E, 0x36, 0x73, 0x37, 0x2F, 0x4C, 0x62, 0x47, 0x6F, 0x45, 0x50, 0x31, 0x57, 0x52, 0x67, 0x70, 0x6F, 0x59, 0x48, 0x2F, 0x42, 0x31, 0x34, 0x6B, 0x2F, 0x52, 0x6E, 0x36, 0x0A, 0x66, 0x75, 0x77, 0x52, 0x4E, 0x36, 0x32, 0x49, 0x6F, 0x39, 0x74, 0x63, 0x39, 0x2B, 0x41, 0x43, 0x4C, 0x74, 0x55, 0x42, 0x37, 0x76, 0x74, 0x47, 0x61, 0x79, 0x33, 0x2B, 0x67, 0x52, 0x77, 0x59, 0x74, 0x53, 0x43, 0x32, 0x62, 0x35, 0x65, 0x64, 0x38, 0x6C, 0x49, 0x69, 0x65, 0x67, 0x74, 0x54, 0x6B, 0x65, 0x61, 0x30, 0x68, 0x30, 0x75, 0x44, 0x53, 0x52, 0x78, 0x41, 0x74, 0x56, 0x73, 0x33, 0x0A, 0x6E, 0x35, 0x6B, 0x79, 0x61, 0x32, 0x51, 0x39, 0x76, 0x51, 0x4B, 0x42, 0x67, 0x46, 0x4A, 0x75, 0x46, 0x7A, 0x4F, 0x5A, 0x74, 0x2B, 0x74, 0x67, 0x59, 0x6E, 0x57, 0x6E, 0x51, 0x55, 0x45, 0x67, 0x57, 0x38, 0x50, 0x30, 0x4F, 0x49, 0x4A, 0x45, 0x48, 0x4D, 0x45, 0x34, 0x55, 0x54, 0x64, 0x4F, 0x63, 0x77, 0x43, 0x78, 0x4B, 0x72, 0x48, 0x52, 0x72, 0x39, 0x33, 0x4A, 0x6A, 0x75, 0x46, 0x32, 0x0A, 0x45, 0x33, 0x77, 0x64, 0x4B, 0x6F, 0x54, 0x69, 0x69, 0x37, 0x50, 0x72, 0x77, 0x4F, 0x59, 0x49, 0x6F, 0x61, 0x4A, 0x54, 0x68, 0x70, 0x6A, 0x50, 0x63, 0x4A, 0x62, 0x62, 0x64, 0x62, 0x66, 0x4B, 0x79, 0x2B, 0x6E, 0x73, 0x51, 0x70, 0x31, 0x59, 0x47, 0x76, 0x39, 0x77, 0x64, 0x4A, 0x72, 0x4D, 0x61, 0x56, 0x77, 0x4A, 0x63, 0x76, 0x49, 0x70, 0x77, 0x56, 0x36, 0x76, 0x31, 0x55, 0x70, 0x66, 0x0A, 0x56, 0x74, 0x4C, 0x61, 0x64, 0x6D, 0x31, 0x6C, 0x6B, 0x6C, 0x76, 0x70, 0x71, 0x73, 0x36, 0x47, 0x4E, 0x4D, 0x38, 0x6A, 0x6E, 0x4D, 0x30, 0x58, 0x78, 0x33, 0x61, 0x6A, 0x6D, 0x6D, 0x6E, 0x66, 0x65, 0x57, 0x39, 0x79, 0x47, 0x58, 0x45, 0x35, 0x70, 0x68, 0x4D, 0x72, 0x7A, 0x4C, 0x4A, 0x6C, 0x39, 0x46, 0x30, 0x39, 0x63, 0x49, 0x32, 0x4C, 0x41, 0x6F, 0x47, 0x42, 0x41, 0x4E, 0x58, 0x76, 0x0A, 0x75, 0x67, 0x56, 0x58, 0x72, 0x70, 0x32, 0x62, 0x73, 0x54, 0x31, 0x6F, 0x6B, 0x64, 0x36, 0x75, 0x53, 0x61, 0x42, 0x73, 0x67, 0x70, 0x4A, 0x6A, 0x50, 0x65, 0x77, 0x4E, 0x52, 0x64, 0x33, 0x63, 0x5A, 0x4B, 0x39, 0x7A, 0x30, 0x61, 0x53, 0x50, 0x31, 0x44, 0x54, 0x41, 0x31, 0x50, 0x4E, 0x6B, 0x70, 0x65, 0x51, 0x77, 0x48, 0x67, 0x2F, 0x2B, 0x36, 0x66, 0x53, 0x61, 0x56, 0x4F, 0x48, 0x7A, 0x0A, 0x79, 0x41, 0x78, 0x44, 0x73, 0x39, 0x68, 0x35, 0x52, 0x72, 0x62, 0x78, 0x52, 0x61, 0x4E, 0x66, 0x73, 0x54, 0x2B, 0x72, 0x41, 0x55, 0x48, 0x37, 0x78, 0x31, 0x53, 0x59, 0x44, 0x56, 0x56, 0x51, 0x59, 0x56, 0x4D, 0x68, 0x55, 0x52, 0x62, 0x54, 0x6F, 0x5A, 0x65, 0x36, 0x47, 0x2F, 0x6A, 0x71, 0x6E, 0x54, 0x43, 0x33, 0x66, 0x4E, 0x66, 0x48, 0x56, 0x31, 0x78, 0x74, 0x5A, 0x66, 0x6F, 0x74, 0x0A, 0x30, 0x6C, 0x6F, 0x4D, 0x48, 0x67, 0x77, 0x65, 0x70, 0x36, 0x2B, 0x53, 0x49, 0x4D, 0x43, 0x6F, 0x65, 0x65, 0x32, 0x5A, 0x63, 0x74, 0x75, 0x5A, 0x56, 0x33, 0x32, 0x6C, 0x63, 0x49, 0x61, 0x66, 0x39, 0x72, 0x62, 0x48, 0x4F, 0x63, 0x37, 0x64, 0x41, 0x6F, 0x47, 0x41, 0x65, 0x51, 0x38, 0x6B, 0x38, 0x53, 0x49, 0x4C, 0x4E, 0x47, 0x36, 0x44, 0x4F, 0x41, 0x33, 0x31, 0x54, 0x45, 0x35, 0x50, 0x0A, 0x6D, 0x30, 0x31, 0x41, 0x4A, 0x49, 0x59, 0x77, 0x37, 0x41, 0x6C, 0x52, 0x33, 0x75, 0x6F, 0x2F, 0x52, 0x4E, 0x61, 0x43, 0x2B, 0x78, 0x59, 0x64, 0x50, 0x55, 0x33, 0x54, 0x73, 0x6B, 0x75, 0x41, 0x4C, 0x78, 0x78, 0x69, 0x44, 0x52, 0x2F, 0x57, 0x73, 0x4C, 0x45, 0x51, 0x42, 0x43, 0x6A, 0x6B, 0x46, 0x57, 0x6D, 0x6D, 0x4A, 0x41, 0x57, 0x6E, 0x51, 0x55, 0x44, 0x74, 0x62, 0x6E, 0x59, 0x4E, 0x0A, 0x53, 0x63, 0x77, 0x52, 0x38, 0x47, 0x32, 0x4A, 0x36, 0x46, 0x6E, 0x72, 0x45, 0x43, 0x74, 0x62, 0x74, 0x79, 0x73, 0x37, 0x33, 0x57, 0x41, 0x56, 0x47, 0x6F, 0x6F, 0x46, 0x5A, 0x6E, 0x63, 0x6D, 0x50, 0x4C, 0x50, 0x38, 0x6C, 0x78, 0x4C, 0x79, 0x62, 0x6C, 0x53, 0x42, 0x44, 0x45, 0x4C, 0x79, 0x61, 0x5A, 0x76, 0x2F, 0x62, 0x41, 0x73, 0x50, 0x6C, 0x4D, 0x4F, 0x39, 0x62, 0x44, 0x35, 0x63, 0x0A, 0x4A, 0x2B, 0x4E, 0x53, 0x42, 0x61, 0x61, 0x2B, 0x6F, 0x69, 0x4C, 0x6C, 0x31, 0x77, 0x6D, 0x43, 0x61, 0x35, 0x4D, 0x43, 0x66, 0x6C, 0x63, 0x3D, 0x0A, 0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x45, 0x4E, 0x44, 0x20, 0x50, 0x52, 0x49, 0x56, 0x41, 0x54, 0x45, 0x20, 0x4B, 0x45, 0x59, 0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x0A}; void PrintLastError(void) { const char *file = NULL; uint32_t line = 0; BSL_ERR_GetLastErrorFileLine(&file, &line); printf("failed at file %s at line %d\n", file, line); } void PrintHex(const uint8_t* data, uint32_t len) { for (uint32_t i = 0; i < len; i++) { printf("%02X", data[i]); if ((i + 1) % 16 == 0 && i + 1 < len) { printf("\n"); } else { printf(" "); } } printf("\n"); } int main(void) { int32_t ret = 1; HITLS_AUTH_PrivPassCtx *client = NULL; HITLS_AUTH_PrivPassCtx *issuer = NULL; HITLS_AUTH_PrivPassCtx *server = NULL; HITLS_AUTH_PrivPassToken *tokenChallenge = NULL; HITLS_AUTH_PrivPassToken *tokenRequest = NULL; HITLS_AUTH_PrivPassToken *tokenResponse = NULL; HITLS_AUTH_PrivPassToken *finalToken = NULL; uint8_t *tokenChallengeBuff = NULL; uint32_t tokenChallengeLen = 0; uint8_t *tokenRequestBuff = NULL; uint32_t tokenRequestLen = 0; uint8_t *tokenResponseBuff = NULL; uint32_t tokenResponseLen = 0; uint8_t *finalTokenBuff = NULL; uint32_t finalTokenLen = 0; // Construct parameter structure uint16_t tokenTypeValue = 0x0002; uint8_t issuerName[] = "Example Issuer"; uint8_t redemption[] = ""; // Length must be 0 or 32 uint8_t originInfo[] = "Example Origin"; BSL_Param param[5] = { {AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_TYPE, BSL_PARAM_TYPE_UINT16, &tokenTypeValue, 2, 2}, {AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_ISSUERNAME, BSL_PARAM_TYPE_OCTETS_PTR, issuerName, sizeof(issuerName), sizeof(issuerName)}, {AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_REDEMPTION, BSL_PARAM_TYPE_OCTETS_PTR, redemption, 0, 0}, {AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_ORIGININFO, BSL_PARAM_TYPE_OCTETS_PTR, originInfo, sizeof(originInfo), sizeof(originInfo)}, BSL_PARAM_END }; ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } client = HITLS_AUTH_PrivPassNewCtx(HITLS_AUTH_PRIVPASS_PUB_VERIFY_TOKENS); issuer = HITLS_AUTH_PrivPassNewCtx(HITLS_AUTH_PRIVPASS_PUB_VERIFY_TOKENS); server = HITLS_AUTH_PrivPassNewCtx(HITLS_AUTH_PRIVPASS_PUB_VERIFY_TOKENS); if (!client || !issuer || !server) { printf("Failed to create contexts\n"); PrintLastError(); goto EXIT; } // Set keys if (HITLS_AUTH_PrivPassSetPubkey(client, pubKey, sizeof(pubKey)) != HITLS_AUTH_SUCCESS || HITLS_AUTH_PrivPassSetPubkey(issuer, pubKey, sizeof(pubKey)) != HITLS_AUTH_SUCCESS || HITLS_AUTH_PrivPassSetPrvkey(issuer, NULL, privKey, sizeof(privKey)) != HITLS_AUTH_SUCCESS || HITLS_AUTH_PrivPassSetPubkey(server, pubKey, sizeof(pubKey)) != HITLS_AUTH_SUCCESS) { printf("Failed to set keys\n"); PrintLastError(); goto EXIT; } printf("\ntokenChallenge: server ------> client\n"); if (HITLS_AUTH_PrivPassGenTokenChallenge(server, param, &tokenChallenge) != HITLS_AUTH_SUCCESS) { printf("Failed to generate token challenge\n"); PrintLastError(); goto EXIT; } if (HITLS_AUTH_PrivPassSerialization(server, tokenChallenge, NULL, &tokenChallengeLen) != HITLS_AUTH_SUCCESS) { printf("Failed to serialize token challenge\n"); PrintLastError(); goto EXIT; } tokenChallengeBuff = BSL_SAL_Malloc(tokenChallengeLen); if (tokenChallengeBuff == NULL) { printf("Failed to allocate memory for token challenge\n"); PrintLastError(); goto EXIT; } if (HITLS_AUTH_PrivPassSerialization(server, tokenChallenge, tokenChallengeBuff, &tokenChallengeLen) != HITLS_AUTH_SUCCESS) { printf("Failed to serialize token challenge\n"); PrintLastError(); goto EXIT; } PrintHex(tokenChallengeBuff, tokenChallengeLen); printf("\ntokenRequest: client ------> issuer\n"); if (HITLS_AUTH_PrivPassGenTokenReq(client, tokenChallenge, &tokenRequest) != HITLS_AUTH_SUCCESS) { printf("Failed to generate token request\n"); PrintLastError(); goto EXIT; } if (HITLS_AUTH_PrivPassSerialization(client, tokenRequest, NULL, &tokenRequestLen) != HITLS_AUTH_SUCCESS) { printf("Failed to serialize token request\n"); PrintLastError(); goto EXIT; } tokenRequestBuff = BSL_SAL_Malloc(tokenRequestLen); if (tokenRequestBuff == NULL) { printf("Failed to allocate memory for token request\n"); PrintLastError(); goto EXIT; } if (HITLS_AUTH_PrivPassSerialization(client, tokenRequest, tokenRequestBuff, &tokenRequestLen) != HITLS_AUTH_SUCCESS) { printf("Failed to serialize token request\n"); PrintLastError(); goto EXIT; } PrintHex(tokenRequestBuff, tokenRequestLen); printf("\ntokenResponse: issuer ------> client\n"); if (HITLS_AUTH_PrivPassGenTokenResponse(issuer, tokenRequest, &tokenResponse) != HITLS_AUTH_SUCCESS) { printf("Failed to generate token response\n"); PrintLastError(); goto EXIT; } if (HITLS_AUTH_PrivPassSerialization(client, tokenResponse, NULL, &tokenResponseLen) != HITLS_AUTH_SUCCESS) { printf("Failed to serialize token response\n"); PrintLastError(); goto EXIT; } tokenResponseBuff = BSL_SAL_Malloc(tokenResponseLen); if (tokenResponseBuff == NULL) { printf("Failed to allocate memory for token response\n"); PrintLastError(); goto EXIT; } if (HITLS_AUTH_PrivPassSerialization(client, tokenResponse, tokenResponseBuff, &tokenResponseLen) != HITLS_AUTH_SUCCESS) { printf("Failed to serialize token response\n"); PrintLastError(); goto EXIT; } PrintHex(tokenResponseBuff, tokenResponseLen); printf("\nfinalToken: client ------> server\n"); if (HITLS_AUTH_PrivPassGenToken(client, tokenChallenge, tokenResponse, &finalToken) != HITLS_AUTH_SUCCESS) { printf("Failed to generate final token\n"); PrintLastError(); goto EXIT; } if (HITLS_AUTH_PrivPassSerialization(client, finalToken, NULL, &finalTokenLen) != HITLS_AUTH_SUCCESS) { printf("Failed to serialize final token\n"); PrintLastError(); goto EXIT; } finalTokenBuff = BSL_SAL_Malloc(finalTokenLen); if (finalTokenBuff == NULL) { printf("Failed to allocate memory for final token\n"); PrintLastError(); goto EXIT; } if (HITLS_AUTH_PrivPassSerialization(client, finalToken, finalTokenBuff, &finalTokenLen) != HITLS_AUTH_SUCCESS) { printf("Failed to serialize final token\n"); PrintLastError(); goto EXIT; } PrintHex(finalTokenBuff, finalTokenLen); printf("\nverifyToken: server\n"); if (HITLS_AUTH_PrivPassVerifyToken(server, tokenChallenge, finalToken) != HITLS_AUTH_SUCCESS) { printf("Token verification failed\n"); PrintLastError(); goto EXIT; } printf("Privacy pass public token verify process completed successfully!\n"); ret = HITLS_AUTH_SUCCESS; EXIT: HITLS_AUTH_PrivPassFreeToken(tokenChallenge); HITLS_AUTH_PrivPassFreeToken(tokenRequest); HITLS_AUTH_PrivPassFreeToken(tokenResponse); HITLS_AUTH_PrivPassFreeToken(finalToken); HITLS_AUTH_PrivPassFreeCtx(client); HITLS_AUTH_PrivPassFreeCtx(issuer); HITLS_AUTH_PrivPassFreeCtx(server); BSL_SAL_FREE(tokenChallengeBuff); BSL_SAL_FREE(tokenRequestBuff); BSL_SAL_FREE(tokenResponseBuff); BSL_SAL_FREE(finalTokenBuff); return ret; }
2401_83913325/openHiTLS-examples_2461
testcode/demo/privpass_token.c
C
unknown
20,588
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "securec.h" #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_algid.h" #include "crypt_eal_init.h" #include "crypt_eal_rand.h" #include "crypt_eal_pkey.h" #include "crypt_eal_codecs.h" #include "hitls_error.h" #include "hitls_config.h" #include "hitls.h" #include "hitls_cert_init.h" #include "hitls_cert.h" #include "hitls_crypt_init.h" #include "hitls_pki_cert.h" #include "crypt_errno.h" #define CERTS_PATH "../../../testcode/testdata/tls/certificate/der/ecdsa_sha256/" #define HTTP_BUF_MAXLEN (18 * 1024) /* 18KB */ int main(int32_t argc, char *argv[]) { int32_t exitValue = -1; int32_t ret = 0; HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; BSL_UIO *uio = NULL; int fd = 0; int infd = 0; HITLS_X509_Cert *rootCA = NULL; HITLS_X509_Cert *subCA = NULL; HITLS_X509_Cert *serverCert = NULL; CRYPT_EAL_PkeyCtx *pkey = NULL; ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_Init: error code is %x\n", ret); return -1; } HITLS_CertMethodInit(); HITLS_CryptMethodInit(); fd = socket(AF_INET, SOCK_STREAM, 0); if (fd == -1) { printf("Create socket failed.\n"); return -1; } int option = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)) < 0) { printf("setsockopt SO_REUSEADDR failed.\n"); goto EXIT; } struct sockaddr_in serverAddr; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(12345); serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(fd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) != 0) { printf("bind failed.\n"); goto EXIT; } if (listen(fd, 5) != 0) { printf("listen socket fail\n"); goto EXIT; } struct sockaddr_in clientAddr; unsigned int len = sizeof(struct sockaddr_in); infd = accept(fd, (struct sockaddr *)&clientAddr, &len); if (infd < 0) { printf("accept failed.\n"); goto EXIT; } config = HITLS_CFG_NewTLS12Config(); if (config == NULL) { printf("HITLS_CFG_NewTLS12Config failed.\n"); goto EXIT; } ret = HITLS_CFG_SetClientVerifySupport(config, false); // disable peer verify if (ret != HITLS_SUCCESS) { printf("Disable peer verify faild.\n"); goto EXIT; } /* 加载证书:需要用户实现 */ ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, CERTS_PATH "ca.der", &rootCA); if (ret != HITLS_SUCCESS) { printf("Parse ca failed.\n"); goto EXIT; } ret = HITLS_X509_CertParseFile(BSL_FORMAT_ASN1, CERTS_PATH "inter.der", &subCA); if (ret != HITLS_SUCCESS) { printf("Parse subca failed.\n"); goto EXIT; } HITLS_CFG_AddCertToStore(config, rootCA, TLS_CERT_STORE_TYPE_DEFAULT, true); HITLS_CFG_AddCertToStore(config, subCA, TLS_CERT_STORE_TYPE_DEFAULT, true); HITLS_CFG_LoadCertFile(config, CERTS_PATH "server.der", TLS_PARSE_FORMAT_ASN1); HITLS_CFG_LoadKeyFile(config, CERTS_PATH "server.key.der", TLS_PARSE_FORMAT_ASN1); /* 新建openHiTLS上下文 */ ctx = HITLS_New(config); if (ctx == NULL) { printf("HITLS_New failed.\n"); goto EXIT; } /* 用户可按需实现method */ uio = BSL_UIO_New(BSL_UIO_TcpMethod()); if (uio == NULL) { printf("BSL_UIO_New failed.\n"); goto EXIT; } ret = BSL_UIO_Ctrl(uio, BSL_UIO_SET_FD, (int32_t)sizeof(fd), &infd); if (ret != HITLS_SUCCESS) { BSL_UIO_Free(uio); printf("BSL_UIO_SET_FD failed, fd = %u.\n", fd); goto EXIT; } ret = HITLS_SetUio(ctx, uio); if (ret != HITLS_SUCCESS) { BSL_UIO_Free(uio); printf("HITLS_SetUio failed. ret = 0x%x.\n", ret); goto EXIT; } /* 进行TLS连接、用户需按实际场景考虑返回值 */ ret = HITLS_Accept(ctx); if (ret != HITLS_SUCCESS) { printf("HITLS_Accept failed, ret = 0x%x.\n", ret); goto EXIT; } /* 读取对端报文、用户需按实际场景考虑返回值 */ uint8_t readBuf[HTTP_BUF_MAXLEN + 1] = {0}; uint32_t readLen = 0; ret = HITLS_Read(ctx, readBuf, HTTP_BUF_MAXLEN, &readLen); if (ret != HITLS_SUCCESS) { printf("HITLS_Read failed, ret = 0x%x.\n", ret); goto EXIT; } printf("get from client size:%u :%s\n", readLen, readBuf); /* 向对端发送报文、用户需按实际场景考虑返回值 */ const uint8_t sndBuf[] = "Hi, this is server\n"; uint32_t writeLen = 0; ret = HITLS_Write(ctx, sndBuf, sizeof(sndBuf), &writeLen); if (ret != HITLS_SUCCESS) { printf("HITLS_Write error:error code:%d\n", ret); goto EXIT; } exitValue = 0; EXIT: HITLS_Close(ctx); HITLS_Free(ctx); HITLS_CFG_FreeConfig(config); close(fd); close(infd); HITLS_X509_CertFree(rootCA); HITLS_X509_CertFree(subCA); HITLS_X509_CertFree(serverCert); CRYPT_EAL_PkeyFreeCtx(pkey); BSL_UIO_Free(uio); return exitValue; }
2401_83913325/openHiTLS-examples_2461
testcode/demo/server.c
C
unknown
5,224
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "crypt_eal_pkey.h" // Header file of the interfaces for asymmetric encryption and decryption. #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_rand.h" #include "crypt_eal_init.h" #include "crypt_types.h" void *StdMalloc(uint32_t len) { return malloc((uint32_t)len); } void PrintLastError(void) { const char *file = NULL; uint32_t line = 0; BSL_ERR_GetLastErrorFileLine(&file, &line); printf("failed at file %s at line %d\n", file, line); } int main(void) { int32_t ret; ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } CRYPT_EAL_PkeyCtx *pkey = NULL; pkey = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SM2); if (pkey == NULL) { PrintLastError(); goto EXIT; } // Generate a key pair. ret = CRYPT_EAL_PkeyGen(pkey); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_PkeyGen: error code is %x\n", ret); PrintLastError(); goto EXIT; } // Data to be encrypted. char *data = "test enc data"; uint32_t dataLen = 12; uint8_t ecrypt[125] = {0}; uint32_t ecryptLen = 125; uint8_t dcrypt[125] = {0}; uint32_t dcryptLen = 125; // Encrypt data. ret = CRYPT_EAL_PkeyEncrypt(pkey, data, dataLen, ecrypt, &ecryptLen); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_PkeyEncrypt: error code is %x\n", ret); PrintLastError(); goto EXIT; } // Decrypt data. ret = CRYPT_EAL_PkeyDecrypt(pkey, ecrypt, ecryptLen, dcrypt, &dcryptLen); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_PkeyDecrypt: error code is %x\n", ret); PrintLastError(); goto EXIT; } if (memcmp(dcrypt, data, dataLen) == 0) { printf("encrypt and decrypt success\n"); } else { ret = -1; } EXIT: // Release the context memory. CRYPT_EAL_PkeyFreeCtx(pkey); CRYPT_EAL_RandDeinit(); BSL_ERR_DeInit(); return ret; }
2401_83913325/openHiTLS-examples_2461
testcode/demo/sm2enc.c
C
unknown
2,712
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "crypt_eal_pkey.h" // Header file for signature verification. #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_eal_rand.h" #include "crypt_eal_init.h" void PrintLastError(void) { const char *file = NULL; uint32_t line = 0; BSL_ERR_GetLastErrorFileLine(&file, &line);// Obtain the name and number of lines of the error file. printf("failed at file %s at line %d\n", file, line); } int main(void) { int ret; uint8_t userId[32] = {0}; uint8_t key[32] = {0}; uint8_t msg[32] = {0}; uint8_t signBuf[100] = {0}; uint32_t signLen = sizeof(signBuf); CRYPT_EAL_PkeyPrv prv = {0}; CRYPT_EAL_PkeyPub pub = {0}; CRYPT_EAL_PkeyCtx *ctx = NULL; ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); goto EXIT; } ctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_SM2); if (ctx == NULL) { goto EXIT; } // Set a user ID. ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, userId, sizeof(userId)); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Generate a key pair. ret = CRYPT_EAL_PkeyGen(ctx); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Sign. ret = CRYPT_EAL_PkeySign(ctx, CRYPT_MD_SM3, msg, sizeof(msg), signBuf, &signLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Verify the signature. ret = CRYPT_EAL_PkeyVerify(ctx, CRYPT_MD_SM3, msg, sizeof(msg), signBuf, signLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } printf("pass \n"); EXIT: // Release the context memory. CRYPT_EAL_PkeyFreeCtx(ctx); CRYPT_EAL_RandDeinit(); BSL_ERR_DeInit(); return ret; }
2401_83913325/openHiTLS-examples_2461
testcode/demo/sm2sign.c
C
unknown
2,679
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "crypt_eal_cipher.h" // Header file of the interfaces for symmetric encryption and decryption. #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_algid.h" // Algorithm ID list. #include "crypt_errno.h" // Error code list. void *StdMalloc(uint32_t len) { return malloc((size_t)len); } void PrintLastError(void) { const char *file = NULL; uint32_t line = 0; BSL_ERR_GetLastErrorFileLine(&file, &line); // Obtain the name and number of lines of the error file. printf("failed at file %s at line %d\n", file, line); } int main(void) { uint8_t data[10] = {0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x1c, 0x14}; uint8_t iv[16] = {0}; uint8_t key[16] = {0}; uint32_t dataLen = sizeof(data); uint8_t cipherText[100]; uint8_t plainText[100]; uint32_t outTotalLen = 0; uint32_t outLen = sizeof(cipherText); uint32_t cipherTextLen; int32_t ret; printf("plain text to be encrypted: "); for (uint32_t i = 0; i < dataLen; i++) { printf("%02x", data[i]); } printf("\n"); // Create a context. CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_SM4_CBC); if (ctx == NULL) { PrintLastError(); BSL_ERR_DeInit(); return 1; } /* * During initialization, the last input parameter can be true or false. true indicates encryption, * and false indicates decryption. */ ret = CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), true); if (ret != CRYPT_SUCCESS) { // Output the error code. You can find the error information in **crypt_errno.h** based on the error code. printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Set the padding mode. ret = CRYPT_EAL_CipherSetPadding(ctx, CRYPT_PADDING_PKCS7); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } /** * Enter the data to be calculated. This interface can be called for multiple times. * The input value of **outLen** is the length of the ciphertext, * and the output value is the amount of processed data. * */ ret = CRYPT_EAL_CipherUpdate(ctx, data, dataLen, cipherText, &outLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } outTotalLen += outLen; outLen = sizeof(cipherText) - outTotalLen; ret = CRYPT_EAL_CipherFinal(ctx, cipherText + outTotalLen, &outLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } outTotalLen += outLen; printf("cipher text value is: "); for (uint32_t i = 0; i < outTotalLen; i++) { printf("%02x", cipherText[i]); } printf("\n"); // Start decryption. cipherTextLen = outTotalLen; outTotalLen = 0; outLen = sizeof(plainText); // When initializing the decryption function, set the last input parameter to false. ret = CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), false); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Set the padding mode, which must be the same as that for encryption. ret = CRYPT_EAL_CipherSetPadding(ctx, CRYPT_PADDING_PKCS7); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Enter the ciphertext data. ret = CRYPT_EAL_CipherUpdate(ctx, cipherText, cipherTextLen, plainText, &outLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } outTotalLen += outLen; outLen = sizeof(plainText) - outTotalLen; // Decrypt the last segment of data and remove the filled content. ret = CRYPT_EAL_CipherFinal(ctx, plainText + outTotalLen, &outLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } outTotalLen += outLen; printf("decrypted plain text value is: "); for (uint32_t i = 0; i < outTotalLen; i++) { printf("%02x", plainText[i]); } printf("\n"); if (outTotalLen != dataLen || memcmp(plainText, data, dataLen) != 0) { printf("plaintext comparison failed\n"); goto EXIT; } printf("pass \n"); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); BSL_ERR_DeInit(); return ret; }
2401_83913325/openHiTLS-examples_2461
testcode/demo/sm4cbc.c
C
unknown
5,187
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "securec.h" #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_eal_init.h" #include "crypt_algid.h" #include "crypt_eal_rand.h" #include "hitls_error.h" #include "hitls_config.h" #include "hitls.h" #include "hitls_cert_init.h" #include "hitls_cert.h" #include "hitls_crypt_init.h" #include "hitls_pki_cert.h" #include "crypt_errno.h" #include "bsl_log.h" #define CERTS_PATH "../../../testcode/testdata/tls/certificate/der/sm2_with_userid/" #define HTTP_BUF_MAXLEN (18 * 1024) /* 18KB */ static int32_t HiTLSInit() { // Registration certificate, crypto callback int32_t ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_Init: error code is %x\n", ret); return -1; } HITLS_CertMethodInit(); HITLS_CryptMethodInit(); } int main(int32_t argc, char *argv[]) { int32_t exitValue = -1; int32_t ret = 0; int32_t port = 12345; HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; BSL_UIO *uio = NULL; int fd = 0; HITLS_X509_Cert *rootCA = NULL; HITLS_X509_Cert *subCA = NULL; if (HiTLSInit() != 0) { goto EXIT; } fd = socket(AF_INET, SOCK_STREAM, 0); if (fd == -1) { printf("Create socket failed.\n"); goto EXIT; } int option = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)) < 0) { close(fd); printf("setsockopt SO_REUSEADDR failed.\n"); goto EXIT; } // Set the protocol and port number struct sockaddr_in serverAddr; (void)memset_s(&serverAddr, sizeof(serverAddr), 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(port); serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); if (connect(fd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) != 0) { printf("connect failed.\n"); goto EXIT; } config = HITLS_CFG_NewTLCPConfig(); if (config == NULL) { printf("HITLS_CFG_NewTLS12Config failed.\n"); goto EXIT; } ret = HITLS_CFG_SetCheckKeyUsage(config, false); // disable cert keyusage check if (ret != HITLS_SUCCESS) { printf("Disable check KeyUsage failed.\n"); goto EXIT; } /* Load root certificate and intermediate certificate */ ret = HITLS_X509_CertParseFile(BSL_FORMAT_PEM, CERTS_PATH "ca.crt", &rootCA); if (ret != HITLS_SUCCESS) { printf("Parse ca failed.\n"); goto EXIT; } ret = HITLS_X509_CertParseFile(BSL_FORMAT_PEM, CERTS_PATH "inter.crt", &subCA); if (ret != HITLS_SUCCESS) { printf("Parse subca failed.\n"); goto EXIT; } HITLS_CFG_AddCertToStore(config, rootCA, TLS_CERT_STORE_TYPE_DEFAULT, true); HITLS_CFG_AddCertToStore(config, subCA, TLS_CERT_STORE_TYPE_DEFAULT, true); // Load signature certificate HITLS_CERT_X509 *signCert = NULL; HITLS_CERT_X509 *signPkey = NULL; signCert = HITLS_CFG_ParseCert(config, CERTS_PATH "sign.crt", strlen(CERTS_PATH "sign.crt"), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_PEM); if (signCert == NULL) { printf("Parse signCert failed.\n"); goto EXIT; } signPkey = HITLS_CFG_ParseKey(config, CERTS_PATH "sign.key", strlen(CERTS_PATH "sign.key"), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_PEM); if (signPkey == NULL) { printf("Parse signPkey failed.\n"); goto EXIT; } HITLS_CFG_SetTlcpCertificate(config, signCert, TLS_PARSE_FORMAT_ASN1, false); HITLS_CFG_SetTlcpPrivateKey(config, signPkey, TLS_PARSE_FORMAT_ASN1, false); // Load encryption certificate HITLS_CERT_X509 *encCert = NULL; HITLS_CERT_X509 *encPkey = NULL; encCert = HITLS_CFG_ParseCert(config, CERTS_PATH "enc.crt", strlen(CERTS_PATH "enc.crt"), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_PEM); if (encCert == NULL) { printf("Parse encCert failed.\n"); goto EXIT; } encPkey = HITLS_CFG_ParseKey(config, CERTS_PATH "enc.key", strlen(CERTS_PATH "enc.key"), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_PEM); if (encPkey == NULL) { printf("Parse encPkey failed.\n"); goto EXIT; } HITLS_CFG_SetTlcpCertificate(config, encCert, TLS_PARSE_FORMAT_ASN1, true); HITLS_CFG_SetTlcpPrivateKey(config, encPkey, TLS_PARSE_FORMAT_ASN1, true); /* Create a new openHiTLS ctx */ ctx = HITLS_New(config); if (ctx == NULL) { printf("HITLS_New failed.\n"); goto EXIT; } uio = BSL_UIO_New(BSL_UIO_TcpMethod()); if (uio == NULL) { printf("BSL_UIO_New failed.\n"); goto EXIT; } ret = BSL_UIO_Ctrl(uio, BSL_UIO_SET_FD, (int32_t)sizeof(fd), &fd); if (ret != HITLS_SUCCESS) { BSL_UIO_Free(uio); printf("BSL_UIO_SET_FD failed, fd = %u.\n", fd); goto EXIT; } ret = HITLS_SetUio(ctx, uio); if (ret != HITLS_SUCCESS) { BSL_UIO_Free(uio); printf("HITLS_SetUio failed. ret = 0x%x.\n", ret); goto EXIT; } /* To establish a TLS connection, users need to consider the return value based on the actual scenario */ ret = HITLS_Connect(ctx); if (ret != HITLS_SUCCESS) { printf("HITLS_Connect failed, ret = 0x%x.\n", ret); goto EXIT; } /* Sending messages to the other end, users need to consider the return value according to the actual scenario */ const uint8_t sndBuf[] = "Hi, this is tlcp client\n"; uint32_t writeLen = 0; ret = HITLS_Write(ctx, sndBuf, sizeof(sndBuf), &writeLen); if (ret != HITLS_SUCCESS) { printf("HITLS_Write error:error code:%d\n", ret); goto EXIT; } /* Read the message from the other end, and the user needs to consider the return value according to the actual scenario */ uint8_t readBuf[HTTP_BUF_MAXLEN + 1] = {0}; uint32_t readLen = 0; ret = HITLS_Read(ctx, readBuf, HTTP_BUF_MAXLEN, &readLen); if (ret != HITLS_SUCCESS) { printf("HITLS_Read failed, ret = 0x%x.\n", ret); goto EXIT; } printf("get from server size:%u :%s\n", readLen, readBuf); exitValue = 0; EXIT: HITLS_Close(ctx); HITLS_Free(ctx); HITLS_CFG_FreeConfig(config); close(fd); HITLS_X509_CertFree(rootCA); HITLS_X509_CertFree(subCA); BSL_UIO_Free(uio); return exitValue; }
2401_83913325/openHiTLS-examples_2461
testcode/demo/tlcp_client.c
C
unknown
6,480
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "securec.h" #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_algid.h" #include "crypt_eal_init.h" #include "crypt_eal_rand.h" #include "crypt_eal_pkey.h" #include "crypt_eal_codecs.h" #include "hitls_error.h" #include "hitls_config.h" #include "hitls.h" #include "hitls_cert_init.h" #include "hitls_cert.h" #include "hitls_crypt_init.h" #include "hitls_pki_cert.h" #include "crypt_errno.h" #include "bsl_log.h" #define CERTS_PATH "../../../testcode/testdata/tls/certificate/der/sm2_with_userid/" #define HTTP_BUF_MAXLEN (18 * 1024) /* 18KB */ static int32_t HiTLSInit() { // Registration certificate, crypto callback int32_t ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL); if (ret != CRYPT_SUCCESS) { printf("CRYPT_EAL_Init: error code is %x\n", ret); return -1; } HITLS_CertMethodInit(); HITLS_CryptMethodInit(); } int main(int32_t argc, char *argv[]) { int32_t exitValue = -1; int32_t ret = 0; int32_t port = 12345; HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; BSL_UIO *uio = NULL; int fd = 0; int infd = 0; HITLS_X509_Cert *rootCA = NULL; HITLS_X509_Cert *subCA = NULL; HITLS_X509_Cert *serverCert = NULL; CRYPT_EAL_PkeyCtx *pkey = NULL; if (HiTLSInit() != 0) { goto EXIT; } fd = socket(AF_INET, SOCK_STREAM, 0); if (fd == -1) { printf("Create socket failed.\n"); return -1; } int option = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)) < 0) { printf("setsockopt SO_REUSEADDR failed.\n"); goto EXIT; } struct sockaddr_in serverAddr; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(port); serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(fd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) != 0) { printf("bind failed.\n"); goto EXIT; } if (listen(fd, 5) != 0) { printf("listen socket fail\n"); goto EXIT; } struct sockaddr_in clientAddr; unsigned int len = sizeof(struct sockaddr_in); infd = accept(fd, (struct sockaddr *)&clientAddr, &len); if (infd < 0) { printf("accept failed.\n"); goto EXIT; } config = HITLS_CFG_NewTLCPConfig(); if (config == NULL) { printf("HITLS_CFG_NewTLS12Config failed.\n"); goto EXIT; } ret = HITLS_CFG_SetClientVerifySupport(config, false); // disable peer verify if (ret != HITLS_SUCCESS) { printf("Disable peer verify faild.\n"); goto EXIT; } /* Load root certificate and intermediate certificate */ ret = HITLS_X509_CertParseFile(BSL_FORMAT_PEM, CERTS_PATH "ca.crt", &rootCA); if (ret != HITLS_SUCCESS) { printf("Parse ca failed.\n"); goto EXIT; } ret = HITLS_X509_CertParseFile(BSL_FORMAT_PEM, CERTS_PATH "inter.crt", &subCA); if (ret != HITLS_SUCCESS) { printf("Parse subca failed.\n"); goto EXIT; } HITLS_CFG_AddCertToStore(config, rootCA, TLS_CERT_STORE_TYPE_DEFAULT, true); HITLS_CFG_AddCertToStore(config, subCA, TLS_CERT_STORE_TYPE_DEFAULT, true); // Load signature certificate HITLS_CERT_X509 *signCert = NULL; HITLS_CERT_X509 *signPkey = NULL; signCert = HITLS_CFG_ParseCert(config, CERTS_PATH "sign.crt", strlen(CERTS_PATH "sign.crt"), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_PEM); if (signCert == NULL) { printf("Parse signCert failed.\n"); goto EXIT; } signPkey = HITLS_CFG_ParseKey(config, CERTS_PATH "sign.key", strlen(CERTS_PATH "sign.key"), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_PEM); if (signPkey == NULL) { printf("Parse signPkey failed.\n"); goto EXIT; } HITLS_CFG_SetTlcpCertificate(config, signCert, TLS_PARSE_FORMAT_ASN1, false); HITLS_CFG_SetTlcpPrivateKey(config, signPkey, TLS_PARSE_FORMAT_ASN1, false); // Load encryption certificate HITLS_CERT_X509 *encCert = NULL; HITLS_CERT_X509 *encPkey = NULL; encCert = HITLS_CFG_ParseCert(config, CERTS_PATH "enc.crt", strlen(CERTS_PATH "enc.crt"), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_PEM); if (encCert == NULL) { printf("Parse encCert failed.\n"); goto EXIT; } encPkey = HITLS_CFG_ParseKey(config, CERTS_PATH "enc.key", strlen(CERTS_PATH "enc.key"), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_PEM); if (encPkey == NULL) { printf("Parse encPkey failed.\n"); goto EXIT; } HITLS_CFG_SetTlcpCertificate(config, encCert, TLS_PARSE_FORMAT_ASN1, true); HITLS_CFG_SetTlcpPrivateKey(config, encPkey, TLS_PARSE_FORMAT_ASN1, true); /* Create a new openHiTLS ctx */ ctx = HITLS_New(config); if (ctx == NULL) { printf("HITLS_New failed.\n"); goto EXIT; } /* Users can implement methods as needed */ uio = BSL_UIO_New(BSL_UIO_TcpMethod()); if (uio == NULL) { printf("BSL_UIO_New failed.\n"); goto EXIT; } ret = BSL_UIO_Ctrl(uio, BSL_UIO_SET_FD, (int32_t)sizeof(fd), &infd); if (ret != HITLS_SUCCESS) { BSL_UIO_Free(uio); printf("BSL_UIO_SET_FD failed, fd = %u.\n", fd); goto EXIT; } ret = HITLS_SetUio(ctx, uio); if (ret != HITLS_SUCCESS) { BSL_UIO_Free(uio); printf("HITLS_SetUio failed. ret = 0x%x.\n", ret); goto EXIT; } /* To establish a TLS connection, users need to consider the return value based on the actual scenario */ ret = HITLS_Accept(ctx); if (ret != HITLS_SUCCESS) { printf("HITLS_Accept failed, ret = 0x%x.\n", ret); goto EXIT; } /* Sending messages to the other end, users need to consider the return value according to the actual scenario */ uint8_t readBuf[HTTP_BUF_MAXLEN + 1] = {0}; uint32_t readLen = 0; ret = HITLS_Read(ctx, readBuf, HTTP_BUF_MAXLEN, &readLen); if (ret != HITLS_SUCCESS) { printf("HITLS_Read failed, ret = 0x%x.\n", ret); goto EXIT; } printf("get from client size:%u :%s\n", readLen, readBuf); /* Read the message from the other end, and the user needs to consider the return value according to the actual scenario */ const uint8_t sndBuf[] = "Hi, this is tlcp server\n"; uint32_t writeLen = 0; ret = HITLS_Write(ctx, sndBuf, sizeof(sndBuf), &writeLen); if (ret != HITLS_SUCCESS) { printf("HITLS_Write error:error code:%d\n", ret); goto EXIT; } exitValue = 0; EXIT: HITLS_Close(ctx); HITLS_Free(ctx); HITLS_CFG_FreeConfig(config); close(fd); close(infd); HITLS_X509_CertFree(rootCA); HITLS_X509_CertFree(subCA); HITLS_X509_CertFree(serverCert); CRYPT_EAL_PkeyFreeCtx(pkey); BSL_UIO_Free(uio); return exitValue; }
2401_83913325/openHiTLS-examples_2461
testcode/demo/tlcp_server.c
C
unknown
6,937
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdbool.h> #include "helper.h" #include "crypt_algid.h" #include "hitls_build.h" #include "crypto_test_util.h" #define ERR_ID (-1) typedef struct { int id; int offset; } MdAlgMap; static MdAlgMap g_mdAlgMap[] = { { CRYPT_MD_MD5, 0 }, { CRYPT_MD_SHA1, 1 }, { CRYPT_MD_SHA224, 2 }, { CRYPT_MD_SHA256, 3 }, { CRYPT_MD_SHA384, 4 }, { CRYPT_MD_SHA512, 5 }, { CRYPT_MD_SHA3_224, 6 }, { CRYPT_MD_SHA3_256, 7 }, { CRYPT_MD_SHA3_384, 8 }, { CRYPT_MD_SHA3_512, 9 }, { CRYPT_MD_SHAKE128, 10 }, { CRYPT_MD_SHAKE256, 11 }, { CRYPT_MD_SM3, 12 }, }; #define MD_ALG_MAP_CNT ((int)(sizeof(g_mdAlgMap) / sizeof(MdAlgMap))) // All MD algorithms are available by default. static int g_mdDisableTable[MD_ALG_MAP_CNT] = { 0 }; static bool g_isInitMd = false; static int g_avlRandAlg = -1; static bool g_isInitRandAlg = false; static void InitMdTable(void) { if (g_isInitMd) { return; } #ifndef HITLS_CRYPTO_MD5 g_mdDisableTable[0] = 1; #endif #ifndef HITLS_CRYPTO_SHA1 g_mdDisableTable[1] = 1; #endif #ifndef HITLS_CRYPTO_SHA224 g_mdDisableTable[2] = 1; #endif #ifndef HITLS_CRYPTO_SHA256 g_mdDisableTable[3] = 1; #endif #ifndef HITLS_CRYPTO_SHA384 g_mdDisableTable[4] = 1; #endif #ifndef HITLS_CRYPTO_SHA512 g_mdDisableTable[5] = 1; #endif #ifndef HITLS_CRYPTO_SHA3 g_mdDisableTable[6] = 1; g_mdDisableTable[7] = 1; g_mdDisableTable[8] = 1; g_mdDisableTable[9] = 1; g_mdDisableTable[10] = 1; g_mdDisableTable[11] = 1; #endif #ifndef HITLS_CRYPTO_SM3 g_mdDisableTable[12] = 1; #endif g_isInitMd = true; } static bool IsDrbgHashDisabled(void) { #ifdef HITLS_CRYPTO_DRBG_HASH return false; #else return true; #endif } static bool IsDrbgHmacDisabled(void) { #ifdef HITLS_CRYPTO_DRBG_HMAC return false; #else return true; #endif } static bool IsDrbgCtrDisabled(void) { #ifdef HITLS_CRYPTO_DRBG_CTR return false; #else return true; #endif } static bool IsDrbgCtrSm4Disabled() { #if defined(HITLS_CRYPTO_DRBG_CTR) && defined(HITLS_CRYPTO_DRBG_GM) && defined(HITLS_CRYPTO_SM4) return false; #else return true; #endif } static int GetDrbgHashAlgId(void) { InitMdTable(); // CRYPT_RAND_SHA256 is preferred (224 depends on 256). if (g_mdDisableTable[3] == 0) { return CRYPT_RAND_SHA256; } if (g_mdDisableTable[5] == 0) { return CRYPT_RAND_SHA512; } if (g_mdDisableTable[1] == 0) { return CRYPT_RAND_SHA1; } if (g_mdDisableTable[12] == 0) { return CRYPT_RAND_SM3; } return ERR_ID; } static int GetDrbgHmacAlgId(void) { InitMdTable(); if (g_mdDisableTable[3] == 0) { return CRYPT_RAND_HMAC_SHA256; } if (g_mdDisableTable[5] == 0) { return CRYPT_RAND_HMAC_SHA512; } if (g_mdDisableTable[1] == 0) { return CRYPT_RAND_HMAC_SHA1; } return ERR_ID; } bool IsMdAlgDisabled(int id) { InitMdTable(); bool res = false; // By default, this algorithm is not disabled. for (int i = 0; i < MD_ALG_MAP_CNT; i++) { if (id == g_mdAlgMap[i].id) { res = g_mdDisableTable[g_mdAlgMap[i].offset] == 1; break; } } return res; } bool IsHmacAlgDisabled(int id) { #ifdef HITLS_CRYPTO_HMAC InitMdTable(); switch (id) { case CRYPT_MAC_HMAC_MD5: return g_mdDisableTable[0] == 1; case CRYPT_MAC_HMAC_SHA1: return g_mdDisableTable[1] == 1; case CRYPT_MAC_HMAC_SHA224: return g_mdDisableTable[2] == 1; case CRYPT_MAC_HMAC_SHA256: return g_mdDisableTable[3] == 1; case CRYPT_MAC_HMAC_SHA384: return g_mdDisableTable[4] == 1; case CRYPT_MAC_HMAC_SHA512: return g_mdDisableTable[5] == 1; case CRYPT_MAC_HMAC_SHA3_224: return g_mdDisableTable[6] == 1; case CRYPT_MAC_HMAC_SHA3_256: return g_mdDisableTable[7] == 1; case CRYPT_MAC_HMAC_SHA3_384: return g_mdDisableTable[8] == 1; case CRYPT_MAC_HMAC_SHA3_512: return g_mdDisableTable[9] == 1; case CRYPT_MAC_HMAC_SM3: return g_mdDisableTable[12] == 1; default: return false; } #else (void)id; return false; #endif } bool IsMacAlgDisabled(int id) { switch (id) { case CRYPT_MAC_HMAC_MD5: case CRYPT_MAC_HMAC_SHA1: case CRYPT_MAC_HMAC_SHA224: case CRYPT_MAC_HMAC_SHA256: case CRYPT_MAC_HMAC_SHA384: case CRYPT_MAC_HMAC_SHA512: case CRYPT_MAC_HMAC_SM3: return IsHmacAlgDisabled(id); case CRYPT_MAC_CBC_MAC_SM4: #ifdef HITLS_CRYPTO_CBC_MAC return false; #else return true; #endif default: return false; } } bool IsDrbgHashAlgDisabled(int id) { if (IsDrbgHashDisabled()) { return true; } InitMdTable(); switch (id) { case CRYPT_RAND_SHA1: return g_mdDisableTable[1] == 1; case CRYPT_RAND_SHA224: return g_mdDisableTable[2] == 1; case CRYPT_RAND_SHA256: return g_mdDisableTable[3] == 1; case CRYPT_RAND_SHA384: return g_mdDisableTable[4] == 1; case CRYPT_RAND_SHA512: return g_mdDisableTable[5] == 1; case CRYPT_RAND_SM3: #ifdef HITLS_CRYPTO_DRBG_GM return g_mdDisableTable[12] == 1; #else return true; #endif default: return false; } } bool IsDrbgHmacAlgDisabled(int id) { if (IsDrbgHmacDisabled()) { return true; } InitMdTable(); switch (id) { case CRYPT_RAND_HMAC_SHA1: return g_mdDisableTable[1] == 1; case CRYPT_RAND_HMAC_SHA224: return g_mdDisableTable[2] == 1; case CRYPT_RAND_HMAC_SHA256: return g_mdDisableTable[3] == 1; case CRYPT_RAND_HMAC_SHA384: return g_mdDisableTable[4] == 1; case CRYPT_RAND_HMAC_SHA512: return g_mdDisableTable[5] == 1; default: return false; } } int GetAvailableRandAlgId(void) { if (g_isInitRandAlg) { return g_avlRandAlg; } g_isInitRandAlg = true; if (!IsDrbgHashDisabled()) { g_avlRandAlg = GetDrbgHashAlgId(); if (g_avlRandAlg != ERR_ID) { return g_avlRandAlg; } } if (!IsDrbgHmacDisabled()) { g_avlRandAlg = GetDrbgHmacAlgId(); if (g_avlRandAlg != ERR_ID) { return g_avlRandAlg; } } if (!IsDrbgCtrDisabled()) { g_avlRandAlg = CRYPT_RAND_AES256_CTR; return g_avlRandAlg; } return g_avlRandAlg; } bool IsRandAlgDisabled(int id) { switch (id) { case CRYPT_RAND_SHA1: case CRYPT_RAND_SHA224: case CRYPT_RAND_SHA256: case CRYPT_RAND_SHA384: case CRYPT_RAND_SHA512: case CRYPT_RAND_SM3: return IsDrbgHashAlgDisabled(id); case CRYPT_RAND_HMAC_SHA1: case CRYPT_RAND_HMAC_SHA224: case CRYPT_RAND_HMAC_SHA256: case CRYPT_RAND_HMAC_SHA384: case CRYPT_RAND_HMAC_SHA512: return IsDrbgHmacAlgDisabled(id); case CRYPT_RAND_AES128_CTR: case CRYPT_RAND_AES192_CTR: case CRYPT_RAND_AES256_CTR: case CRYPT_RAND_AES128_CTR_DF: case CRYPT_RAND_AES192_CTR_DF: case CRYPT_RAND_AES256_CTR_DF: return IsDrbgCtrDisabled(); case CRYPT_RAND_SM4_CTR_DF: return IsDrbgCtrSm4Disabled(); default: return false; } return false; } bool IsAesAlgDisabled(int id) { #ifdef HITLS_CRYPTO_AES switch (id) { #ifndef HITLS_CRYPTO_CBC case CRYPT_CIPHER_AES128_CBC: case CRYPT_CIPHER_AES192_CBC: case CRYPT_CIPHER_AES256_CBC: return true; #endif #ifndef HITLS_CRYPTO_ECB case CRYPT_CIPHER_AES128_ECB: case CRYPT_CIPHER_AES192_ECB: case CRYPT_CIPHER_AES256_ECB: return true; #endif #ifndef HITLS_CRYPTO_CTR case CRYPT_CIPHER_AES128_CTR: case CRYPT_CIPHER_AES192_CTR: case CRYPT_CIPHER_AES256_CTR: return true; #endif #ifndef HITLS_CRYPTO_CCM case CRYPT_CIPHER_AES128_CCM: case CRYPT_CIPHER_AES192_CCM: case CRYPT_CIPHER_AES256_CCM: return true; #endif #ifndef HITLS_CRYPTO_GCM case CRYPT_CIPHER_AES128_GCM: case CRYPT_CIPHER_AES192_GCM: case CRYPT_CIPHER_AES256_GCM: return true; #endif #ifndef HITLS_CRYPTO_CFB case CRYPT_CIPHER_AES128_CFB: case CRYPT_CIPHER_AES192_CFB: case CRYPT_CIPHER_AES256_CFB: return true; #endif #ifndef HITLS_CRYPTO_OFB case CRYPT_CIPHER_AES128_OFB: case CRYPT_CIPHER_AES192_OFB: case CRYPT_CIPHER_AES256_OFB: return true; #endif #ifndef HITLS_CRYPTO_XTS case CRYPT_CIPHER_AES128_XTS: case CRYPT_CIPHER_AES256_XTS: return true; #endif default: return false; // Unsupported algorithm ID } #else (void)id; return true; #endif } bool IsSm4AlgDisabled(int id) { #ifdef HITLS_CRYPTO_SM4 switch (id) { #ifndef HITLS_CRYPTO_XTS case CRYPT_CIPHER_SM4_XTS: return true; #endif #ifndef HITLS_CRYPTO_CBC case CRYPT_CIPHER_SM4_CBC: return true; #endif #ifndef HITLS_CRYPTO_ECB case CRYPT_CIPHER_SM4_ECB: return true; #endif #ifndef HITLS_CRYPTO_CTR case CRYPT_CIPHER_SM4_CTR: return true; #endif #ifndef HITLS_CRYPTO_GCM case CRYPT_CIPHER_SM4_GCM: return true; #endif #ifndef HITLS_CRYPTO_CFB case CRYPT_CIPHER_SM4_CFB: return true; #endif #ifndef HITLS_CRYPTO_OFB case CRYPT_CIPHER_SM4_OFB: return true; #endif default: return false; // Unsupported algorithm ID } #else (void)id; return true; #endif } bool IsCipherAlgDisabled(int id) { switch (id) { case CRYPT_CIPHER_AES128_CBC: case CRYPT_CIPHER_AES192_CBC: case CRYPT_CIPHER_AES256_CBC: case CRYPT_CIPHER_AES128_CTR: case CRYPT_CIPHER_AES192_CTR: case CRYPT_CIPHER_AES256_CTR: case CRYPT_CIPHER_AES128_CCM: case CRYPT_CIPHER_AES192_CCM: case CRYPT_CIPHER_AES256_CCM: case CRYPT_CIPHER_AES128_GCM: case CRYPT_CIPHER_AES192_GCM: case CRYPT_CIPHER_AES256_GCM: case CRYPT_CIPHER_AES128_CFB: case CRYPT_CIPHER_AES192_CFB: case CRYPT_CIPHER_AES256_CFB: case CRYPT_CIPHER_AES128_OFB: case CRYPT_CIPHER_AES192_OFB: case CRYPT_CIPHER_AES256_OFB: return IsAesAlgDisabled(id); case CRYPT_CIPHER_CHACHA20_POLY1305: #if !defined(HITLS_CRYPTO_CHACHA20) && !defined(HITLS_CRYPTO_CHACHA20POLY1305) return true; #else return false; #endif case CRYPT_CIPHER_SM4_XTS: case CRYPT_CIPHER_SM4_CBC: case CRYPT_CIPHER_SM4_CTR: case CRYPT_CIPHER_SM4_GCM: case CRYPT_CIPHER_SM4_CFB: case CRYPT_CIPHER_SM4_OFB: return IsSm4AlgDisabled(id); default: return false; } } bool IsCmacAlgDisabled(int id) { #ifdef HITLS_CRYPTO_CMAC switch (id) { #ifndef HITLS_CRYPTO_CMAC_AES case CRYPT_MAC_CMAC_AES128: case CRYPT_MAC_CMAC_AES192: case CRYPT_MAC_CMAC_AES256: return true; #endif #ifndef HITLS_CRYPTO_CMAC_SM4 case CRYPT_MAC_CMAC_SM4: return true; #endif default: return false; // Unsupported algorithm ID } #else (void)id; return true; #endif } bool IsCurveDisabled(int eccId) { switch (eccId) { #ifdef HITLS_CRYPTO_CURVE_NISTP224 case CRYPT_ECC_NISTP224: return false; #endif #ifdef HITLS_CRYPTO_CURVE_NISTP256 case CRYPT_ECC_NISTP256: return false; #endif #ifdef HITLS_CRYPTO_CURVE_NISTP384 case CRYPT_ECC_NISTP384: return false; #endif #ifdef HITLS_CRYPTO_CURVE_NISTP521 case CRYPT_ECC_NISTP521: return false; #endif #ifdef HITLS_CRYPTO_CURVE_BP256R1 case CRYPT_ECC_BRAINPOOLP256R1: return false; #endif #ifdef HITLS_CRYPTO_CURVE_BP384R1 case CRYPT_ECC_BRAINPOOLP384R1: return false; #endif #ifdef HITLS_CRYPTO_CURVE_BP512R1 case CRYPT_ECC_BRAINPOOLP512R1: return false; #endif #ifdef HITLS_CRYPTO_CURVE_192WAPI case CRYPT_ECC_192WAPI: return false; #endif default: return true; } } bool IsCurve25519AlgDisabled(int id) { if (id == CRYPT_PKEY_ED25519) { #ifndef HITLS_CRYPTO_ED25519 return true; #else return false; #endif } if (id == CRYPT_PKEY_X25519) { #ifndef HITLS_CRYPTO_X25519 return true; #else return false; #endif } return false; // Unsupported algorithm ID }
2401_83913325/openHiTLS-examples_2461
testcode/framework/crypto/alg_check.c
C
unknown
13,604
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdint.h> #include <pthread.h> #include <unistd.h> #include <fcntl.h> #include "hitls_build.h" #include "bsl_sal.h" #include "bsl_errno.h" #include "crypt_errno.h" #include "crypt_types.h" #include "crypt_eal_md.h" #include "eal_md_local.h" #include "crypt_eal_rand.h" #include "crypt_eal_mac.h" #include "crypt_eal_init.h" #include "test.h" #include "helper.h" #include "crypto_test_util.h" #include "securec.h" #include "crypt_util_rand.h" #ifndef HITLS_BSL_SAL_MEM void *TestMalloc(uint32_t len) { return malloc((size_t)len); } #endif void TestMemInit(void) { #ifdef HITLS_BSL_SAL_MEM return; #else BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_MALLOC, TestMalloc); BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_FREE, free); #endif } #if defined(HITLS_CRYPTO_EAL) && defined(HITLS_CRYPTO_DRBG) typedef struct { CRYPT_Data *entropy; CRYPT_Data *nonce; CRYPT_Data *pers; CRYPT_Data *addin1; CRYPT_Data *entropyPR1; CRYPT_Data *addin2; CRYPT_Data *entropyPR2; CRYPT_Data *retBits; } DRBG_Vec_t; #ifndef HITLS_CRYPTO_ENTROPY static int32_t GetEntropy(void *ctx, CRYPT_Data *entropy, uint32_t strength, CRYPT_Range *lenRange) { if (lenRange == NULL) { Print("getEntropy Error lenRange NULL\n"); return CRYPT_NULL_INPUT; } if (ctx == NULL || entropy == NULL) { Print("getEntropy Error\n"); lenRange->max = strength; return CRYPT_NULL_INPUT; } DRBG_Vec_t *seedCtx = (DRBG_Vec_t *)ctx; entropy->data = seedCtx->entropy->data; entropy->len = seedCtx->entropy->len; return CRYPT_SUCCESS; } static void CleanEntropy(void *ctx, CRYPT_Data *entropy) { (void)ctx; (void)entropy; return; } #endif int32_t TestSimpleRand(uint8_t *buff, uint32_t len) { int rand = open("/dev/urandom", O_RDONLY); if (rand < 0) { printf("open /dev/urandom failed.\n"); return -1; } int l = read(rand, buff, len); if (l < 0) { printf("read from /dev/urandom failed. errno: %d.\n", errno); close(rand); return -1; } close(rand); return 0; } int32_t TestSimpleRandEx(void *libCtx, uint8_t *buff, uint32_t len) { (void)libCtx; return TestSimpleRand(buff, len); } int TestRandInitEx(void *libCtx) { (void)libCtx; int drbgAlgId = GetAvailableRandAlgId(); int32_t ret; if (drbgAlgId == -1) { Print("Drbg algs are disabled."); return CRYPT_NOT_SUPPORT; } #ifndef HITLS_CRYPTO_ENTROPY CRYPT_RandSeedMethod seedMeth = {GetEntropy, CleanEntropy, NULL, NULL}; uint8_t entropy[64] = {0}; CRYPT_Data tempEntropy = {entropy, sizeof(entropy)}; DRBG_Vec_t seedCtx = {0}; seedCtx.entropy = &tempEntropy; #endif #ifdef HITLS_CRYPTO_PROVIDER #ifndef HITLS_CRYPTO_ENTROPY BSL_Param param[4] = {0}; (void)BSL_PARAM_InitValue(&param[0], CRYPT_PARAM_RAND_SEEDCTX, BSL_PARAM_TYPE_CTX_PTR, &seedCtx, 0); (void)BSL_PARAM_InitValue(&param[1], CRYPT_PARAM_RAND_SEED_GETENTROPY, BSL_PARAM_TYPE_FUNC_PTR, seedMeth.getEntropy, 0); (void)BSL_PARAM_InitValue(&param[2], CRYPT_PARAM_RAND_SEED_CLEANENTROPY, BSL_PARAM_TYPE_FUNC_PTR, seedMeth.cleanEntropy, 0); ret = CRYPT_EAL_ProviderRandInitCtx(NULL, (CRYPT_RAND_AlgId)drbgAlgId, "provider=default", NULL, 0, param); #else ret = CRYPT_EAL_ProviderRandInitCtx(libCtx, (CRYPT_RAND_AlgId)drbgAlgId, "provider=default", NULL, 0, NULL); #endif #else #ifndef HITLS_CRYPTO_ENTROPY ret = CRYPT_EAL_RandInit(drbgAlgId, &seedMeth, (void *)&seedCtx, NULL, 0); #else ret = CRYPT_EAL_RandInit(drbgAlgId, NULL, NULL, NULL, 0); #endif #endif if (ret == CRYPT_EAL_ERR_DRBG_REPEAT_INIT) { ret = CRYPT_SUCCESS; } return ret; } int TestRandInit(void) { return TestRandInitEx(NULL); } void TestRandDeInit(void) { #ifdef HITLS_CRYPTO_PROVIDER CRYPT_EAL_RandDeinitEx(NULL); #else CRYPT_EAL_RandDeinit(); #endif } #endif #if defined(HITLS_CRYPTO_EAL) && defined(HITLS_CRYPTO_MAC) uint32_t TestGetMacLen(int algId) { switch (algId) { case CRYPT_MAC_HMAC_MD5: return 16; case CRYPT_MAC_HMAC_SHA1: return 20; case CRYPT_MAC_HMAC_SHA224: case CRYPT_MAC_HMAC_SHA3_224: return 28; case CRYPT_MAC_HMAC_SHA256: case CRYPT_MAC_HMAC_SHA3_256: return 32; case CRYPT_MAC_HMAC_SHA384: case CRYPT_MAC_HMAC_SHA3_384: return 48; case CRYPT_MAC_HMAC_SHA512: case CRYPT_MAC_HMAC_SHA3_512: return 64; case CRYPT_MAC_HMAC_SM3: return 32; case CRYPT_MAC_CMAC_AES128: case CRYPT_MAC_CMAC_AES192: case CRYPT_MAC_CMAC_AES256: return 16; // AES block size case CRYPT_MAC_CMAC_SM4: return 16;// SM4 block size case CRYPT_MAC_CBC_MAC_SM4: return 16;// SM4 block size case CRYPT_MAC_SIPHASH64: return 8; case CRYPT_MAC_SIPHASH128: return 16; default: return 0; } } void TestMacSameAddr(int algId, Hex *key, Hex *data, Hex *mac) { uint32_t outLen = data->len > mac->len ? data->len : mac->len; uint8_t out[outLen]; CRYPT_EAL_MacCtx *ctx = NULL; int padType = CRYPT_PADDING_ZEROS; ASSERT_EQ(memcpy_s(out, outLen, data->x, data->len), 0); TestMemInit(); ASSERT_TRUE((ctx = CRYPT_EAL_MacNewCtx(algId)) != NULL); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, key->x, key->len), CRYPT_SUCCESS); if (algId == CRYPT_MAC_CBC_MAC_SM4) { ASSERT_EQ(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padType, sizeof(int)), CRYPT_SUCCESS); } ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, out, data->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, out, &outLen), CRYPT_SUCCESS); ASSERT_COMPARE("mac result cmp", out, outLen, mac->x, mac->len); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } void TestMacAddrNotAlign(int algId, Hex *key, Hex *data, Hex *mac) { uint32_t outLen = data->len > mac->len ? data->len : mac->len; uint8_t out[outLen]; CRYPT_EAL_MacCtx *ctx = NULL; int padType = CRYPT_PADDING_ZEROS; uint8_t keyTmp[key->len + 1] __attribute__((aligned(8))); uint8_t dataTmp[data->len + 1] __attribute__((aligned(8))); uint8_t *pKey = keyTmp + 1; uint8_t *pData = dataTmp + 1; ASSERT_TRUE(memcpy_s(pKey, key->len, key->x, key->len) == EOK); ASSERT_TRUE(memcpy_s(pData, data->len, data->x, data->len) == EOK); TestMemInit(); ASSERT_TRUE((ctx = CRYPT_EAL_MacNewCtx(algId)) != NULL); ASSERT_EQ(CRYPT_EAL_MacInit(ctx, pKey, key->len), CRYPT_SUCCESS); if (algId == CRYPT_MAC_CBC_MAC_SM4) { ASSERT_EQ(CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padType, sizeof(int)), CRYPT_SUCCESS); } ASSERT_EQ(CRYPT_EAL_MacUpdate(ctx, pData, data->len), CRYPT_SUCCESS); ASSERT_EQ(CRYPT_EAL_MacFinal(ctx, out, &outLen), CRYPT_SUCCESS); ASSERT_COMPARE("mac result cmp", out, outLen, mac->x, mac->len); EXIT: CRYPT_EAL_MacFreeCtx(ctx); } #endif #ifdef HITLS_CRYPTO_CIPHER CRYPT_EAL_CipherCtx *TestCipherNewCtx(CRYPT_EAL_LibCtx *libCtx, int32_t id, const char *attrName, int isProvider) { #ifdef HITLS_CRYPTO_PROVIDER if (isProvider == 1) { if (CRYPT_EAL_Init(0) != CRYPT_SUCCESS) { return NULL; } return CRYPT_EAL_ProviderCipherNewCtx(libCtx, id, attrName); } else { return CRYPT_EAL_CipherNewCtx(id); } #else (void)libCtx; (void)attrName; (void)isProvider; return CRYPT_EAL_CipherNewCtx(id); #endif } #endif #ifdef HITLS_CRYPTO_PKEY CRYPT_EAL_PkeyCtx *TestPkeyNewCtx( CRYPT_EAL_LibCtx *libCtx, int32_t id, uint32_t operType, const char *attrName, int isProvider) { #ifdef HITLS_CRYPTO_PROVIDER if (isProvider == 1) { #ifdef HITLS_CRYPTO_EALINIT if (CRYPT_EAL_Init(0) != CRYPT_SUCCESS) { return NULL; } #endif return CRYPT_EAL_ProviderPkeyNewCtx(libCtx, id, operType, attrName); } else { return CRYPT_EAL_PkeyNewCtx(id); } #else (void)libCtx; (void)operType; (void)attrName; (void)isProvider; return CRYPT_EAL_PkeyNewCtx(id); #endif } #endif
2401_83913325/openHiTLS-examples_2461
testcode/framework/crypto/crypto_test_util.c
C
unknown
8,760
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CRYPTO_TEST_UTIL_H #define CRYPTO_TEST_UTIL_H #include "hitls_build.h" #include "crypt_eal_cipher.h" #include "crypt_eal_pkey.h" #ifdef __cplusplus extern "C" { #endif void TestMemInit(void); int TestRandInit(void); int TestRandInitEx(void *libCtx); void TestRandDeInit(void); bool IsMdAlgDisabled(int id); bool IsHmacAlgDisabled(int id); bool IsMacAlgDisabled(int id); bool IsDrbgHashAlgDisabled(int id); bool IsDrbgHmacAlgDisabled(int id); int GetAvailableRandAlgId(void); bool IsRandAlgDisabled(int id); bool IsAesAlgDisabled(int id); bool IsSm4AlgDisabled(int id); bool IsCipherAlgDisabled(int id); bool IsCmacAlgDisabled(int id); bool IsCurveDisabled(int eccId); bool IsCurve25519AlgDisabled(int id); int32_t TestSimpleRand(uint8_t *buff, uint32_t len); int32_t TestSimpleRandEx(void *libCtx, uint8_t *buff, uint32_t len); #if defined(HITLS_CRYPTO_EAL) && defined(HITLS_CRYPTO_MAC) uint32_t TestGetMacLen(int algId); void TestMacSameAddr(int algId, Hex *key, Hex *data, Hex *mac); void TestMacAddrNotAlign(int algId, Hex *key, Hex *data, Hex *mac); #endif #ifdef HITLS_CRYPTO_CIPHER CRYPT_EAL_CipherCtx *TestCipherNewCtx(CRYPT_EAL_LibCtx *libCtx, int32_t id, const char *attrName, int isProvider); #endif #ifdef HITLS_CRYPTO_PKEY CRYPT_EAL_PkeyCtx *TestPkeyNewCtx( CRYPT_EAL_LibCtx *libCtx, int32_t id, uint32_t operType, const char *attrName, int isProvider); #endif #ifdef __cplusplus } #endif #endif // CRYPTO_TEST_UTIL_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/crypto/crypto_test_util.h
C
unknown
2,009
# This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. cmake_minimum_required(VERSION 3.16 FATAL_ERROR) project(GEN_TEST) set(GEN_TESTCASE "gen_testcase") set(HITLS_SRC ${PROJECT_SOURCE_DIR}/../../..) set(EXECUTABLE_OUTPUT_PATH ${HITLS_SRC}/testcode/output) set(SECURTE_INCLUDE ${HITLS_SRC}/platform/Secure_C/include) set(GEN_SOURCE_SRC ${PROJECT_SOURCE_DIR}/main.c ${PROJECT_SOURCE_DIR}/helper.c ${PROJECT_SOURCE_DIR}/test.c ) include_directories(${SECURTE_INCLUDE} ${HITLS_SRC}/testcode/framework/include ${HITLS_SRC}/testcode/framework/crypto ${HITLS_SRC}/config/macro_config ${HITLS_SRC}/crypto/include ${HITLS_SRC}/include/crypto ${HITLS_SRC}/include/bsl ${HITLS_SRC}/bsl/err/include ) add_executable(${GEN_TESTCASE} ${GEN_SOURCE_SRC}) if(PRINT_TO_TERMINAL) target_compile_options(${GEN_TESTCASE} PRIVATE -DPRINT_TO_TERMINAL) endif() target_link_directories(${GEN_TESTCASE} PRIVATE ${HITLS_SRC}/platform/Secure_C/lib ) target_link_libraries(${GEN_TESTCASE} boundscheck )
2401_83913325/openHiTLS-examples_2461
testcode/framework/gen_test/CMakeLists.txt
CMake
unknown
1,511
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "helper.h" #include <dirent.h> #include "securec.h" #include "crypt_utils.h" #define INCLUDE_BASE "/* INCLUDE_BASE" #define BEGIN_HEADER "/* BEGIN_HEADER */" #define END_HEADER "/* END_HEADER */" #define BEGIN_CASE "/* BEGIN_CASE */" #define END_CASE "/* END_CASE */" #define PRINT_TESTSUITES_TAG "</testsuites>\n" #define PRINT_TESTSUITE_TAG " </testsuite>\n" #define PRINT_TESTCASE_TAG " </testcase>\n" #define PRINT_TESTCASE_LIST_TAG " <testcase name=\"%s\" status=\"run\" time=\"0\" classname=\"%s\" />\n" #define PRINT_FAILURE_TAG " <failure message=\"failed\" type=\"\" />\n" #define LINE_BREAK_SYMBOL '\n' #define LINE_HEAD_SYMBOL '\r' FunctionTable g_testFunc[MAX_TEST_FUCNTION_COUNT]; int g_testFuncCount = 0; char g_expTable[MAX_EXPRESSION_COUNT][MAX_EXPRESSION_LEN]; int g_expCount = 0; FILE *g_fpOutput = NULL; int g_lineCount = 0; char g_suiteFileName[MAX_FILE_PATH_LEN]; void SetOutputFile(FILE *fp) { g_fpOutput = fp; } FILE *GetOutputFile(void) { return g_fpOutput; } void FreeHex(Hex *data) { if (data == NULL) { return; } data->len = 0; if (data->x != NULL) { free(data->x); data->x = NULL; } } Hex *NewHex(void) { Hex *data = (Hex *)malloc(sizeof(Hex)); if (data == NULL) { return NULL; } data->len = 0; data->x = NULL; return data; } int IsInt(const char *str) { uint32_t i = 0; if (str[0] == '-') { i = 1; } for (; i < strlen(str); i++) { if (str[i] > '9' || str[i] < '0') { return 0; } } return 1; } void Print(const char *fmt, ...) { #ifdef PRINT_TO_TERMINAL va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args); #else va_list args; va_start(args, fmt); (void)vfprintf(g_fpOutput, fmt, args); va_end(args); #endif } int ReadLine(FILE *file, char *buf, uint32_t bufLen, bool skipHash, bool skipEmptyLine) { int foundLine = 0; int i; char *ret = NULL; while (!foundLine) { ret = fgets(buf, bufLen, file); if (ret == NULL) { return -1; } g_lineCount++; int len = strlen(buf); if ((buf[0] == '#') && skipHash) { continue; } if (!skipEmptyLine) { foundLine = 1; } for (i = 0; i < len; i++) { char cur = buf[i]; if (cur != ' ' && cur != LINE_BREAK_SYMBOL && cur != LINE_HEAD_SYMBOL) { foundLine = 1; } if (cur == LINE_BREAK_SYMBOL || cur == LINE_HEAD_SYMBOL) { buf[i] = '\0'; break; } } } return 0; } int SplitArguments(char *inStr, uint32_t inLen, char **outParam, uint32_t *paramLen) { uint32_t cur = 0; uint32_t count = 0; bool inString = false; char *in = inStr; char **param = outParam; param[count] = &in[cur]; count++; cur++; if (count > *paramLen) { return 1; } while (cur < inLen && in[cur] != '\0') { if (in[cur] == '\"') { inString = !inString; } if (in[cur] == ':' && !inString) { if (cur == inLen - 1) { param[count] = &in[cur]; } else { param[count] = &in[cur + 1]; count++; } if (count > *paramLen) { printf("Exceed maximum param limit, expect num %u, actual num %u\n", *paramLen, count); return 1; } in[cur] = '\0'; } cur++; } if (in[cur - 1] == '\n') { in[cur - 1] = '\0'; } *paramLen = count; if (inString) { return 1; } return 0; } static int g_fuzzEnd = 0; int CheckTag(char *in, uint32_t len) { char *cur = in; while (*cur == ' ') { cur++; } uint32_t beginHeaderLen = strlen(BEGIN_HEADER); uint32_t endHeaderLen = strlen(END_HEADER); uint32_t beginCaseLen = strlen(BEGIN_CASE); uint32_t endCaseLen = strlen(END_CASE); uint32_t includeBaseLen = strlen(INCLUDE_BASE); if ((len >= beginHeaderLen) && (strlen(cur) >= beginHeaderLen) && (strncmp(cur, BEGIN_HEADER, beginHeaderLen) == 0)) { return TAG_BEGIN_HEADER; } else if ((len >= endHeaderLen) && (strlen(cur) >= endHeaderLen) && (strncmp(cur, END_HEADER, endHeaderLen) == 0)) { return TAG_END_HEADER; } else if ((len >= beginCaseLen) && (strlen(cur) >= beginCaseLen) && (strncmp(cur, BEGIN_CASE, beginCaseLen) == 0)) { return TAG_BEGIN_CASE; } else if ((len >= endCaseLen) && (strlen(cur) >= endCaseLen) && (strncmp(cur, END_CASE, endCaseLen) == 0)) { return TAG_END_CASE; } else if ((len >= includeBaseLen) && (strlen(cur) >= includeBaseLen) && (strncmp(cur, INCLUDE_BASE, includeBaseLen) == 0)) { return TAG_INCLUDE_BASE; } return TAG_NOT_TAG; } static int ClearVoid(const char *in, const uint32_t inLen, uint32_t *cur, uint32_t *prev) { uint32_t localCur = *cur; uint32_t localPrev; while (localCur < inLen && in[localCur] == ' ') { localCur++; } localPrev = localCur; if (strncmp(&in[localCur], "void", strlen("void")) != 0) { return 1; } localCur += strlen("void"); while (localCur < inLen && in[localCur] == ' ') { localCur++; } localPrev = localCur; *cur = localCur; *prev = localPrev; return 0; } static int NextArgument(const char *in, const uint32_t inLen, uint32_t *cur) { uint32_t localCur = *cur; while (localCur < inLen && in[localCur] != ',' && in[localCur] != ')') { localCur++; } if (localCur >= inLen) { return 1; } *cur = localCur; return 0; } static int CheckType(const char *in, const uint32_t cur, const uint32_t prev, int *outType) { int *type = outType; if ((cur - prev == strlen("int")) && (strncmp(&in[prev], "int", strlen("int")) == 0)) { *type = ARG_TYPE_INT; } else if ((cur - prev == strlen("Hex")) && (strncmp(&in[prev], "Hex", strlen("Hex")) == 0)) { *type = ARG_TYPE_HEX; } else if ((cur - prev == strlen("char")) && (strncmp(&in[prev], "char", strlen("char")) == 0)) { *type = ARG_TYPE_STR; } else { return 1; } return 0; } int ReadFunction(const char *in, const uint32_t inLen, char *outFuncName, uint32_t outLen, int argv[MAX_ARGUMENT_COUNT], uint32_t *argCount) { uint32_t cur = 0; uint32_t prev = 0; char *funcName = outFuncName; if (ClearVoid(in, inLen, &cur, &prev) != 0) { return 1; } // get function name while (cur < inLen && in[cur] != '(') { cur++; } if (cur >= inLen) { return 1; } if (strncpy_s(funcName, outLen, &in[prev], cur - prev) != 0) { return 1; } funcName[cur - prev] = '\0'; cur++; // get argument types uint32_t count = 0; while (cur < inLen) { while (cur < inLen && in[cur] == ' ') { cur++; } prev = cur; while (cur < inLen && in[cur] != ' ' && in[cur] != ',' && in[cur] != '*' && in[cur] != ')') { cur++; } if (in[cur] == ')') { break; } if (cur == inLen || in[cur] == ',') { return 1; } int type = -1; if (CheckType(in, cur, prev, &type) != 0) { Print("******\nERROR: check type failed at: \n"); return 1; } argv[count] = type; count++; if (NextArgument(in, inLen, &cur) != 0) { return 1; } if (in[cur] == ')') { break; } cur++; } *argCount = count; return 0; } int AddFunction(const char *funcName, int argv[MAX_ARGUMENT_COUNT], const uint32_t argCount) { if (g_testFuncCount >= MAX_TEST_FUCNTION_COUNT || argCount > MAX_ARGUMENT_COUNT) { return 1; } if (strcpy_s(g_testFunc[g_testFuncCount].name, MAX_TEST_FUNCTION_NAME, funcName) != 0) { return 1; } g_testFunc[g_testFuncCount].argCount = argCount; for (uint32_t i = 0; i < argCount; i++) { g_testFunc[g_testFuncCount].argType[i] = argv[i]; } g_testFunc[g_testFuncCount].id = g_testFuncCount; g_testFuncCount++; return 0; } int GenFunctionWrapper(FILE *file, FunctionTable *function) { int ret; ret = fprintf(file, "void %s_wrapper(void **param)\n", function->name); if (ret < 0) { return 1; } ret = fprintf(file, "{\n"); if (ret < 0) { return 1; } ret = fprintf(file, " (void)signal(SIGALRM, handleAlarmSignal);\n"); if (ret < 0) { return 1; } ret = fprintf(file, " alarm(600u);\n"); if (ret < 0) { return 1; } if (function->argCount == 0) { ret = fprintf(file, " (void) param;\n"); if (ret < 0) { return 1; } } ret = fprintf(file, " %s(", function->name); if (ret < 0) { return 1; } for (uint32_t i = 0; i < function->argCount; i++) { if (function->argType[i] == ARG_TYPE_INT) { ret = fprintf(file, "*((int*)param[%d])", (int)i); if (ret < 0) { return 1; } } else if (function->argType[i] == ARG_TYPE_STR) { ret = fprintf(file, "(char*)param[%d]", (int)i); if (ret < 0) { return 1; } } else if (function->argType[i] == ARG_TYPE_HEX) { ret = fprintf(file, "(Hex*)param[%d]", (int)i); if (ret < 0) { return 1; } } if (i != function->argCount - 1) { ret = fprintf(file, ", "); if (ret < 0) { return 1; } } } ret = fprintf(file, ");\n}\n\n"); if (ret < 0) { return 1; } return 0; } int GenFunctionPointer(FILE *file) { if (file == NULL) { return 1; } int ret; ret = fprintf(file, "%s\n\n", "typedef void (*TestWrapper)(void **param);"); if (ret < 0) { return 1; } ret = fprintf(file, "%s\n%s\n", "TestWrapper test_funcs[] = ", "{"); if (ret < 0) { return 1; } for (int i = 0; i < g_testFuncCount; i++) { ret = fprintf(file, " %s_wrapper, \n", g_testFunc[i].name); if (ret < 0) { return 1; } } ret = fprintf(file, "%s\n", "};"); if (ret < 0) { return 1; } return 0; } static int ConnectFunction(char *lineBuf, uint32_t bufLen, FILE *fp) { char buf[MAX_FUNCTION_LINE_LEN]; bool reachEnd = false; int ret = 0; while (!reachEnd) { for (int i = 0; lineBuf[i] != '\0'; i++) { if (lineBuf[i] == ')') { ret = 0; reachEnd = true; } if (lineBuf[i] == '{') { ret = 1; reachEnd = true; } } if (reachEnd) { break; } if (ReadLine(fp, buf, MAX_FUNCTION_LINE_LEN, 0, 0) == 0) { if (strcat_s(lineBuf, bufLen, buf) != 0) { return 1; } } else { return 1; } } return ret; } int ScanAllFunction(FILE *inFile, FILE *outFile) { char buf[MAX_FUNCTION_LINE_LEN]; int ret = 0; uint32_t len = MAX_ARGUMENT_COUNT; bool inFunction = false; bool isDeclaration = true; int arguments[MAX_ARGUMENT_COUNT]; char funcName[MAX_TEST_FUNCTION_NAME]; while (ReadLine(inFile, buf, MAX_FUNCTION_LINE_LEN, 0, 0) == 0) { int curTag = CheckTag(buf, strlen(buf)); if (curTag == TAG_NOT_TAG) { if (!inFunction) { fprintf(outFile, "%s\n", buf); continue; } } else if (curTag == TAG_BEGIN_CASE) { if (!inFunction) { inFunction = true; isDeclaration = true; continue; } Print("ERROR: missing end case tag\n"); return 1; } else if (curTag == TAG_END_CASE) { if (inFunction) { inFunction = false; fprintf(outFile, "\n"); continue; } return 1; } else { return 1; } if (isDeclaration) { if (ConnectFunction(buf, sizeof(buf), inFile) != 0) { Print("******\nERROR: connect function failed at: \n"); Print("%s\n", buf); return 1; } ret = ReadFunction(buf, strlen(buf), funcName, sizeof(funcName), arguments, &len); if (ret != 0) { Print("*******\nERROR: Read function failed at: \n"); Print("%s\n", buf); return ret; } ret = AddFunction(funcName, arguments, len); if (ret != 0) { return ret; } isDeclaration = false; len = MAX_ARGUMENT_COUNT; } (void)fprintf(outFile, "%s\n", buf); } return 0; } static int IncludeBase(char *line, uint32_t len, FILE *outFile, const char *dir) { if (len < strlen(INCLUDE_BASE)) { return 1; } char *name = &line[strlen(INCLUDE_BASE)]; while (*name == ' ') { name++; } if (*name == '\0') { return 1; } char *end = name; while (*end != ' ') { end++; } *end = '\0'; char fileBuf[MAX_FILE_PATH_LEN]; if (snprintf_s(fileBuf, MAX_FILE_PATH_LEN, MAX_FILE_PATH_LEN, BASE_FILE_FORMAT, dir, name) == -1) { return 1; } g_lineCount = 0; FILE *fpBase = fopen(fileBuf, "r"); if (fpBase == NULL) { Print("ERROR:Open the base file. %s An error occurred when\n", fileBuf); return 1; } int ret; char buf[MAX_FUNCTION_LINE_LEN]; while (ReadLine(fpBase, buf, MAX_FUNCTION_LINE_LEN, 0, 0) == 0) { ret = fprintf(outFile, "%s\n", buf); if (ret < 0) { goto EXIT; } } EXIT: if (fclose(fpBase) != 0) { Print("base file close failed\n"); } return 0; } int WriteHeader(FILE *outFile) { if (fprintf(outFile, "#include \"helper.h\"\n#include \"test.h\"\n#include <time.h>\n#include <unistd.h>\n") < 0) { return 1; } return 0; } int ScanHeader(FILE *inFile, FILE *outFile, const char *dir) { char buf[MAX_FUNCTION_LINE_LEN]; bool inHeader = false; while (ReadLine(inFile, buf, MAX_FUNCTION_LINE_LEN, 0, !inHeader) == 0) { int curTag = CheckTag(buf, strlen(buf)); if (curTag == TAG_BEGIN_HEADER) { if (!inHeader) { inHeader = true; } else { Print("******\nERROR: duplicate begin header tag\n"); return 1; } } else if (curTag == TAG_END_HEADER) { if (inHeader) { (void)fprintf(outFile, "%s\n", buf); return 0; } else { Print("******\nERROR: found end header without begin\n"); return 1; } } else if (curTag == TAG_INCLUDE_BASE) { int tmpLineCount = g_lineCount; if (IncludeBase(buf, strlen(buf), outFile, dir) != 0) { Print("******\nERROR: include base file failed\n"); return 1; } g_lineCount = tmpLineCount; continue; } else if (curTag != TAG_NOT_TAG) { Print("******\nERROR: missing end header tag\n"); return 1; } (void)fprintf(outFile, "%s\n", buf); } return 0; } static int AddExp(const char *exp) { if (g_expCount >= MAX_EXPRESSION_COUNT) { Print("Too much macros. Max macro count is %d\n", MAX_EXPRESSION_COUNT); return -1; } for (int i = 0; i < g_expCount; i++) { if (strcmp(exp, g_expTable[i]) == 0) { return i; } } if (strcpy_s(g_expTable[g_expCount], MAX_EXPRESSION_LEN, exp) != 0) { Print("Macro too long, max length is %d\n", MAX_EXPRESSION_LEN); return -1; } g_expCount++; return g_expCount - 1; } static int GetFuncIdByName(const char *name, uint32_t len) { int funcId = -1; for (int i = 0; i < g_testFuncCount; i++) { if ((len < MAX_TEST_FUNCTION_NAME) && (strcmp(name, g_testFunc[i].name) == 0)) { funcId = i; break; } } return funcId; } int GenDatax(FILE *inFile, FILE *outFile) { char buf[MAX_DATA_LINE_LEN]; char title[MAX_DATA_LINE_LEN]; int ret; int funcId = -1; char *param[MAX_ARGUMENT_COUNT]; uint32_t paramLen = MAX_ARGUMENT_COUNT; while (ReadLine(inFile, title, MAX_DATA_LINE_LEN, 1, 1) == 0) { ret = fprintf(outFile, "%s\n", title); if (ret < 0) { return 1; } if ((ReadLine(inFile, buf, MAX_DATA_LINE_LEN, 1, 1) != 0)) { return 1; } paramLen = MAX_ARGUMENT_COUNT; ret = SplitArguments(buf, strlen(buf), param, &paramLen); if (ret != 0) { Print("******\nERROR: Generate datax failed: split argument failed at testcase:\n"); Print("%s\n", title); return ret; } funcId = GetFuncIdByName(param[0], strlen(param[0])); if (funcId == -1) { Print("******\nERROR: Generate datax failed: no function id for %s at testcase:\n", param[0]); Print("%s\n", title); return 1; } if (paramLen != g_testFunc[funcId].argCount + 1) { Print("******\nERROR: Generate datax failed: invalid argument count for function %s at testcase:\n", param[0]); Print("%s\n", title); return 1; } ret = fprintf(outFile, "%d:", funcId); if (ret < 0) { return 1; } int expId = 0; for (uint32_t i = 0; i < g_testFunc[funcId].argCount; i++) { if (g_testFunc[funcId].argType[i] == ARG_TYPE_INT && (IsInt(param[i + 1]) == 1)) { ret = fprintf(outFile, "int:%s", param[i + 1]); } else if (g_testFunc[funcId].argType[i] == ARG_TYPE_INT && (!IsInt(param[i + 1]))) { expId = AddExp(param[i + 1]); ret = fprintf(outFile, "exp:%d", expId); } else if (g_testFunc[funcId].argType[i] == ARG_TYPE_STR) { ret = fprintf(outFile, "char:%s", param[i + 1]); } else if (g_testFunc[funcId].argType[i] == ARG_TYPE_HEX) { ret = fprintf(outFile, "Hex:%s", param[i + 1]); } else { Print("invalid argument type\n"); return 1; } if (ret < 0) { return 1; } if (i != g_testFunc[funcId].argCount - 1) { ret = fprintf(outFile, ":"); } if (expId == -1) { return 1; } expId = 0; } ret = fprintf(outFile, "\n\n"); if (ret < 0) { return 1; } } return 0; } int GenExpTable(FILE *outFile) { int ret; ret = fprintf(outFile, "int getExpression(int expId, int *out)\n{\n"); if (ret < 0) { return 1; } if (g_expCount == 0) { ret = fprintf(outFile, " (void) out;\n (void) expId;\n"); if (ret < 0) { return 1; } } ret = fprintf(outFile, " int ret = 0;\n"); if (ret < 0) { return 1; } ret = fprintf(outFile, " switch (expId)\n {\n"); if (ret < 0) { return 1; } for (int i = 0; i < g_expCount; i++) { ret = fprintf(outFile, " case %d:\n", i); if (ret < 0) { return 1; } ret = fprintf(outFile, " *out = %s;\n", g_expTable[i]); if (ret < 0) { return 1; } ret = fprintf(outFile, " break;\n"); if (ret < 0) { return 1; } } ret = fprintf(outFile, " default:\n"); if (ret < 0) { return 1; } ret = fprintf(outFile, " ret = 1;\n"); if (ret < 0) { return 1; } ret = fprintf(outFile, " break;\n"); if (ret < 0) { return 1; } ret = fprintf(outFile, " }\n return ret;\n}\n"); if (ret < 0) { return 1; } return 0; } int LoadFunctionName(FILE *outFile) { int ret; ret = fprintf(outFile, "const char * funcName[] = {\n"); if (ret < 0) { return 1; } for (int i = 0; i < g_testFuncCount; i++) { ret = fprintf(outFile, " \"%s\",\n", g_testFunc[i].name); if (ret < 0) { return 1; } } ret = fprintf(outFile, "};\n\n"); if (ret < 0) { return 1; } return 0; } int LoadHelper(FILE *inFile, FILE *outFile) { int ret; char buf[MAX_FUNCTION_LINE_LEN]; if (inFile == NULL || outFile == NULL) { return 1; } while (fgets(buf, MAX_FUNCTION_LINE_LEN, inFile) != NULL) { ret = fprintf(outFile, "%s", buf); if (ret < 0) { return 1; } } (void)fprintf(outFile, "\n\n"); return 0; } int SplitHex(Hex *src, Hex *dest, int max) { uint32_t blocks = src->len / SPILT_HEX_BLOCK_SIZE; uint32_t remain = src->len % SPILT_HEX_BLOCK_SIZE; uint32_t i; if (blocks + 1 > (uint32_t)max) { return 0; } for (i = 0; i < blocks; i++) { dest[i].x = src->x + i * SPILT_HEX_BLOCK_SIZE; dest[i].len = SPILT_HEX_BLOCK_SIZE; } if (remain == 0) { return blocks; } else { dest[i].x = src->x + i * SPILT_HEX_BLOCK_SIZE; dest[i].len = remain; return blocks + 1; } } int SplitHexRand(Hex *src, Hex *dest, int max) { uint32_t left = src->len; int id = 0; if (left <= 3) { dest[id].x = src->x; dest[id].len = left; id++; return id; } while (left > 3) { dest[id].x = src->x + (src->len - left); uint16_t clen = GET_UINT16_LE(dest[id].x, 0); dest[id].len = clen > left ? left : clen; left -= dest[id].len; id++; if (id > max - 1) { break; } } if (left > 0) { dest[id - 1].len += left; } return id; } FILE *OpenFile(const char *name, const char *option, const char *format) { FILE *fp = NULL; char fileBuf[MAX_FILE_PATH_LEN]; if (snprintf_s(fileBuf, MAX_FILE_PATH_LEN, MAX_FILE_PATH_LEN, format, name) == -1) { Print("argument too long\n"); return NULL; } fp = fopen(fileBuf, option); return fp; } int StripDir(const char *in, char *suiteName, const uint32_t suiteNameLen, char *dir, const uint32_t dirNameLen) { int len = strlen(in); int begin = len - 1; char *localDir = dir; char *localSuiteName = suiteName; while (begin >= 0 && in[begin] != '/') { begin--; } if (begin < 0) { return 1; } if (strncpy_s(localDir, dirNameLen, in, begin) != 0) { return 1; } if (strcpy_s(localSuiteName, suiteNameLen, &in[begin + 1]) != 0) { return 1; } if (strcpy_s(g_suiteFileName, MAX_FILE_PATH_LEN, &in[begin + 1]) != 0) { return 1; } return 0; } int ScanFunctionFile(FILE *fpIn, FILE *fpOut, const char *dir) { int ret; ret = ScanHeader(fpIn, fpOut, dir); if (ret != 0) { Print("scan header failed\n"); return 1; } ret = ScanAllFunction(fpIn, fpOut); if (ret != 0) { Print("scan function failed\n"); return 1; } if (fprintf(fpOut, "\n void handleAlarmSignal(int signum)\n{\n\ (void)signum; \n\ fprintf(stderr, \"timeout 600\\n\");\n\ exit(-1);\n}\n") < 0) { return 1; } for (int i = 0; i < g_testFuncCount; i++) { ret = GenFunctionWrapper(fpOut, &g_testFunc[i]); if (ret < 0) { Print("generate function wrapper failed\n"); return 1; } } if (g_fuzzEnd == 1) { ret = fprintf(fpOut, "#define FREE_FUZZ_TC 1\n\n"); } else { ret = fprintf(fpOut, "#define FREE_FUZZ_TC 0\n\n"); } if (ret < 0) { return 1; } return 0; } static bool IsSuite(char *buf, uint32_t bufLen) { uint32_t beginTagLen = strlen("Begin time:"); uint32_t endTagLen = strlen("End time:"); uint32_t resultTagLen = strlen("Result:"); uint32_t atTagLen = strlen("at:"); if (bufLen >= beginTagLen && strncmp(buf, "Begin time:", beginTagLen) == 0) { return false; } else if (bufLen >= endTagLen && strncmp(buf, "End time:", endTagLen) == 0) { return false; } else if (bufLen >= resultTagLen && strncmp(buf, "Result:", resultTagLen) == 0) { return false; } else if (bufLen >= atTagLen && strncmp(buf, "at:", atTagLen) == 0) { return false; } return true; } static int ReadAllLogFile(DIR *logDir, int *totalSuiteCount, FILE *outFile, TestSuiteResult *result, int resultLen) { struct dirent *dir = NULL; int suiteCount = 0; int cur; DIR *localLogDir = logDir; // Stores the execution results of all test cases. FILE *fpAllLog = OpenFile("result.log", "w+", "%s"); if (fpAllLog == NULL) { return 1; } FILE *fpLog = NULL; while ((dir = readdir(localLogDir)) != NULL) { char buf[MAX_LOG_LEN]; uint32_t bufLen = sizeof(buf); if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0) { continue; } // len of ".log" is 4 if (strlen(dir->d_name) <= 4 || strlen(dir->d_name) > MAX_FILE_PATH_LEN - 1) { (void)fclose(fpAllLog); return 1; } fpLog = OpenFile(dir->d_name, "r", LOG_FILE_FORMAT); if (fpLog == NULL) { (void)fclose(fpAllLog); return 1; } if (suiteCount >= resultLen) { Print("Reached maximum suite count\n"); (void)fclose(fpLog); (void)fclose(fpAllLog); return 1; } if (strcpy_s(result[suiteCount].name, MAX_TEST_FUNCTION_NAME - 1, dir->d_name) != EOK) { Print("Dir's Name is too long\n"); (void)fclose(fpLog); (void)fclose(fpAllLog); return 1; } // len of ".log" is 4 result[suiteCount].name[strlen(dir->d_name) - 4] = '\0'; result[suiteCount].total = 0; result[suiteCount].pass = 0; result[suiteCount].skip = 0; result[suiteCount].line = 0; while (ReadLine(fpLog, buf, bufLen, 0, 0) == 0) { char testCaseName[MAX_TEST_FUNCTION_NAME]; memset_s(testCaseName, MAX_TEST_FUNCTION_NAME, 0, MAX_TEST_FUNCTION_NAME); if (!IsSuite(buf, strlen(buf))) { continue; } result[suiteCount].total++; cur = 0; while (buf[cur] != '\0' && !(buf[cur] == '.' && buf[cur + 1] == '.')) { cur++; } if (buf[cur] == '\0') { Print("Read log file %s failed\n", dir->d_name); (void)fclose(fpLog); (void)fclose(fpAllLog); return 1; } if (strncpy_s(testCaseName, sizeof(testCaseName) - 1, buf, cur) != EOK) { Print("TestCaseName is too long\n"); (void)fclose(fpLog); (void)fclose(fpAllLog); return 1; } testCaseName[cur] = '\0'; while (buf[cur] == '.') { cur++; } if (strncmp(&buf[cur], "pass", strlen("pass")) == 0) { result[suiteCount].pass++; result[suiteCount].line++; (void)fprintf(outFile, PRINT_TESTCASE_LIST_TAG, testCaseName, result[suiteCount].name); (void)fprintf(fpAllLog, "%s %s\n", testCaseName, "PASS"); } else if (strncmp(&buf[cur], "skip", strlen("skip")) == 0) { result[suiteCount].skip++; result[suiteCount].line++; (void)fprintf(outFile, PRINT_TESTCASE_LIST_TAG, testCaseName, result[suiteCount].name); (void)fprintf(fpAllLog, "%s %s\n", testCaseName, "SKIP"); } else { result[suiteCount].line += 3; // Incorrect test case requires 3 lines (void)fprintf(outFile, PRINT_TESTCASE_LIST_TAG, testCaseName, result[suiteCount].name); (void)fprintf(fpAllLog, "%s %s\n", testCaseName, "FAIL"); (void)fprintf(outFile, PRINT_FAILURE_TAG); (void)fprintf(outFile, PRINT_TESTCASE_TAG); } } suiteCount++; cur = 0; (void)fclose(fpLog); } *totalSuiteCount = suiteCount; (void)fclose(fpAllLog); return 0; } static int GenResultFile(FILE *in, FILE *out, TestSuiteResult result[MAX_SUITE_COUNT], int testSuiteCount) { int totalTests = 0; int totalPass = 0; int totalSkip = 0; if (testSuiteCount >= MAX_SUITE_COUNT) { Print("suites count too great\n"); return 1; } for (int i = 0; i < testSuiteCount; i++) { totalTests += result[i].total; totalPass += result[i].pass; totalSkip += result[i].skip; } (void)fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); (void)fprintf(out, "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" errors=\"0\" ", totalTests, totalTests - totalPass - totalSkip, totalSkip); (void)fprintf(out, "timestamp=\"0000-00-00T00:00:00\" time=\"0\" name=\"AllTests\">\n"); for (int i = 0; i < testSuiteCount; i++) { (void)fprintf(out, " <testsuite name=\"%s\" tests=\"%d\" skips = \"%d\" failures=\"%d\" ", result[i].name, result[i].total, result[i].skip, result[i].total - result[i].pass - result[i].skip); (void)fprintf(out, "disabled=\"0\" errors=\"0\" time=\"0\">\n"); for (int j = 0; j < result[i].line; j++) { char buf[MAX_LOG_LEN]; if (fgets(buf, sizeof(buf), in) != NULL) { (void)fputs(buf, out); } else { return 1; } } (void)fprintf(out, PRINT_TESTSUITE_TAG); } (void)fprintf(out, PRINT_TESTSUITES_TAG); return 0; } int GenResult(void) { int ret; TestSuiteResult result[MAX_SUITE_COUNT]; int testSuiteCount = 0; DIR *logDir = NULL; logDir = opendir(LOG_FILE_DIR); if (logDir == NULL) { Print("fail to open log directory\n"); return 1; } FILE *fpTmp = NULL; fpTmp = fopen("tmp.txt", "w+"); if (fpTmp == NULL) { Print("open tmp.txt failed\n"); (void)closedir(logDir); return 1; } FILE *fpResult = NULL; fpResult = fopen("result.xml", "w"); if (fpResult == NULL) { Print("open result.xml failed\n"); (void)closedir(logDir); (void)fclose(fpTmp); (void)remove("tmp.txt"); return 1; } ret = ReadAllLogFile(logDir, &testSuiteCount, fpTmp, result, sizeof(result)); if (ret != 0) { Print("read log failed\n"); goto EXIT; } rewind(fpTmp); ret = GenResultFile(fpTmp, fpResult, result, testSuiteCount); if (ret != 0) { Print("gen result failed\n"); goto EXIT; } EXIT: (void)closedir(logDir); (void)fclose(fpTmp); (void)fclose(fpResult); (void)remove("tmp.txt"); return ret; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/gen_test/helper.c
C
unknown
32,462
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "securec.h" #include "helper.h" #define EXECUTE_BASE_FILE "../common/execute_base.c" #define EXECUTE_TEST_FILE "../common/execute_test.c" typedef struct { char suiteName[MAX_FILE_PATH_LEN]; char dir[MAX_FILE_PATH_LEN]; FILE *fpIn; FILE *fpOut; FILE *fpData; FILE *fpBase; FILE *fpDatax; FILE *fpHelper; } GenTestParams; int WriteToFile(GenTestParams *genParam) { int ret = 0; ret = WriteHeader(genParam->fpOut); if (ret != 0) { return ret; } // Scanned test_suite_xxx.c, and write fpOut ret = ScanFunctionFile(genParam->fpIn, genParam->fpOut, genParam->dir); if (ret != 0) { return ret; } ret = GenFunctionPointer(genParam->fpOut); if (ret != 0) { return ret; } ret = GenDatax(genParam->fpData, genParam->fpDatax); if (ret != 0) { Print("gen datax failed\n"); return ret; } ret = GenExpTable(genParam->fpOut); if (ret != 0) { return ret; } ret = LoadFunctionName(genParam->fpOut); if (ret != 0) { return ret; } (void)fprintf(genParam->fpOut, "char suiteName[200] = \"%s\";\n\n", genParam->suiteName); // Write execute_base.c to fpOut ret = LoadHelper(genParam->fpBase, genParam->fpOut); if (ret != 0) { return ret; } // Write execute_test.c to fpOut return LoadHelper(genParam->fpHelper, genParam->fpOut); } int main(int argc, char **argv) { (void)argc; #ifndef PRINT_TO_TERMINAL FILE *fp = fopen("GenTest.output", "a"); if (fp == NULL) { return 1; } SetOutputFile(fp); #endif if (strcmp(argv[1], "GenReport") == 0) { int resultRet = GenResult(); #ifndef PRINT_TO_TERMINAL (void)fclose(fp); #endif return resultRet; } int ret = 0; GenTestParams genParam = {0}; StripDir(argv[1], genParam.suiteName, MAX_FILE_PATH_LEN, genParam.dir, MAX_FILE_PATH_LEN); // Read test_suite_xxx.c genParam.fpIn = OpenFile(argv[1], "r", "%s.c"); if (genParam.fpIn == NULL) { Print("Open %s.c error occurred while file\n", argv[1]); #ifndef PRINT_TO_TERMINAL (void)fclose(fp); #endif return -1; } // Output file testcode/output/test_suite_xxx.c genParam.fpOut = OpenFile(genParam.suiteName, "w", "%s.c"); if (genParam.fpOut == NULL) { Print("Error generating c file\n"); ret = 1; goto END_FP_IN; } genParam.fpData = OpenFile(argv[1], "r", "%s.data"); if (genParam.fpData == NULL) { Print("An error occurred while opening the data file.\n"); ret = 1; goto END_FP_OUT; } genParam.fpDatax = OpenFile(genParam.suiteName, "w", "%s.datax"); if (genParam.fpDatax == NULL) { Print("Error generating datax file\n"); ret = 1; goto END_FP_DATA; } genParam.fpBase = fopen(EXECUTE_BASE_FILE, "r"); if (genParam.fpBase == NULL) { Print("An error occurred when opening the base file.\n"); ret = 1; goto END_FP_DATAX; } genParam.fpHelper = fopen(EXECUTE_TEST_FILE, "r"); if (genParam.fpHelper == NULL) { Print("Error opening secondary file\n"); ret = 1; goto END_FP_BASE; } ret = WriteToFile(&genParam); (void)fclose(genParam.fpHelper); END_FP_BASE: (void)fclose(genParam.fpBase); END_FP_DATAX: (void)fclose(genParam.fpDatax); END_FP_DATA: (void)fclose(genParam.fpData); END_FP_OUT: (void)fclose(genParam.fpOut); END_FP_IN: (void)fclose(genParam.fpIn); #ifndef PRINT_TO_TERMINAL (void)fclose(fp); #endif return ret; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/gen_test/main.c
C
unknown
4,190
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "securec.h" #include "helper.h" #include "test.h" TestInfo g_testResult; int ConvertInt(const char *intStr, int *outNum) { int *num = outNum; uint32_t i = 0; if (intStr[0] == '-') { i = 1; } for (; i < strlen(intStr); i++) { if (intStr[i] > '9' || intStr[i] < '0') { return 1; } } // Decimal *num = strtol(intStr, NULL, 10); return 0; } int ConvertString(char **str) { if ((*str)[0] != '"') { return 1; } uint32_t back = strlen(*str) - 1; if ((*str)[back] != '"') { back--; if ((*str)[back] != '"') { return 1; } } (*str)[back] = '\0'; (*str)++; return 0; } int IsValidHexChar(char c) { if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) { return 0; } return 1; } int ConvertHex(const char *str, Hex *output) { uint32_t len = strlen(str); if (len == 0) { output->x = NULL; output->len = 0; return 0; } // The length of a hex string must be a multiple of 2. if (len % 2 != 0) { return 1; } // Length of the hex string/2 = Length of the byte stream len = len / 2; output->x = (uint8_t *)malloc(len * sizeof(uint8_t)); if (output->x == NULL) { return 1; } output->len = len; // Every 2 bytes in a group for (uint32_t i = 0; i < 2 * len; i += 2) { if ((IsValidHexChar(str[i]) == 1) || (IsValidHexChar(str[i + 1]) == 1)) { goto ERR; } // hex to int formulas: (Hex % 32 + 9) % 25 = int, hex output->x[i / 2] = (str[i] % 32 + 9) % 25 * 16 + (str[i + 1] % 32 + 9) % 25; } return 0; ERR: free(output->x); output->len = 0; return 1; } void RecordFailure(const char *test, const char *filename) { g_testResult.result = TEST_RESULT_FAILED; if (strcpy_s(g_testResult.test, sizeof(g_testResult.test), test) != 0) { Print("failure log failed: message too long\n"); } if (strcpy_s(g_testResult.filename, sizeof(g_testResult.filename), filename) != 0) { Print("failure log failed: filename too long\n"); } } void SkipTest(const char *filename) { g_testResult.result = TEST_RESULT_SKIPPED; if (strcpy_s(g_testResult.filename, sizeof(g_testResult.filename), filename) != 0) { Print("failure log failed: filename too long\n"); } } void PrintResult(bool showDetail, char *vectorName, uint64_t useTime) { if (showDetail) { if (g_testResult.result == TEST_RESULT_SUCCEED) { Print("pass. use ms: %ld\n", useTime); } else if (g_testResult.result == TEST_RESULT_SKIPPED) { Print("skip\n"); } else { Print("failed\n"); Print("at: (%s) in %s\n", g_testResult.test, g_testResult.filename); } } else if (g_testResult.result == TEST_RESULT_FAILED) { Print("\nfailed at vector: %s\n", vectorName); Print("at: (%s) in %s\n", g_testResult.test, g_testResult.filename); } } void PrintLog(FILE *logFile) { int ret; if (g_testResult.result == TEST_RESULT_SUCCEED) { ret = fprintf(logFile, "pass\n"); if (ret < 0) { Print("write to log file failed\n"); } } else if (g_testResult.result == TEST_RESULT_SKIPPED) { ret = fprintf(logFile, "skip\n"); if (ret < 0) { Print("write to log file failed\n"); } } else { ret = fprintf(logFile, "failed\n"); if (ret < 0) { Print("write to log file failed\n"); } ret = fprintf(logFile, "at: (%s) in in %s\n", g_testResult.test, g_testResult.filename); if (ret < 0) { Print("write to log file failed\n"); } } } void PrintDiff(const uint8_t *str1, uint32_t size1, const uint8_t *str2, uint32_t size2) { Print("\nCompare different:\nstr1: "); uint32_t i; for (i = 0; i < size1; i++) { Print("%02X ", str1[i]); } Print("\nstr2: "); for (i = 0; i < size2; i++) { Print("%02X ", str2[i]); } Print("\n"); }
2401_83913325/openHiTLS-examples_2461
testcode/framework/gen_test/test.c
C
unknown
4,697
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HELPER_H #define HELPER_H #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <stdint.h> #include <stdarg.h> #ifdef __cplusplus extern "C" { #endif #define MAX_TEST_FUCNTION_COUNT 100 #define MAX_TEST_FUNCTION_NAME 500 #define MAX_ARGUMENT_COUNT 50 #define MAX_EXPRESSION_COUNT 100 #define MAX_EXPRESSION_LEN 100 #define MAX_DATA_LINE_LEN 120000 #define MAX_FUNCTION_LINE_LEN 512 #define MAX_FILE_PATH_LEN 300 #define MAX_SUITE_COUNT 600 #define MAX_LOG_LEN 500 #define TAG_NOT_TAG 0 #define TAG_BEGIN_HEADER 1 #define TAG_END_HEADER 2 #define TAG_BEGIN_CASE 3 #define TAG_END_CASE 4 #define TAG_INCLUDE_BASE 5 #define SPILT_HEX_BLOCK_SIZE 4 #define ARG_TYPE_INT 1 #define ARG_TYPE_STR 2 #define ARG_TYPE_HEX 3 #define BASE_FILE_FORMAT "%s/%s.base.c" #define LOG_FILE_DIR "./log/" #define LOG_FILE_FORMAT "./log/%s" #define FUZZ_PRINT_EXECUTES "\r%d" typedef struct { char name[MAX_FILE_PATH_LEN]; int total; int pass; int skip; int line; } TestSuiteResult; typedef struct { char name[MAX_TEST_FUNCTION_NAME]; int id; int argType[MAX_ARGUMENT_COUNT]; uint32_t argCount; } FunctionTable; typedef struct { uint8_t *x; uint32_t len; } Hex; extern FunctionTable g_testFunc[MAX_TEST_FUCNTION_COUNT]; extern int g_testFuncCount; extern char g_expTable[MAX_EXPRESSION_COUNT][MAX_EXPRESSION_LEN]; extern int g_expCount; void Print(const char *fmt, ...); void SetOutputFile(FILE *fp); FILE *GetOutputFile(void); void FreeHex(Hex *data); Hex *NewHex(void); int IsInt(const char *str); int ReadLine(FILE *file, char *buf, uint32_t bufLen, bool skipHash, bool skipEmptyLine); int SplitArguments(char *inStr, uint32_t inLen, char **outParam, uint32_t *paramLen); int ReadFunction(const char *in, const uint32_t inLen, char *outFuncName, uint32_t outLen, int argv[MAX_ARGUMENT_COUNT], uint32_t *argCount); int AddFunction(const char *funcName, int argv[MAX_ARGUMENT_COUNT], const uint32_t argCount); int CheckTag(char *in, uint32_t len); int GenFunctionWrapper(FILE *file, FunctionTable *function); int ScanAllFunction(FILE *inFile, FILE *outFile); int ScanHeader(FILE *inFile, FILE *outFile, const char *dir); int GenFunctionPointer(FILE *file); int GenDatax(FILE *inFile, FILE *outFile); int GenExpTable(FILE *outFile); int LoadFunctionName(FILE *outFile); int LoadHelper(FILE *inFile, FILE *outFile); int ScanFunctionFile(FILE *fpIn, FILE *fpOut, const char *dir); int StripDir(const char *in, char *suiteName, const uint32_t suiteNameLen, char *dir, const uint32_t dirNameLen); FILE *OpenFile(const char *name, const char *option, const char *format); int GenResult(void); int SplitHex(Hex *src, Hex *dest, int max); int SplitHexRand(Hex *src, Hex *dest, int max); int WriteHeader(FILE *outFile); #ifdef __cplusplus } #endif #endif // HELPER_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/include/helper.h
C
unknown
3,408
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef TEST_H #define TEST_H #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <stdint.h> #include <signal.h> #include <setjmp.h> #include <sys/wait.h> #include <time.h> #include "helper.h" #include "crypto_test_util.h" #ifdef __cplusplus extern "C" { #endif #define TEST_RESULT_SUCCEED 0 #define TEST_RESULT_FAILED 1 #define TEST_RESULT_SKIPPED 2 typedef struct { int result; char test[512]; char filename[256]; } TestInfo; #define TRUE_OR_EXIT(TEST) \ do { \ if (!(TEST)) { \ goto EXIT; \ } \ } while (0) #define TRUE_OR_ABRT(TEST) \ do { \ if (!(TEST)) { \ raise(SIGABRT); \ } \ } while (0) #define PRINT_ABRT(TEST) \ do { \ if (!(TEST)) { \ goto ABORT; \ } \ } while (0) #define ASSERT_TRUE(TEST) \ do { \ if (!(TEST)) { \ RecordFailure(#TEST, __FILE__); \ goto EXIT; \ } \ } while (0) #define ASSERT_EQ(VALUE1, VALUE2) \ do { \ int64_t value1__ = (int64_t)(VALUE1); \ int64_t value2__ = (int64_t)(VALUE2); \ if (value1__ != value2__) { \ RecordFailure(#VALUE1 #VALUE2, __FILE__); \ Print("\nvalue is %d (0x%x).\nexpect %d (0x%x).\n", value1__, value1__, value2__, value2__); \ goto EXIT; \ } \ } while (0) #define ASSERT_LT(VALUE1, VALUE2) \ do { \ int64_t value1__ = (int64_t)(VALUE1); \ int64_t value2__ = (int64_t)(VALUE2); \ if (!(value1__ < value2__)) { \ RecordFailure(#VALUE1 #VALUE2, __FILE__); \ Print("\nvalue is %d (0x%x).\nexpect %d (0x%x).\n", value1__, value1__, value2__, value2__); \ goto EXIT; \ } \ } while (0) #define ASSERT_EQ_LOG(LOG, VALUE1, VALUE2) \ do { \ int64_t value1__ = (int64_t)(VALUE1); \ int64_t value2__ = (int64_t)(VALUE2); \ if (value1__ != value2__) { \ RecordFailure(LOG, __FILE__); \ Print("\nvalue is %d (0x%x).\nexpect %d (0x%x).\n", value1__, value1__, value2__, value2__); \ goto EXIT; \ } \ } while (0) #define ASSERT_NE(VALUE1, VALUE2) \ do { \ int64_t value1__ = (int64_t)(VALUE1); \ int64_t value2__ = (int64_t)(VALUE2); \ if (value1__ == value2__) { \ RecordFailure(#VALUE1#VALUE2, __FILE__); \ Print("\nvalue is the same: %d (0x%x).\n", value1__, value2__); \ goto EXIT; \ } \ } while (0) #define ASSERT_TRUE_AND_LOG(LOG, TEST) \ do { \ if (!(TEST)) { \ RecordFailure(LOG, __FILE__); \ goto EXIT; \ } \ } while (0) #define ASSERT_COMPARE(LOG, STR1, SIZE1, STR2, SIZE2) \ do { \ ASSERT_TRUE_AND_LOG(LOG, (SIZE1) == (SIZE2)); \ if (memcmp((STR1), (STR2), (SIZE1)) != 0) { \ RecordFailure((LOG), __FILE__); \ PrintDiff((uint8_t *)(STR1), (uint32_t)(SIZE1), (uint8_t *)(STR2), (uint32_t)(SIZE2)); \ goto EXIT; \ } \ } while (0) #define SKIP_TEST() \ do {\ SkipTest(__FILE__); \ return; \ } while (0) extern int *GetJmpAddress(void); #ifndef TEST_NO_SUBPROC #define SUB_PROC 1 #define SUB_PROC_BEGIN(parentAction) if (fork() > 0) parentAction #define SUB_PROC_END() *GetJmpAddress() = SUB_PROC; return #define SUB_PROC_WAIT(times) for (uint16_t i = 0; i < times; i++) wait(NULL) #else #define SUB_PROC 0 #define SUB_PROC_BEGIN(parentAction) #define SUB_PROC_END() #define SUB_PROC_WAIT(times) #endif extern TestInfo g_testResult; int ConvertInt(const char *intStr, int *outNum); int ConvertString(char **str); int ConvertHex(const char *str, Hex *output); void RecordFailure(const char *test, const char *filename); void SkipTest(const char *filename); void PrintResult(bool showDetail, char *vectorName, uint64_t useTime); void PrintLog(FILE *logFile); void PrintDiff(const uint8_t *str1, uint32_t size1, const uint8_t *str2, uint32_t size2); #ifdef __cplusplus } #endif #endif // TEST_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/include/test.h
C
unknown
6,498
# This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. add_executable(process ${openHiTLS_SRC}/testcode/framework/process/process.c) set_target_properties(process PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${openHiTLS_SRC}/testcode/output" ) target_include_directories(process PRIVATE ${openHiTLS_SRC}/platform/Secure_C/include ${openHiTLS_SRC}/testcode/framework/tls/resource/include ${openHiTLS_SRC}/testcode/framework/tls/base/include ${openHiTLS_SRC}/testcode/framework/tls/process/include ${openHiTLS_SRC}/testcode/framework/tls/include ${openHiTLS_SRC}/testcode/framework/tls/transfer/include ${openHiTLS_SRC}/testcode/framework/tls/rpc/include ${openHiTLS_SRC}/include/bsl ${openHiTLS_SRC}/include/crypto ${openHiTLS_SRC}/bsl/sal/include ${openHiTLS_SRC}/bsl/hash/include ${openHiTLS_SRC}/bsl/uio/src ${openHiTLS_SRC}/bsl/uio/include ${openHiTLS_SRC}/include/tls ${openHiTLS_SRC}/include/crypto ${openHiTLS_SRC}/tls/include ${openHiTLS_SRC}/config/macro_config ) target_link_directories(process PRIVATE ${openHiTLS_SRC}/build ${openHiTLS_SRC}/testcode/output/lib ${openHiTLS_SRC}/platform/Secure_C/lib ) set(PROCESS_LIBS tls_hlt tls_frame hitls_tls) if(ENABLE_PKI AND ${BUILD_PKI} GREATER -1) list(APPEND PROCESS_LIBS hitls_pki) endif() list(APPEND PROCESS_LIBS hitls_crypto hitls_bsl boundscheck pthread dl rec_wrapper) target_link_libraries(process ${PROCESS_LIBS})
2401_83913325/openHiTLS-examples_2461
testcode/framework/process/CMakeLists.txt
CMake
unknown
1,991
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdlib.h> #include <signal.h> #include <unistd.h> #include <stdbool.h> #include <semaphore.h> #include "securec.h" #include "channel_res.h" #include "handle_cmd.h" #include "tls_res.h" #include "control_channel.h" #include "logger.h" #include "lock.h" #include "rpc_func.h" #include "hlt_type.h" #include "hlt.h" #include "process.h" #define DOMAIN_PATH_LEN (128) #define SUCCESS 0 #define ERROR (-1) #define ASSERT_RETURN(condition, log) \ do { \ if (!(condition)) { \ LOG_ERROR(log); \ return ERROR; \ } \ } while (0) int IsFeedbackResult(ControlChannelRes *channelInfo) { int i, ret; ControlChannelBuf dataBuf = {0}; OsLock(channelInfo->sendBufferLock); if (channelInfo->sendBufferNum == 0) { OsUnLock(channelInfo->sendBufferLock); return SUCCESS; } i = 0; while (channelInfo->sendBufferNum > 0) { ret = memcpy_s(dataBuf.data, CONTROL_CHANNEL_MAX_MSG_LEN, channelInfo->sendBuffer[i], strlen((char*)(channelInfo->sendBuffer[i]))); if (ret != EOK) { LOG_ERROR("MemCpy Error"); OsUnLock(channelInfo->sendBufferLock); return ERROR; } dataBuf.dataLen = strlen((char*)channelInfo->sendBuffer[i]); LOG_DEBUG("Remote Process Send Result %s", dataBuf.data); ret = ControlChannelWrite(channelInfo->sockFd, channelInfo->peerDomainPath, &dataBuf); if (ret != EOK) { LOG_ERROR("ControlChannelWrite Error, Msg is %s, ret is %d\n", dataBuf.data, ret); OsUnLock(channelInfo->sendBufferLock); return ERROR; } LOG_DEBUG("Remote Process Send Result %s Success", dataBuf.data); channelInfo->sendBufferNum--; i++; } OsUnLock(channelInfo->sendBufferLock); return SUCCESS; } void FreeThreadRes(pthread_t *threadList, int threadNum) { for (int i = 0; i < threadNum; i++) { pthread_cancel(threadList[i]); pthread_join(threadList[i], NULL); } return; } void ThreadExcuteCmd(void *param) { CmdData cmdData = {0}; if (memcpy_s(&cmdData, sizeof(cmdData), (CmdData *)param, sizeof(CmdData)) != EOK) { free(param); return; } free(param); ControlChannelRes *channelInfo = GetControlChannelRes(); (int)ExecuteCmd(&cmdData); PushResultToChannelSendBuffer(channelInfo, cmdData.result); return; } int main(int argc, char **argv) { int ret, sctpFd; ControlChannelRes* channelInfo = NULL; ControlChannelBuf dataBuf; CmdData exitCmdData = {0}; CmdData* cmdData = NULL; Process* process = NULL; pid_t ppid = atoi(argv[4]); (void)ppid; // Do not set the output buffer setbuf(stdout, NULL); LOG_DEBUG("argv value is %d", argc); ret = InitProcess(); ASSERT_RETURN(ret == SUCCESS, "InitProcess Error"); process = GetProcess(); process->remoteFlag = 1; // Must be marked as a remote process process->tlsType = atoi(argv[1]); // The first parameter indicates the Hitls function ret = memcpy_s(process->srcDomainPath, DOMAIN_PATH_LEN, argv[2], strlen(argv[2])); // The second parameter indicates the local IP address ASSERT_RETURN(ret == SUCCESS, "memcpy process->srcDomainPath Error"); ret = memcpy_s(process->peerDomainPath, DOMAIN_PATH_LEN, argv[3], strlen(argv[3])); // The third parameter indicates the address of the control process ASSERT_RETURN(ret == SUCCESS, "memcpy process->srcDomainPath Error"); // Dependent library initialization ret = HLT_LibraryInit(process->tlsType); ASSERT_RETURN(ret == SUCCESS, "HLT_TlsRegCallback Error"); // Initialize the linked list for storing CTX and SSL ret = InitTlsResList(); ASSERT_RETURN(ret == SUCCESS, "InitTlsResList Error"); // Initializes the global variable that stores the control channel information. ret = InitControlChannelRes(process->srcDomainPath, strlen(process->srcDomainPath), process->peerDomainPath, strlen(process->peerDomainPath)); ASSERT_RETURN(ret == SUCCESS, "ChannelInfoInit Error"); // Creating a Control Link UDP DOMAIN SOCKET channelInfo = GetControlChannelRes(); ret = ControlChannelInit(channelInfo); ASSERT_RETURN(ret == SUCCESS, "ControlChannelInit Error"); // Print information LOG_DEBUG("Create Remote Process Successful"); // The message is sent to the peer end, indicating that the process is started successfully PushResultToChannelSendBuffer(channelInfo, "0|HEART"); while (1) { if (kill(ppid, 0) != 0) { LOG_DEBUG("\nthe parent process [%u] does not exist, I want to exist\n", ppid); break; } // Waiting for the command from the peer end ret = ControlChannelRead(channelInfo->sockFd, &dataBuf); if (ret == 0) { // Receives a message, parses the message, and performs related operations LOG_DEBUG("Remote Process Rcv Cmd Is: %s", dataBuf.data); cmdData = (CmdData*)malloc(sizeof(CmdData)); if (cmdData == NULL) { LOG_ERROR("Malloc cmdData Error"); break; } ret = ParseCmdFromBuf(&dataBuf, cmdData); if (ret != SUCCESS) { LOG_ERROR("ParseCmdFromBuf Error ..."); free(cmdData); break; } if (strncmp((char *)cmdData->funcId, "HLT_RpcProcessExit", strlen("HLT_RpcProcessExit")) == 0) { // Indicates that the process needs to exit sctpFd = atoi((char *)cmdData->paras[0]); (void)sprintf_s((char *)exitCmdData.result, sizeof(exitCmdData.result), "%s|%s|%d", cmdData->id, cmdData->funcId, sctpFd); PushResultToChannelSendBuffer(channelInfo, exitCmdData.result); free(cmdData); break; } ThreadExcuteCmd(cmdData); } // Check whether feedback is required ret = IsFeedbackResult(channelInfo); if (ret != 0) { break; } } LOG_DEBUG("Process Return"); (void)IsFeedbackResult(channelInfo); // Clearing Resources FreeControlChannelRes(); FreeTlsResList(); FreeProcess(); if (sctpFd > 0) { close(sctpFd); } return SUCCESS; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/process/process.c
C
unknown
7,075
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <errno.h> #include <limits.h> #include <memory.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdbool.h> #include <sys/mman.h> #include "stub_replace.h" #ifdef HITLS_BIG_ENDIAN #include "crypt_utils.h" #endif /* The LSB of the function pointer indicates the thumb function. The LSB of the actual address needs to be cleared. */ #define REAL_ADDR(ptr) (void *)(((uintptr_t)(ptr)) & (~(uintptr_t)1)) /* * Used to record the size of the system memory page. */ static long g_pageSize = -1; /* * Obtains the start address of the memory page where the specified function code is located. * fn - Function Address (Function Pointer) */ static inline void *FuncPageGet(uintptr_t fn) { return (void *)(fn & (~(g_pageSize - 1))); } /* * This file does not use the memcpy function of the system. In this way, the mempcy function of * the system can be dynamically replaced by STUB_Replace. */ static int32_t StubCopy(void *dest, void *src, uint32_t size) { if ((src == NULL) || (dest == NULL)) { return ERANGE; } uint8_t *localDst = (uint8_t *)(dest); uint8_t *localSrc = (uint8_t *)(src); for (uint32_t i = 0; i < size; i++) { localDst[i] = localSrc[i]; } return 0; } /* * This file does not use the memset function of the system. In this way, the memset function of * the system can be dynamically replaced by STUB_Replace. */ static void StubSet(void *dest, int val, uint32_t size) { if (dest == NULL) { return; } uint8_t *localDst = (uint8_t *)(dest); for (uint32_t i = 0; i < size; i++) { localDst[i] = val; } } #if defined(__arm__) || defined(__thumb__) static int ReplaceT32(void *srcFn, const void *stubFn) { uint16_t instr1 = 0xF000; uint16_t instr2; uint32_t imm; /* * The difference between the jump instruction and srcFn is 4 bytes. The current address is obtained by * subtracting 4 bytes from the PC. */ uint32_t addrDiff = REAL_ADDR(stubFn) - (REAL_ADDR(srcFn) + 4) - 4; /* * 32-bit test occurrence address: srcFn - stubFn, the scope is out of range, * temporarily comment on the following scope judgment. * if (abs((int32_t)addrDiff) >= 0x100000) { // Max jump range * return -1; * } */ if (((uintptr_t)stubFn) & 0x01) { // Thumb instruction set BL corresponding machine code is [1 1 1 1 0 S imm10][1 1 J1 1 J2 imm11] // Address offset calculation: I1: NOT(J1 EOR S); I2: NOT(J2 EOR S); // imm32: SignExtend(S:I1:I2:imm10:imm11:'0', 32) instr2 = 0xF800; // Corresponding bit of machine code J1 J2 take 1 if (stubFn < srcFn) { instr1 = 0xF400; // The corresponding bit S of the machine code is 1. } imm = addrDiff >> 1; // The address is shifted right by one bit. imm &= (1 << 21) - 1; // Lower 21 bits instr1 |= (imm >> 11) & 0x3FF; // Move rightwards by 11 digits and take imm10. instr2 |= (imm & 0x7FF); } else { // Thumb instruction set BLX corresponding machine code is [1 1 1 1 0 S imm10H][1 1 J1 0 J2 imm10L H] // Address offset calculation: I1 = NOT(J1 EOR S); I2 = NOT(J2 EOR S) // imm32 = SignExtend(S:I1:I2:imm10H:imm10L:'00', 32) instr2 = 0xE800; // J1 and J2 corresponding to the machine code are set to 1. if (stubFn < srcFn) { instr1 = 0xF400; // The corresponding bit S of the machine code is 1. } imm = addrDiff >> 2; // Shift right by 2 bits imm &= (1 << 20) - 1; // Take lower 20 bits instr1 |= (imm >> 10) & 0x3FF; // Take 10 bits instr2 |= (imm & 0x3FF) << 1; // Take lower 10 bits } uint8_t *text = (uint8_t*)REAL_ADDR(srcFn); ((uint16_t *)text)[0] = 0xb580; ((uint16_t *)text)[1] = 0xaf00; ((uint16_t *)text)[2] = instr1; // BL/BLX offset 2 ((uint16_t *)text)[3] = instr2; // Offset 3 ((uint16_t *)text)[4] = 0xaf00; // Offset 4 ((uint16_t *)text)[5] = 0xbd80; // Offset 5 return 0; } static int ReplaceA32(void *srcFn, const void *stubFn) { uint32_t inst; uint32_t addrDiff = REAL_ADDR(stubFn) - (srcFn + 4) - 8; uint32_t imm24; if (abs((int32_t)addrDiff) >= 0x1000000) { // Max jump range return -1; } if (((uintptr_t)stubFn) & 0x01) { // a32 instruction set BLX corresponding machine code is [1 1 1 1 1 0 1 H imm24] // imm32 = SignExtend(imm24:H:'0', 32) uint32_t h = (addrDiff & 0b10) >> 1; // bit[1] of the address difference imm24 = (addrDiff >> 2); // Shift right by 2 bits imm24 &= (1 << 24) - 1; // Take lower 24 bits inst = 0xfa000000 | imm24 | (h << 24); // h is located in bit[24]. } else { // a32 instruction set BL corresponding machine code is [(!= 1111) 1 0 1 1 imm24] // imm32 = SignExtend(imm24:'00', 32) imm24 = (addrDiff >> 2); // Shift right by 2 bits imm24 &= (1 << 24) - 1; // Take lower 24 bits inst = 0xeb000000 | imm24; } ((uint32_t *)srcFn)[0] = 0xe92d4000; ((uint32_t *)srcFn)[1] = inst; // BL/BLX ((uint32_t *)srcFn)[2] = 0xe8bd8000; // Offset 2 return 0; } #endif /* * Replaces the specified function with the specified stub function. * stubInfo - Record information about stub replacement, which is used for STUB_Reset restoration. * srcFn - Functions in the source code * stubFn - You need to replace the stub function that is inserted into the run. * return - 0:Success, non-zero:Error code */ int STUB_Replace(FuncStubInfo *stubInfo, void *srcFn, const void *stubFn) { (void)stubFn; #if defined(__arm__) || defined(__thumb__) stubInfo->fn = REAL_ADDR(srcFn); #else stubInfo->fn = srcFn; #endif StubCopy(stubInfo->codeBuf, (char *)(stubInfo->fn), CODESIZE); bool nextPage = false; uintptr_t srcPoint = (uintptr_t)srcFn; if ((g_pageSize - (srcPoint % g_pageSize)) < CODESIZE) { nextPage = true; } /* To modify instruction content corresponding to the source function, add memory write permission first */ if (mprotect(FuncPageGet(srcPoint), g_pageSize, PROT_READ | PROT_WRITE | PROT_EXEC) < 0) { perror("STUB_Replace: set error mprotect to w+r+x faild"); return -1; } if (nextPage) { if (mprotect(FuncPageGet(srcPoint + CODESIZE), g_pageSize, PROT_READ | PROT_WRITE | PROT_EXEC) < 0) { perror("STUB_Replace: set error mprotect to w+r+x faild"); return -1; } } #if defined(__x86_64__) /* * Short jump mode: Change to jmp jump instruction, and set jump position (the offset of the current position). * However, the offset cannot exceed 32 bits. There is a restriction on 64-bit systems. * [*(unsigned char *)srcFn = (unsigned char)0xE9;] [*(unsigned int *)((unsigned char *)srcFn + 1) = * (unsigned char *)stubFn - (unsigned char *)srcFn - CODESIZE;] Long jump mode: * Directly use a 64-bit address to jump, the following method is used. */ unsigned char *tmpBuf = (unsigned char *)srcFn; int idx = 0; tmpBuf[idx++] = 0xFF; // 0xFF 0x25 Constructing a long jump instruction tmpBuf[idx++] = 0x25; // 0xFF 0x25 Constructing a long jump instruction tmpBuf[idx++] = 0x0; tmpBuf[idx++] = 0x0; tmpBuf[idx++] = 0x0; tmpBuf[idx++] = 0x0; tmpBuf[idx++] = (((uintptr_t)stubFn) & 0xff); tmpBuf[idx++] = ((((uintptr_t)stubFn) >> 8) & 0xff); // Obtain the address by little-endian shift by 8 bits tmpBuf[idx++] = ((((uintptr_t)stubFn) >> 16) & 0xff); // Obtain the address by little-endian shift by 16 bits tmpBuf[idx++] = ((((uintptr_t)stubFn) >> 24) & 0xff); // Obtain the address by little-endian shift by 24 bits tmpBuf[idx++] = ((((uintptr_t)stubFn) >> 32) & 0xff); // Obtain the address by little-endian shift by 32 bits tmpBuf[idx++] = ((((uintptr_t)stubFn) >> 40) & 0xff); // Obtain the address by little-endian shift by 40 bits tmpBuf[idx++] = ((((uintptr_t)stubFn) >> 48) & 0xff); // Obtain the address by little-endian shift by 48 bits tmpBuf[idx++] = ((((uintptr_t)stubFn) >> 56) & 0xff); // Obtain the address by little-endian shift by 56 bits #elif defined(__aarch64__) || defined(_M_ARM64) /* ldr x9, PC+8 br x9 addr */ uint32_t ldrIns = 0x58000040 | 9; // 9 = 1001 uint32_t brIns = 0xd61f0120 | (9 << 5); // 9 << 5 #ifdef HITLS_BIG_ENDIAN ldrIns = CRYPT_SWAP32(ldrIns); brIns = CRYPT_SWAP32(brIns); #endif ((uint32_t *)srcFn)[0] = ldrIns; ((uint32_t *)srcFn)[1] = brIns; /* ldr x9, + 8 */ *(long long *)((char *)srcFn + 8) = (long long)stubFn; #elif defined(__arm__) || defined(__thumb__) if (((uintptr_t)srcFn) & 0x01) { if (ReplaceT32(srcFn, stubFn) != 0) { return -1; } } else { if (ReplaceA32(srcFn, stubFn) != 0) { return -1; } } #elif defined(__i386__) unsigned long tmpAdd = (unsigned long)stubFn - (unsigned long)(srcFn + 5); unsigned char *tmpBuf = (unsigned char *)srcFn; *(tmpBuf + 0) = 0xe9; *(unsigned long *)(tmpBuf + 1) = tmpAdd; #endif /* Flush cached instructions into */ __builtin___clear_cache((char *)(stubInfo->fn), (char *)(stubInfo->fn) + CODESIZE); /* The modification is complete. Remove the memory write permission. */ if (mprotect(FuncPageGet(srcPoint), g_pageSize, PROT_READ | PROT_EXEC) < 0) { perror("STUB_Replace: set error mprotect to r+x failed"); return -1; } if (nextPage) { if (mprotect(FuncPageGet(srcPoint + CODESIZE), g_pageSize, PROT_READ | PROT_EXEC) < 0) { perror("STUB_Replace: set error mprotect to r+x failed"); return -1; } } return 0; } /* * Restore the source function and remove the instrumentation. * stubInfo - Information logged when instrumentation * return - 0:Success, non-zero:Error code */ int STUB_Reset(FuncStubInfo *stubInfo) { bool nextPage = false; if (stubInfo->fn == NULL) { return -1; } uintptr_t srcPoint = (uintptr_t)stubInfo->fn; if ((g_pageSize - (srcPoint % g_pageSize)) < CODESIZE) { nextPage = true; } /* To modify instruction content corresponding to the source function, add memory write permission first */ if (mprotect(FuncPageGet((uintptr_t)stubInfo->fn), g_pageSize, PROT_READ | PROT_WRITE | PROT_EXEC) < 0) { perror("STUB_Reset: error mprotect to w+r+x faild"); return -1; } if (nextPage) { if (mprotect(FuncPageGet(srcPoint + CODESIZE), g_pageSize, PROT_READ | PROT_WRITE | PROT_EXEC) < 0) { perror("STUB_Replace: set error mprotect to w+r+x faild"); return -1; } } /* Restore the recorded rewritten original function mov/push/mov a few instructions */ if (StubCopy(stubInfo->fn, stubInfo->codeBuf, CODESIZE) < 0) { return -1; } /* Flush cached instructions into */ __builtin___clear_cache((char *)stubInfo->fn, (char *)stubInfo->fn + CODESIZE); /* If recovered, disable the memory modification permission. */ if (mprotect(FuncPageGet((uintptr_t)stubInfo->fn), g_pageSize, PROT_READ | PROT_EXEC) < 0) { perror("STUB_Reset: error mprotect to r+x failed"); return -1; } if (nextPage) { if (mprotect(FuncPageGet(srcPoint + CODESIZE), g_pageSize, PROT_READ | PROT_EXEC) < 0) { perror("STUB_Replace: set error mprotect to r+x failed"); return -1; } } StubSet(stubInfo, 0, sizeof(FuncStubInfo)); return 0; } /* * Initialize the dynamic stub change function and obtain the memory page size. Invoke the function once. * return - 0:Success, non-zero:Error code */ int STUB_Init(void) { if (g_pageSize != -1) { return 0; } g_pageSize = sysconf(_SC_PAGE_SIZE); if (g_pageSize < 0) { perror("STUB_Init: get system _SC_PAGE_SIZE configure failed"); return -1; } return 0; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/stub/stub_replace.c
C
unknown
12,791
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef STUB_REPALCE_H #define STUB_REPALCE_H #include <stdint.h> #if defined(__x86_64__) /* * The first 14 bytes of the function entry are used to construct the jump instruction. * Short jump instruction is 5 bytes, and Long jump instruction is 14 bytes. */ #define CODESIZE 14U #elif defined(__aarch64__) || defined(_M_ARM64) /* ARM64 needs 16 bytes to construct the jump instruction. */ #define CODESIZE 16U #elif defined(__arm__) /* ARM32 needs 12 bytes to construct the jump instruction. */ #define CODESIZE 12U #endif #ifdef __cplusplus extern "C" { #endif typedef struct { void *fn; unsigned char codeBuf[CODESIZE]; } FuncStubInfo; /* * Initialize the dynamic stub change function. Invoke the function once. * return - 0:Success, non-zero:Error code */ int STUB_Init(void); /* * Replaces the specified function with the specified stub function. * stubInfo - Record information about stub replacement, which is used for STUB_Reset restoration. * srcFn - Functions in the source code * stubFn - Need to replace the stub function that is inserted into the run. * return - 0:Success, non-zero:Error code */ int STUB_Replace(FuncStubInfo *stubInfo, void *srcFn, const void *stubFn); /* * Restore the source function and remove the instrumentation. * stubInfo - Information logged when instrumentation * return - 0:Success, non-zero:Error code */ int STUB_Reset(FuncStubInfo *stubInfo); #ifdef __cplusplus } #endif #endif // STUB_REPALCE_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/stub/stub_replace.h
C
unknown
2,018
# This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. SET(DT_LIBNAME "tls_frame") SET(HLT_LIBNAME "tls_hlt") SET(WRAPPER_LIBNAME "rec_wrapper") add_library(TLS_TEST_INTF INTERFACE) if(TLS_DEBUG) add_compile_definitions(TLS_TEST_INTF INTERFACE TLS_DEBUG) endif() target_include_directories(TLS_TEST_INTF INTERFACE ${openHiTLS_SRC}/platform/Secure_C/include ${openHiTLS_SRC}/include ${openHiTLS_SRC}/include/tls ${openHiTLS_SRC}/include/bsl ${openHiTLS_SRC}/include/crypto ${openHiTLS_SRC}/include/pki ${openHiTLS_SRC}/config/macro_config ${openHiTLS_SRC}/bsl/list/include ${openHiTLS_SRC}/bsl/obj/include ${openHiTLS_SRC}/bsl/include ${openHiTLS_SRC}/bsl/sal/include ${openHiTLS_SRC}/bsl/log/include ${openHiTLS_SRC}/bsl/time/include ${openHiTLS_SRC}/bsl/async/include ${openHiTLS_SRC}/bsl/hash/include ${openHiTLS_SRC}/bsl/uio/include ${openHiTLS_SRC}/bsl/uio/src ${openHiTLS_SRC}/pki/x509_cert/include ${openHiTLS_SRC}/tls/cert/hitls_x509_adapt ${openHiTLS_SRC}/tls/include ${openHiTLS_SRC}/tls/cert/cert_self ${openHiTLS_SRC}/tls/cert/include ${openHiTLS_SRC}/tls/config/include ${openHiTLS_SRC}/tls/cm/include ${openHiTLS_SRC}/tls/record/include ${openHiTLS_SRC}/tls/record/src ${openHiTLS_SRC}/tls/handshake/cookie/include ${openHiTLS_SRC}/tls/handshake/common/include ${openHiTLS_SRC}/tls/crypt/include/ ${openHiTLS_SRC}/tls/handshake/parse/include ${openHiTLS_SRC}/tls/handshake/pack/src ${openHiTLS_SRC}/tls/handshake/pack/include ${openHiTLS_SRC}/tls/ccs/include ${openHiTLS_SRC}/tls/alert/include ${openHiTLS_SRC}/tls/crypt/crypt_self ${openHiTLS_SRC}/testcode/framework/stub ${openHiTLS_SRC}/testcode/framework/tls/include ${openHiTLS_SRC}/testcode/framework/tls/io/include ${openHiTLS_SRC}/testcode/framework/tls/cert/include ${openHiTLS_SRC}/testcode/framework/tls/crypt/include ${openHiTLS_SRC}/testcode/framework/tls/msg/include ${openHiTLS_SRC}/testcode/framework/tls/base/include ${openHiTLS_SRC}/testcode/framework/tls/resource/include ${openHiTLS_SRC}/testcode/framework/tls/rpc/include ${openHiTLS_SRC}/testcode/framework/tls/process/include ${openHiTLS_SRC}/testcode/framework/tls/transfer/include ${openHiTLS_SRC}/testcode/framework/tls/frame/src ${openHiTLS_SRC}/testcode/framework/tls/io/src ${openHiTLS_SRC}/testcode/framework/tls/func_wrapper/include ${openHiTLS_SRC}/testcode/framework/tls/callback/include ${openHiTLS_SRC}/tls/feature/custom_extensions/include ) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/crypt/src CRYPT_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/io/src IO_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/frame/src FRAME_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/msg/src MSG_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/base/src BASE_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/resource/src RESOURCE_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/process/src PROCESS_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/rpc/src RPC_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/transfer/src TRANSFER_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/callback/src CALLBACK_SRC) aux_source_directory(${openHiTLS_SRC}/testcode/framework/tls/func_wrapper/src WRAPPER_SRC) SET(WRAPPER_SRC ${WRAPPER_SRC} ${openHiTLS_SRC}/testcode/framework/stub/stub_replace.c) target_compile_options(TLS_TEST_INTF INTERFACE -g) add_library(${HLT_LIBNAME} STATIC ${BASE_SRC} ${RESOURCE_SRC} ${CALLBACK_SRC} ${PROCESS_SRC} ${RPC_SRC} ${TRANSFER_SRC}) target_link_libraries(${HLT_LIBNAME} PRIVATE TLS_TEST_INTF) add_library(${DT_LIBNAME} STATIC ${BASE_SRC} ${CALLBACK_SRC} ${CRYPT_SRC} ${IO_SRC} ${FRAME_SRC} ${MSG_SRC}) target_link_libraries(${DT_LIBNAME} PRIVATE TLS_TEST_INTF) add_library(${WRAPPER_LIBNAME} STATIC ${WRAPPER_SRC}) target_link_libraries(${WRAPPER_LIBNAME} PRIVATE TLS_TEST_INTF) set_target_properties(${HLT_LIBNAME} ${DT_LIBNAME} ${WRAPPER_LIBNAME} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY "${openHiTLS_SRC}/testcode/output/lib" )
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/CMakeLists.txt
CMake
unknown
4,778
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef __LOCK_H__ #define __LOCK_H__ #include <pthread.h> typedef pthread_mutex_t Lock; /** * @brief Create a lock resource */ Lock *OsLockNew(void); /** * @brief Lock */ int OsLock(Lock *lock); /** * @brief Unlock */ int OsUnLock(Lock *lock); /** * @brief Release the lock resource */ void OsLockDestroy(Lock *lock); #endif // __LOCK_H__
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/base/include/lock.h
C
unknown
895
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef __LOGGER_H__ #define __LOGGER_H__ #include <stdio.h> #include <stdint.h> #include "securec.h" #ifdef __cplusplus extern "C" { #endif #define LOG_MAX_SIZE 1024 typedef enum { ENUM_LOG_LEVEL_TRACE, /* Basic level */ ENUM_LOG_LEVEL_DEBUG, /* Debugging level */ ENUM_LOG_LEVEL_WARNING, /* Warning level */ ENUM_LOG_LEVEL_ERROR, /* Error level */ ENUM_LOG_LEVEL_FATAL /* Fatal level */ } LogLevel; /** * @ingroup log * @brief Record error information based on the log level * * @par * Record error information based on the log level * * @attention * * @param[in] level Log level * @param[in] file File where the error information is stored * @param[in] line Number of the line where the error information is stored * @param[in] fmt Format character string for printing * * @retval 0 Success * @retval others failure */ int LogWrite(LogLevel level, const char *file, int line, const char *fmt, ...); #define LOG_DEBUG(...) LogWrite(ENUM_LOG_LEVEL_DEBUG, __FILE__, __LINE__, __VA_ARGS__) #define LOG_ERROR(...) LogWrite(ENUM_LOG_LEVEL_ERROR, __FILE__, __LINE__, __VA_ARGS__) #ifdef __cplusplus } #endif // __cplusplus #endif // __LOGGER_H__
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/base/include/logger.h
C
unknown
1,738
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <pthread.h> #include <stdint.h> #include "securec.h" #include "logger.h" #include "lock.h" Lock *OsLockNew(void) { pthread_mutexattr_t attr; Lock *lock; if ((lock = (Lock *)malloc(sizeof(pthread_mutex_t))) == NULL) { LOG_ERROR("OAL_Malloc error"); return NULL; } pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL); if (pthread_mutex_init(lock, &attr) != 0) { LOG_ERROR("pthread_mutex_init error"); pthread_mutexattr_destroy(&attr); free(lock); return NULL; } pthread_mutexattr_destroy(&attr); return lock; } int OsLock(Lock *lock) { if (pthread_mutex_lock(lock) != 0) { LOG_ERROR("pthread_mutex_lock error"); return -1; } return 0; } int OsUnLock(Lock *lock) { if (pthread_mutex_unlock(lock) != 0) { LOG_ERROR("pthread_mutex_unlock error"); return -1; } return 0; } void OsLockDestroy(Lock *lock) { if (lock == NULL) { return; } pthread_mutex_destroy(lock); free(lock); }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/base/src/lock.c
C
unknown
1,635
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <unistd.h> #include "logger.h" LogLevel GetLogLevel(void) { #ifdef TLS_DEBUG return ENUM_LOG_LEVEL_TRACE; #else return ENUM_LOG_LEVEL_FATAL; #endif } static const char *ConvertLevel2Str(LogLevel level) { switch (level) { case ENUM_LOG_LEVEL_TRACE: return "TRACE"; case ENUM_LOG_LEVEL_DEBUG: return "DEBUG"; case ENUM_LOG_LEVEL_WARNING: return "WARNING"; case ENUM_LOG_LEVEL_ERROR: return "ERROR"; case ENUM_LOG_LEVEL_FATAL: return "FATAL"; default: return "UNKNOWN"; } } int LogWrite(LogLevel level, const char *file, int line, const char *fmt, ...) { int len, ilen; LogLevel curLevel; va_list vargs; int tmpLevel = level; char logBuf[LOG_MAX_SIZE] = {0}; if ((tmpLevel < ENUM_LOG_LEVEL_TRACE) || (tmpLevel > ENUM_LOG_LEVEL_FATAL)) { return 0; } // Print logs whose levels are higher than or equal to the current level. curLevel = GetLogLevel(); if (level < curLevel) { return 0; } // Process the log header if (file == NULL || line == 0) { len = snprintf_s(logBuf, LOG_MAX_SIZE, (size_t)(LOG_MAX_SIZE - 1), "[%d_TEST_%s]", getpid(), ConvertLevel2Str((LogLevel)tmpLevel)); } else { len = snprintf_s(logBuf, LOG_MAX_SIZE, (size_t)(LOG_MAX_SIZE - 1), "[%d_TEST_%s][%s:%d]", getpid(), ConvertLevel2Str((LogLevel)tmpLevel), file, line); } if (len < 0 || len > LOG_MAX_SIZE - 1) { return 0; } va_start(vargs, fmt); ilen = vsnprintf_s(logBuf + len, (size_t)(LOG_MAX_SIZE - len), (size_t)(LOG_MAX_SIZE - len - 1), fmt, vargs); if (ilen < 0 || ilen > LOG_MAX_SIZE - len - 1) { // In the case of overflow truncation, the maximum value is used len = LOG_MAX_SIZE; logBuf[len - 1] = '\0'; goto EXIT; } len += ilen; logBuf[len] = '\n'; logBuf[len + 1] = '\0'; EXIT: va_end(vargs); #ifdef TLS_DEBUG printf("%s", logBuf); #endif return 0; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/base/src/logger.c
C
unknown
2,629
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CERT_CALLBACK_H #define CERT_CALLBACK_H #include "hlt_type.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Certificate callback */ int32_t RegCertCallback(CertCallbackType type); /** * @brief Memory callback */ int32_t RegMemCallback(MemCallbackType type); /** * @brief Loading Certificates and Private Keys by hitls x509 */ int32_t HiTLS_X509_LoadCertAndKey(HITLS_Config *tlsCfg, const char *caFile, const char *chainFile, const char *eeFile, const char *signFile, const char *privateKeyFile, const char *signPrivateKeyFile); void BinLogFixLenFunc(uint32_t logId, uint32_t logLevel, uint32_t logType, void *format, void *para1, void *para2, void *para3, void *para4); void BinLogVarLenFunc(uint32_t logId, uint32_t logLevel, uint32_t logType, void *format, void *para); void RegDefaultMemCallback(void); #ifdef __cplusplus } #endif #endif // CERT_CALLBACK_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/callback/include/cert_callback.h
C
unknown
1,443
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <unistd.h> #include <stdbool.h> #include <stdio.h> #include "hitls_build.h" #include "crypt_eal_pkey.h" #include "hlt_type.h" #include "hitls_cert_type.h" #include "hitls_cert.h" #include "hitls_type.h" #include "hitls_cert_reg.h" #include "hitls_config.h" #include "hitls_cert.h" #include "hitls_cert_init.h" #include "bsl_sal.h" #include "bsl_log.h" #include "bsl_err.h" #include "logger.h" #include "tls_config.h" #include "tls.h" #include "bsl_list.h" #include "hitls_x509_adapt.h" #include "hitls_cert_init.h" #include "hitls_pki_x509.h" #include "cert_method.h" #define SUCCESS 0 #define ERROR (-1) #define SINGLE_CERT_LEN (512) #define CERT_FILE_LEN (4 * 1024) int32_t RegCertCallback(CertCallbackType type) { switch (type) { case CERT_CALLBACK_DEFAULT: #ifndef HITLS_TLS_FEATURE_PROVIDER HITLS_CertMethodInit(); #endif break; default: return ERROR; } return SUCCESS; } void BinLogFixLenFunc(uint32_t logId, uint32_t logLevel, uint32_t logType, void *format, void *para1, void *para2, void *para3, void *para4) { (void)logLevel; (void)logType; printf("logId:%u\t", logId); printf(format, para1, para2, para3, para4); printf("\n"); return; } void BinLogVarLenFunc(uint32_t logId, uint32_t logLevel, uint32_t logType, void *format, void *para) { (void)logLevel; (void)logType; printf("logId:%u\t", logId); printf(format, para); printf("\n"); return; } void RegDefaultMemCallback(void) { BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_MALLOC, malloc); BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_FREE, free); BSL_ERR_Init(); BSL_LOG_SetBinLogLevel(BSL_LOG_LEVEL_DEBUG); #ifdef TLS_DEBUG BSL_LOG_BinLogFuncs logFunc = { BinLogFixLenFunc, BinLogVarLenFunc }; BSL_LOG_RegBinLogFunc(&logFunc); #endif LOG_DEBUG("HiTLS RegDefaultMemCallback"); return; } int32_t RegMemCallback(MemCallbackType type) { switch (type) { case MEM_CALLBACK_DEFAULT : RegDefaultMemCallback(); break; default: return ERROR; } return SUCCESS; } HITLS_CERT_X509 *HiTLS_X509_LoadCertFile(HITLS_Config *tlsCfg, const char *file) { #ifdef HITLS_TLS_FEATURE_PROVIDER HITLS_Lib_Ctx *libCtx = LIBCTX_FROM_CONFIG(tlsCfg); const char *attrName = ATTRIBUTE_FROM_CONFIG(tlsCfg); return HITLS_CERT_ProviderCertParse(libCtx, attrName, (const uint8_t *)file, strlen(file) + 1, TLS_PARSE_TYPE_FILE, "ASN1"); #else return HITLS_X509_Adapt_CertParse(tlsCfg, (const uint8_t *)file, strlen(file) + 1, TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); #endif } void *HiTLS_X509_LoadCertListToStore(HITLS_Config *tlsCfg, const char *fileList) { int32_t ret; char certList[MAX_CERT_LEN] = {0}; char certPath[SINGLE_CERT_LEN] = {0}; ret = memcpy_s(certList, MAX_CERT_LEN, fileList, strlen(fileList)); if (ret != EOK) { LOG_ERROR("memcpy_s Error"); return NULL; } void *store = SAL_CERT_StoreNew(tlsCfg->certMgrCtx); if(store == NULL){ LOG_ERROR("SAL_CERT_StoreNew Error"); return NULL; } char *rest = NULL; char *token = strtok_s(certList, ":", &rest); do { (void)memset_s(certPath, SINGLE_CERT_LEN, 0, SINGLE_CERT_LEN); ret = sprintf_s(certPath, SINGLE_CERT_LEN, "%s%s", DEFAULT_CERT_PATH, token); if (ret <= 0) { LOG_ERROR("sprintf_s Error"); HITLS_X509_StoreCtxFree(store); return NULL; } LOG_DEBUG("Load Cert Path is %s", certPath); HITLS_CERT_X509 *cert = HiTLS_X509_LoadCertFile(tlsCfg, certPath); if (cert == NULL) { HITLS_X509_StoreCtxFree(store); return NULL; } ret = HITLS_X509_Adapt_StoreCtrl(tlsCfg, store, CERT_STORE_CTRL_ADD_CERT_LIST, cert, NULL); if (ret != SUCCESS) { LOG_ERROR("X509_STORE_add_cert Error: path = %s.", certPath); HITLS_X509_StoreCtxFree(store); return NULL; } token = strtok_s(NULL, ":", &rest); } while (token != NULL); return store; } int32_t HITLS_X509_LoadEECertList(HITLS_Config *tlsCfg, const char *eeFileList, bool isEnc) { int32_t ret; HITLS_CERT_X509 *cert = NULL; char certList[MAX_CERT_LEN] = {0}; char certPath[SINGLE_CERT_LEN] = {0}; ret = memcpy_s(certList, MAX_CERT_LEN, eeFileList, strlen(eeFileList)); if (ret != EOK) { LOG_ERROR("memcpy_s Error"); return ERROR; } char *rest = NULL; char *token = strtok_s(certList, ":", &rest); do { (void)memset_s(certPath, SINGLE_CERT_LEN, 0, SINGLE_CERT_LEN); ret = sprintf_s(certPath, SINGLE_CERT_LEN, "%s%s", DEFAULT_CERT_PATH, token); if (ret <= 0) { LOG_ERROR("sprintf_s Error"); return ERROR; } LOG_DEBUG("Load Cert Path is %s", certPath); cert = HiTLS_X509_LoadCertFile(tlsCfg, certPath); if (cert == NULL) { LOG_ERROR("LoadCert Error: path = %s", certPath); return ERROR; } if (isEnc == true) { ret = HITLS_CFG_SetTlcpCertificate(tlsCfg, cert, 0, isEnc); } else { ret = HITLS_CFG_SetCertificate(tlsCfg, cert, 0); } if (ret != SUCCESS) { LOG_ERROR("HITLS_CFG_SetCertificate Error: path = %s.", certPath); HITLS_X509_Adapt_CertFree(cert); return ERROR; } token = strtok_s(NULL, ":", &rest); } while (token != NULL); return SUCCESS; } int32_t HITLS_X509_LoadPrivateKeyList(HITLS_Config *tlsCfg, const char *keyFileList, bool isEnc) { int32_t ret; HITLS_CERT_Key *key = NULL; char fileList[MAX_CERT_LEN] = {0}; char filePath[SINGLE_CERT_LEN] = {0}; ret = memcpy_s(fileList, MAX_CERT_LEN, keyFileList, strlen(keyFileList)); if (ret != EOK) { LOG_ERROR("memcpy_s Error"); return ERROR; } char *rest = NULL; char *token = strtok_s(fileList, ":", &rest); do { (void)memset_s(filePath, SINGLE_CERT_LEN, 0, SINGLE_CERT_LEN); ret = sprintf_s(filePath, SINGLE_CERT_LEN, "%s%s", DEFAULT_CERT_PATH, token); if (ret <= 0) { LOG_ERROR("sprintf_s Error"); return ERROR; } LOG_DEBUG("Load Cert Path is %s", filePath); #ifdef HITLS_TLS_FEATURE_PROVIDER key = HITLS_X509_Adapt_ProviderKeyParse(tlsCfg, (const uint8_t *)filePath, strlen(filePath), TLS_PARSE_TYPE_FILE, "ASN1", NULL); #else key = HITLS_X509_Adapt_KeyParse(tlsCfg, (const uint8_t *)filePath, strlen(filePath), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); #endif if (key == NULL) { LOG_ERROR("LoadCert Error: path = %s.", filePath); return ERROR; } if (isEnc == true) { ret = HITLS_CFG_SetTlcpPrivateKey(tlsCfg, key, 0, isEnc); } else { ret = HITLS_CFG_SetPrivateKey(tlsCfg, key, 0); } if (ret != SUCCESS) { LOG_ERROR("HITLS_CFG_SetPrivateKey Error: path = %s.", filePath); CRYPT_EAL_PkeyFreeCtx(key); return ERROR; } token = strtok_s(NULL, ":", &rest); } while (token != NULL); return SUCCESS; } void FRAME_HITLS_X509_FreeCert(HITLS_CERT_Store *caStore, HITLS_CERT_Store *chainStore) { if (caStore != NULL) { HITLS_X509_StoreCtxFree(caStore); } if (chainStore != NULL) { HITLS_X509_StoreCtxFree(chainStore); } return; } int32_t HiTLS_X509_LoadCertAndKey(HITLS_Config *tlsCfg, const char *caFile, const char *chainFile, const char *eeFile, const char *signFile, const char *privateKeyFile, const char *signPrivateKeyFile) { int32_t ret; if ((caFile != NULL) && (strncmp(caFile, "NULL", strlen(caFile)) != 0)) { HITLS_CERT_Store *caStore = HiTLS_X509_LoadCertListToStore(tlsCfg, caFile); if (caStore == NULL) { return ERROR; } ret = HITLS_CFG_SetCertStore(tlsCfg, caStore, 0); if (ret != SUCCESS) { HITLS_X509_StoreCtxFree(caStore); return ret; } } if ((chainFile != NULL) && (strncmp(chainFile, "NULL", strlen(chainFile)) != 0)) { HITLS_CERT_Store *chainStore = HiTLS_X509_LoadCertListToStore(tlsCfg, chainFile); if (chainStore == NULL) { return ERROR; } ret = HITLS_CFG_SetChainStore(tlsCfg, chainStore, 0); if (ret != SUCCESS) { HITLS_X509_StoreCtxFree(chainStore); return ret; } } bool hasTlcpSignCert = ((signFile != NULL) && (strncmp(signFile, "NULL", strlen(signFile)) != 0)); if (hasTlcpSignCert) { ret = HITLS_X509_LoadEECertList(tlsCfg, signFile, false); if (ret != SUCCESS) { return ret; } } if ((eeFile != NULL) && (strncmp(eeFile, "NULL", strlen(eeFile)) != 0)) { ret = HITLS_X509_LoadEECertList(tlsCfg, eeFile, hasTlcpSignCert); if (ret != SUCCESS) { return ret; } } if ((signPrivateKeyFile != NULL) && (strncmp(signPrivateKeyFile, "NULL", strlen(signPrivateKeyFile)) != 0)) { ret = HITLS_X509_LoadPrivateKeyList(tlsCfg, signPrivateKeyFile, false); if (ret != SUCCESS) { return ret; } if ((privateKeyFile != NULL) && (strncmp(privateKeyFile, "NULL", strlen(eeFile)) != 0)) { ret = HITLS_X509_LoadPrivateKeyList(tlsCfg, privateKeyFile, true); if (ret != SUCCESS) { return ret; } } } else { if ((privateKeyFile != NULL) && (strncmp(privateKeyFile, "NULL", strlen(eeFile)) != 0)) { ret = HITLS_X509_LoadPrivateKeyList(tlsCfg, privateKeyFile, false); if (ret != SUCCESS) { return ret; } } } return SUCCESS; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/callback/src/cert_callback.c
C
unknown
10,467
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef STUB_CRYPT_H #define STUB_CRYPT_H #ifdef __cplusplus extern "C" { #endif /** * @brief Stub the test framework */ void FRAME_RegCryptMethod(void); void FRAME_DeRegCryptMethod(void); #ifdef __cplusplus } #endif #endif // STUB_CRYPT_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/crypt/include/stub_crypt.h
C
unknown
788
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdint.h> #include <stddef.h> #include "hitls_build.h" #include "securec.h" #include "bsl_sal.h" #include "hitls_crypt_reg.h" #include "hitls_error.h" #include "hs_common.h" #include "config_type.h" #include "stub_replace.h" #include "crypt_default.h" #ifdef HITLS_TLS_FEATURE_PROVIDER #include "hitls_crypt.h" #include "crypt_eal_rand.h" #endif #define MD5_DIGEST_LENGTH 16 #define SHA1_DIGEST_LENGTH 20 #define SHA256_DIGEST_LENGTH 32 #define SHA384_DIGEST_LENGTH 48 #define SHA512_DIGEST_LENGTH 64 #define SM3_DIGEST_LENGTH 32 #define AEAD_TAG_LENGTH 16 typedef struct { HITLS_HashAlgo algo; uint8_t *key; uint32_t keyLen; } FRAME_HmacCtx; typedef struct { HITLS_HashAlgo algo; } FRAME_HashCtx; typedef struct { uint8_t *pubKey; uint32_t pubKeyLen; uint8_t *privateKey; uint32_t privateKeyLen; } FRAME_EcdhKey; typedef struct { uint8_t *p; uint8_t *g; uint16_t plen; uint16_t glen; uint8_t *pubKey; uint32_t pubKeyLen; uint8_t *privateKey; uint32_t privateKeyLen; } FRAME_DhKey; /** * @ingroup hitls_crypt_reg * @brief Obtain the random number * * @param buf [OUT] random number * @param len [IN] random number length * * @return 0 indicates success. Other values indicate failure */ int32_t STUB_CRYPT_RandBytesCallback(uint8_t *buf, uint32_t len) { if (memset_s(buf, len, 1, len) != EOK) { return HITLS_MEMCPY_FAIL; } return HITLS_SUCCESS; } int32_t STUB_CRYPT_RandBytesCallbackLibCtx(void *libCtx, uint8_t *buf, uint32_t len) { (void)libCtx; if (memset_s(buf, len, 1, len) != EOK) { return HITLS_MEMCPY_FAIL; } return HITLS_SUCCESS; } /** * @ingroup hitls_crypt_reg * @brief Generate a key pair based on the elliptic curve parameters * * @param curveParams [IN] Elliptic curve parameters * * @return Key handle */ HITLS_CRYPT_Key *STUB_CRYPT_GenerateEcdhKeyPairCallback(const HITLS_ECParameters *curveParams) { uint32_t keyLen = 0u; if (curveParams == NULL) { return NULL; } FRAME_EcdhKey *ecdhKey = (FRAME_EcdhKey *)BSL_SAL_Calloc(1u, sizeof(FRAME_EcdhKey)); if (ecdhKey == NULL) { return NULL; } const TLS_GroupInfo *groupInfo = NULL; switch (curveParams->type) { case HITLS_EC_CURVE_TYPE_NAMED_CURVE: groupInfo = ConfigGetGroupInfo(NULL, curveParams->param.namedcurve); if (groupInfo == NULL) { BSL_SAL_FREE(ecdhKey); return NULL; } keyLen = groupInfo->pubkeyLen; break; default: break; } uint8_t *pubKey = (uint8_t *)BSL_SAL_Malloc(keyLen); if (pubKey == NULL) { BSL_SAL_FREE(ecdhKey); return NULL; } memset_s(pubKey, keyLen, 1u, keyLen); uint8_t *privateKey = (uint8_t *)BSL_SAL_Malloc(keyLen); if (privateKey == NULL) { BSL_SAL_FREE(pubKey); BSL_SAL_FREE(ecdhKey); return NULL; } memset_s(privateKey, keyLen, 2u, keyLen); ecdhKey->pubKey = pubKey; ecdhKey->pubKeyLen = keyLen; ecdhKey->privateKey = privateKey; ecdhKey->privateKeyLen = keyLen; return ecdhKey; } HITLS_CRYPT_Key *STUB_CRYPT_GenerateEcdhKeyPairCallbackLibCtx(void *libCtx, const char *attrName, const HITLS_Config *config, const HITLS_ECParameters *curveParams) { (void)libCtx; (void)attrName; (void)config; return STUB_CRYPT_GenerateEcdhKeyPairCallback(curveParams); } /** * @ingroup hitls_crypt_reg * @brief Release the key * * @param key [IN] Key handle */ void STUB_CRYPT_FreeEcdhKeyCallback(HITLS_CRYPT_Key *key) { FRAME_EcdhKey *ecdhKey = (FRAME_EcdhKey *)key; if (ecdhKey != NULL) { BSL_SAL_FREE(ecdhKey->pubKey); BSL_SAL_FREE(ecdhKey->privateKey); BSL_SAL_FREE(ecdhKey); } return; } /** * @ingroup hitls_crypt_reg * @brief Extract the public key data * * @param key [IN] Key handle * @param pubKeyBuf [OUT] Public key data * @param bufLen [IN] buffer length * @param pubKeyLen [OUT] Public key data length * * @return 0 indicates success. Other values indicate failure */ int32_t STUB_CRYPT_GetEcdhEncodedPubKeyCallback(HITLS_CRYPT_Key *key, uint8_t *pubKeyBuf, uint32_t bufLen, uint32_t *pubKeyLen) { FRAME_EcdhKey *ecdhKey = (FRAME_EcdhKey *)key; if ((ecdhKey == NULL) || (pubKeyBuf == NULL) || (pubKeyLen == NULL) || (bufLen < ecdhKey->pubKeyLen)) { return HITLS_INTERNAL_EXCEPTION; } if (memcpy_s(pubKeyBuf, bufLen, ecdhKey->pubKey, ecdhKey->pubKeyLen) != EOK) { return HITLS_MEMCPY_FAIL; } *pubKeyLen = ecdhKey->pubKeyLen; return HITLS_SUCCESS; } /** * @ingroup hitls_crypt_reg * @brief Calculate the shared key based on the local key and peer public key * * @param key [IN] Key handle * @param pubKeyBuf [IN] Public key data * @param pubKeyLen [IN] Public key data length * @param sharedSecret [OUT] Shared key * @param sharedSecretLen [IN/OUT] IN: Maximum length of the key padding OUT: Key length * * @return 0 indicates success. Other values indicate failure */ int32_t STUB_CRYPT_CalcEcdhSharedSecretCallback(HITLS_CRYPT_Key *key, uint8_t *peerPubkey, uint32_t pubKeyLen, uint8_t *sharedSecret, uint32_t *sharedSecretLen) { FRAME_EcdhKey *ecdhKey = (FRAME_EcdhKey *)key; if ((ecdhKey == NULL) || (peerPubkey == NULL) || (sharedSecret == NULL) || (sharedSecretLen == NULL) || (ecdhKey->privateKeyLen > pubKeyLen) || (*sharedSecretLen < pubKeyLen)) { return HITLS_INTERNAL_EXCEPTION; } if (memset_s(sharedSecret, *sharedSecretLen, 3u, pubKeyLen) != EOK) { return HITLS_MEMCPY_FAIL; } *sharedSecretLen = pubKeyLen; return HITLS_SUCCESS; } int32_t STUB_CRYPT_CalcEcdhSharedSecretCallbackLibCtx(void *libCtx, const char *attrName, HITLS_CRYPT_Key *key, uint8_t *peerPubkey, uint32_t pubKeyLen, uint8_t *sharedSecret, uint32_t *sharedSecretLen) { (void)libCtx; (void)attrName; return STUB_CRYPT_CalcEcdhSharedSecretCallback(key, peerPubkey, pubKeyLen, sharedSecret, sharedSecretLen); } void STUB_CRYPT_FreeDhKeyCallback(HITLS_CRYPT_Key *key) { FRAME_DhKey *dhKey = (FRAME_DhKey *)key; if (dhKey != NULL) { BSL_SAL_FREE(dhKey->p); BSL_SAL_FREE(dhKey->g); BSL_SAL_FREE(dhKey->privateKey); BSL_SAL_FREE(dhKey->pubKey); BSL_SAL_FREE(dhKey); } return; } HITLS_CRYPT_Key *STUB_CRYPT_GenerateDhKeyBySecbitsCallback(int32_t secbits) { uint16_t plen; if (secbits >= 192) { plen = 1024; } else if (secbits >= 152) { plen = 512; } else if (secbits >= 128) { plen = 384; } else if (secbits >= 112) { plen = 256; } else { plen = 128; } FRAME_DhKey *dhKey = (FRAME_DhKey *)BSL_SAL_Calloc(1u, sizeof(FRAME_DhKey)); if (dhKey == NULL) { return NULL; } dhKey->p = BSL_SAL_Calloc(1u, plen); if (dhKey->p == NULL) { BSL_SAL_FREE(dhKey); return NULL; } memset_s(dhKey->p, plen, 1u, plen); dhKey->plen = plen; dhKey->g = BSL_SAL_Calloc(1u, plen); if (dhKey->g == NULL) { STUB_CRYPT_FreeDhKeyCallback(dhKey); return NULL; } memset_s(dhKey->g, plen, 2u, plen); dhKey->glen = plen; dhKey->pubKey = BSL_SAL_Calloc(1u, plen); if (dhKey->pubKey == NULL) { STUB_CRYPT_FreeDhKeyCallback(dhKey); return NULL; } memset_s(dhKey->pubKey, plen, 3u, plen); dhKey->pubKeyLen = plen; dhKey->privateKey = BSL_SAL_Calloc(1u, plen); if (dhKey->privateKey == NULL) { STUB_CRYPT_FreeDhKeyCallback(dhKey); return NULL; } memset_s(dhKey->privateKey, plen, 4u, plen); dhKey->privateKeyLen = plen; return dhKey; } HITLS_CRYPT_Key *STUB_CRYPT_GenerateDhKeyBySecbitsCallbackLibCtx(void *libCtx, const char *attrName, int32_t secbits) { (void)libCtx; (void)attrName; return STUB_CRYPT_GenerateDhKeyBySecbitsCallback(secbits); } HITLS_CRYPT_Key *STUB_CRYPT_GenerateDhKeyByParamsCallback(uint8_t *p, uint16_t plen, uint8_t *g, uint16_t glen) { if ((p == NULL) || (plen == 0) || (g == NULL) || (glen == 0)) { return NULL; } FRAME_DhKey *dhKey = (FRAME_DhKey *)BSL_SAL_Calloc(1u, sizeof(FRAME_DhKey)); if (dhKey == NULL) { return NULL; } dhKey->p = BSL_SAL_Dump(p, plen); if (dhKey->p == NULL) { BSL_SAL_FREE(dhKey); return NULL; } dhKey->plen = plen; dhKey->g = BSL_SAL_Dump(g, glen); if (dhKey->g == NULL) { STUB_CRYPT_FreeDhKeyCallback(dhKey); return NULL; } dhKey->glen = glen; dhKey->pubKey = BSL_SAL_Calloc(1u, plen); if (dhKey->pubKey == NULL) { STUB_CRYPT_FreeDhKeyCallback(dhKey); return NULL; } if (memset_s(dhKey->pubKey, plen, 3u, plen) != EOK) { STUB_CRYPT_FreeDhKeyCallback(dhKey); return NULL; } dhKey->pubKeyLen = plen; dhKey->privateKey = BSL_SAL_Calloc(1u, plen); if (dhKey->privateKey == NULL) { STUB_CRYPT_FreeDhKeyCallback(dhKey); return NULL; } if (memset_s(dhKey->privateKey, plen, 4u, plen) != EOK) { STUB_CRYPT_FreeDhKeyCallback(dhKey); return NULL; } dhKey->privateKeyLen = plen; return dhKey; } HITLS_CRYPT_Key *STUB_CRYPT_GenerateDhKeyByParamsCallbackLibCtx(void *libCtx, const char *attrName, uint8_t *p, uint16_t plen, uint8_t *g, uint16_t glen) { (void)libCtx; (void)attrName; return STUB_CRYPT_GenerateDhKeyByParamsCallback(p, plen, g, glen); } int32_t STUB_CRYPT_DHGetParametersCallback(HITLS_CRYPT_Key *key, uint8_t *p, uint16_t *plen, uint8_t *g, uint16_t *glen) { if ((key == NULL) || (plen == NULL) || (glen == NULL)) { return HITLS_INTERNAL_EXCEPTION; } FRAME_DhKey *dhKey = (FRAME_DhKey *)key; if (p != NULL) { if (memcpy_s(p, *plen, dhKey->p, dhKey->plen) != EOK) { return HITLS_MEMCPY_FAIL; } } if (g != NULL) { if (memcpy_s(g, *glen, dhKey->g, dhKey->glen) != EOK) { return HITLS_MEMCPY_FAIL; } } *plen = dhKey->plen; *glen = dhKey->glen; return HITLS_SUCCESS; } int32_t STUB_CRYPT_GetDhEncodedPubKeyCallback(HITLS_CRYPT_Key *key, uint8_t *pubKeyBuf, uint32_t bufLen, uint32_t *pubKeyLen) { if ((key == NULL) || (pubKeyBuf == NULL) || (pubKeyLen == NULL)) { return HITLS_INTERNAL_EXCEPTION; } FRAME_DhKey *dhKey = (FRAME_DhKey *)key; if (memcpy_s(pubKeyBuf, bufLen, dhKey->pubKey, dhKey->pubKeyLen) != EOK) { return HITLS_MEMCPY_FAIL; } *pubKeyLen = dhKey->pubKeyLen; return HITLS_SUCCESS; } int32_t STUB_CRYPT_CalcDhSharedSecretCallback(HITLS_CRYPT_Key *key, uint8_t *peerPubkey, uint32_t pubKeyLen, uint8_t *sharedSecret, uint32_t *sharedSecretLen) { FRAME_DhKey *dhKey = (FRAME_DhKey *)key; if ((dhKey == NULL) || (peerPubkey == NULL) || (sharedSecret == NULL) || (sharedSecretLen == NULL) || (dhKey->plen < pubKeyLen)) { return HITLS_INTERNAL_EXCEPTION; } if (memset_s(sharedSecret, *sharedSecretLen, 1u, dhKey->plen) != EOK) { return HITLS_MEMCPY_FAIL; } *sharedSecretLen = dhKey->plen; return HITLS_SUCCESS; } /** * @ingroup hitls_crypt_reg * @brief Obtain the HMAC length * * @param hashAlgo [IN] Hash algorithm * * @return HMAC length */ uint32_t STUB_CRYPT_HmacSizeCallback(HITLS_HashAlgo hashAlgo) { switch (hashAlgo) { case HITLS_HASH_MD5: return MD5_DIGEST_LENGTH; case HITLS_HASH_SHA1: return SHA1_DIGEST_LENGTH; case HITLS_HASH_SHA_256: return SHA256_DIGEST_LENGTH; case HITLS_HASH_SHA_384: return SHA384_DIGEST_LENGTH; case HITLS_HASH_SHA_512: return SHA512_DIGEST_LENGTH; default: break; } return 0u; } /** * @ingroup hitls_crypt_reg * @brief Initialize the HMAC context * * @param hashAlgo [IN] Hash algorithm * @param key [IN] Key * @param len [IN] Key length * * @return HMAC context */ HITLS_HMAC_Ctx *STUB_CRYPT_HmacInitCallback(HITLS_HashAlgo hashAlgo, const uint8_t *key, uint32_t len) { FRAME_HmacCtx *ctx = BSL_SAL_Calloc(1u, sizeof(FRAME_HmacCtx)); if (ctx == NULL) { return NULL; } ctx->algo = hashAlgo; ctx->key = BSL_SAL_Dump(key, len); if (ctx->key == NULL) { BSL_SAL_FREE(ctx); return NULL; } ctx->keyLen = len; return ctx; } HITLS_HMAC_Ctx *STUB_CRYPT_HmacInitCallbackLibCtx(void *libCtx, const char *attrName, HITLS_HashAlgo hashAlgo, const uint8_t *key, uint32_t len) { (void)libCtx; (void)attrName; return STUB_CRYPT_HmacInitCallback(hashAlgo, key, len); } /** * @ingroup hitls_crypt_reg * @brief Release the HMAC context * * @param ctx [IN] HMAC context */ void STUB_CRYPT_HmacFreeCallback(HITLS_HMAC_Ctx *ctx) { FRAME_HmacCtx *hmacCtx = (FRAME_HmacCtx *)ctx; if (hmacCtx != NULL) { BSL_SAL_FREE(hmacCtx->key); BSL_SAL_FREE(hmacCtx); } return; } /** * @ingroup hitls_crypt_reg * @brief Add the input data * * @param ctx [IN] HMAC context * @param data [IN] Input data * @param len [IN] Data length * * @return 0 indicates success. Other values indicate failure */ int32_t STUB_CRYPT_HmacUpdateCallback(HITLS_HMAC_Ctx *ctx, const uint8_t *data, uint32_t len) { if ((ctx == NULL) || (data == NULL) || len == 0) { return HITLS_INTERNAL_EXCEPTION; } return HITLS_SUCCESS; } /** * @ingroup hitls_crypt_reg * @brief Output the HMAC result * * @param ctx [IN] HMAC context * @param out [OUT] Output data * @param len [IN/OUT] IN: Maximum buffer length OUT: Output data length * * @return 0 indicates success. Other values indicate failure */ int32_t STUB_CRYPT_HmacFinalCallback(HITLS_HMAC_Ctx *ctx, uint8_t *out, uint32_t *len) { FRAME_HmacCtx *hmacCtx = (FRAME_HmacCtx *)ctx; if ((hmacCtx == NULL) || (out == NULL) || (len == NULL)) { return HITLS_INTERNAL_EXCEPTION; } uint32_t hmacSize = STUB_CRYPT_HmacSizeCallback(hmacCtx->algo); if ((hmacSize == 0u) || (hmacSize > *len)) { return HITLS_INTERNAL_EXCEPTION; } if (memset_s(out, *len, 4u, hmacSize) != EOK) { return HITLS_MEMCPY_FAIL; } *len = hmacSize; return HITLS_SUCCESS; } /** * @ingroup hitls_crypt_reg * @brief HMAC function * * @param hashAlgo [IN] Hash algorithm * @param key [IN] Key * @param keyLen [IN] Key length * @param in [IN] Input data * @param inLen [IN] Input data length * @param out [OUT] Output data * @param outLen [IN/OUT] IN: Maximum buffer length OUT: Output data length * * @return 0 indicates success. Other values indicate failure */ int32_t STUB_CRYPT_HmacCallback(HITLS_HashAlgo hashAlgo, const uint8_t *key, uint32_t keyLen, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { if ((key == NULL) || (keyLen == 0) || (in == NULL) || (inLen == 0) || (out == NULL) || (outLen == NULL)) { return HITLS_INTERNAL_EXCEPTION; } uint32_t hmacSize = STUB_CRYPT_HmacSizeCallback(hashAlgo); if ((hmacSize == 0u) || (hmacSize > *outLen)) { return HITLS_INTERNAL_EXCEPTION; } if (memset_s(out, *outLen, 4u, hmacSize) != EOK) { return HITLS_MEMCPY_FAIL; } *outLen = hmacSize; return HITLS_SUCCESS; } int32_t STUB_CRYPT_HmacCallbackLibCtx(void *libCtx, const char *attrName, HITLS_HashAlgo hashAlgo, const uint8_t *key, uint32_t keyLen, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { (void)libCtx; (void)attrName; return STUB_CRYPT_HmacCallback(hashAlgo, key, keyLen, in, inLen, out, outLen); } /** * @ingroup hitls_crypt_reg * @brief Obtain the hash length * * @param hashAlgo [IN] Hash algorithm * * @return Hash length */ uint32_t STUB_CRYPT_DigestSizeCallback(HITLS_HashAlgo hashAlgo) { return STUB_CRYPT_HmacSizeCallback(hashAlgo); } /** * @ingroup hitls_crypt_reg * @brief Initialize the hash context * * @param hashAlgo [IN] Hash algorithm * * @return hash context */ HITLS_HASH_Ctx *STUB_CRYPT_DigestInitCallback(HITLS_HashAlgo hashAlgo) { FRAME_HashCtx *ctx = BSL_SAL_Calloc(1u, sizeof(FRAME_HashCtx)); if (ctx == NULL) { return NULL; } ctx->algo = hashAlgo; return ctx; } HITLS_HASH_Ctx *STUB_CRYPT_DigestInitCallbackLibCtx(void *libCtx, const char *attrName, HITLS_HashAlgo hashAlgo) { (void)libCtx; (void)attrName; return STUB_CRYPT_DigestInitCallback(hashAlgo); } /** * @ingroup hitls_crypt_reg * @brief Copy hash Context * * @param ctx [IN] hash Context * * @return hash Context */ HITLS_HASH_Ctx *STUB_CRYPT_DigestCopyCallback(HITLS_HASH_Ctx *ctx) { FRAME_HashCtx *srcCtx = (FRAME_HashCtx *)ctx; if (srcCtx == NULL) { return NULL; } FRAME_HashCtx *newCtx = BSL_SAL_Calloc(1u, sizeof(FRAME_HashCtx)); if (newCtx == NULL) { return NULL; } newCtx->algo = srcCtx->algo; return newCtx; } /** * @ingroup hitls_crypt_reg * @brief Release the hash context * * @param ctx [IN] hash Context */ void STUB_CRYPT_DigestFreeCallback(HITLS_HASH_Ctx *ctx) { BSL_SAL_FREE(ctx); return; } /** * @ingroup hitls_crypt_reg * @brief Add the input data * * @param ctx [IN] hash Context * @param data [IN] Input data * @param len [IN] Input data length * * @return 0 indicates success. Other values indicate failure */ int32_t STUB_CRYPT_DigestUpdateCallback(HITLS_HASH_Ctx *ctx, const uint8_t *data, uint32_t len) { if ((ctx == NULL) || (data == NULL) || (len == 0u)) { return HITLS_INTERNAL_EXCEPTION; } return HITLS_SUCCESS; } /** * @ingroup hitls_crypt_reg * @brief Output the hash result * * @param ctx [IN] hash Context * @param out [IN] Output data * @param len [IN/OUT] IN: Maximum buffer length OUT: Output data length * * @return 0 indicates success. Other values indicate failure */ int32_t STUB_CRYPT_DigestFinalCallback(HITLS_HASH_Ctx *ctx, uint8_t *out, uint32_t *len) { FRAME_HashCtx *hashCtx = (FRAME_HashCtx *)ctx; if ((hashCtx == NULL) || (out == NULL) || (len == NULL)) { return HITLS_INTERNAL_EXCEPTION; } uint32_t digestSize = STUB_CRYPT_DigestSizeCallback(hashCtx->algo); if ((digestSize == 0) || (digestSize > *len)) { return HITLS_INTERNAL_EXCEPTION; } if (memset_s(out, *len, 5u, digestSize) != EOK) { return HITLS_MEMCPY_FAIL; } *len = digestSize; return HITLS_SUCCESS; } /** * @ingroup hitls_crypt_reg * @brief hash function * * @param hashAlgo [IN] Hash algorithm * @param in [IN] Input data * @param inLen [IN] Input data length * @param out [OUT] Output data * @param outLen [IN/OUT] IN: Maximum buffer length OUT: Output data length * * @return 0 indicates success. Other values indicate failure */ int32_t STUB_CRYPT_DigestCallback(HITLS_HashAlgo hashAlgo, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { if ((in == NULL) || (out == NULL) || (outLen == NULL) || (inLen == 0)) { return HITLS_INTERNAL_EXCEPTION; } uint32_t digestSize = STUB_CRYPT_DigestSizeCallback(hashAlgo); if ((digestSize == 0) || (digestSize > *outLen)) { return HITLS_INTERNAL_EXCEPTION; } if (memset_s(out, *outLen, 5u, digestSize) != EOK) { return HITLS_MEMCPY_FAIL; } *outLen = digestSize; return HITLS_SUCCESS; } int32_t STUB_CRYPT_DigestCallbackLibCtx(void *libCtx, const char *attrName, HITLS_HashAlgo hashAlgo, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { (void)libCtx; (void)attrName; return STUB_CRYPT_DigestCallback(hashAlgo, in, inLen, out, outLen); } /** * @ingroup hitls_crypt_reg * @brief Encryption * * @param cipher [IN] Key parameters * @param in [IN] Plaintext data * @param inLen [IN] Plaintext data length * @param out [OUT] Ciphertext data * @param outLen [IN/OUT] IN: maximum buffer length OUT: ciphertext data length * * @return 0 indicates success. Other values indicate failure */ int32_t STUB_CRYPT_EncryptCallback(const HITLS_CipherParameters *cipher, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { if (cipher->type == HITLS_AEAD_CIPHER) { if (*outLen < inLen + AEAD_TAG_LENGTH) { return HITLS_INTERNAL_EXCEPTION; } (void)memset_s(out, *outLen, 0, *outLen); if (inLen != 0 && memcpy_s(out, *outLen, in, inLen) != EOK) { return HITLS_MEMCPY_FAIL; } *outLen = inLen + AEAD_TAG_LENGTH; } else { *outLen = 0; return HITLS_INTERNAL_EXCEPTION; } return HITLS_SUCCESS; } int32_t STUB_CRYPT_EncryptCallbackLibCtx(void *libCtx, const char *attrName, const HITLS_CipherParameters *cipher, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { (void)libCtx; (void)attrName; return STUB_CRYPT_EncryptCallback(cipher, in, inLen, out, outLen); } /** * @ingroup hitls_crypt_reg * @brief Decrypt * * @param cipher [IN] Key parameters * @param in [IN] Ciphertext data * @param inLen [IN] Ciphertext data length * @param out [OUT] Plaintext data * @param outLen [IN/OUT] IN: Maximum buffer length OUT: Plaintext data length * * @return 0 indicates success. Other values indicate failure */ int32_t STUB_CRYPT_DecryptCallback(const HITLS_CipherParameters *cipher, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { if (cipher->type == HITLS_AEAD_CIPHER) { if (inLen < AEAD_TAG_LENGTH) { return HITLS_INTERNAL_EXCEPTION; } (void)memset_s(out, *outLen, 0, *outLen); if (memcpy_s(out, *outLen, in, inLen - AEAD_TAG_LENGTH) != EOK) { return HITLS_MEMCPY_FAIL; } *outLen = inLen - AEAD_TAG_LENGTH; } else { *outLen = 0; return HITLS_INTERNAL_EXCEPTION; } return HITLS_SUCCESS; } int32_t STUB_CRYPT_DecryptCallbackLibCtx(void *libCtx, const char *attrName, const HITLS_CipherParameters *cipher, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { (void)libCtx; (void)attrName; return STUB_CRYPT_DecryptCallback(cipher, in, inLen, out, outLen); } FuncStubInfo g_tmpRpInfo[16] = {0}; void FRAME_RegCryptMethod(void) { #ifndef HITLS_TLS_FEATURE_PROVIDER HITLS_CRYPT_BaseMethod cryptMethod = { 0 }; cryptMethod.randBytes = STUB_CRYPT_RandBytesCallback; cryptMethod.hmacSize = STUB_CRYPT_HmacSizeCallback; cryptMethod.hmacInit = STUB_CRYPT_HmacInitCallback; cryptMethod.hmacFree = STUB_CRYPT_HmacFreeCallback; cryptMethod.hmacUpdate = STUB_CRYPT_HmacUpdateCallback; cryptMethod.hmacFinal = STUB_CRYPT_HmacFinalCallback; cryptMethod.hmac = STUB_CRYPT_HmacCallback; cryptMethod.digestSize = STUB_CRYPT_DigestSizeCallback; cryptMethod.digestInit = STUB_CRYPT_DigestInitCallback; cryptMethod.digestCopy = STUB_CRYPT_DigestCopyCallback; cryptMethod.digestFree = CRYPT_DEFAULT_DigestFree; cryptMethod.digestUpdate = STUB_CRYPT_DigestUpdateCallback; cryptMethod.digestFinal = STUB_CRYPT_DigestFinalCallback; cryptMethod.digest = STUB_CRYPT_DigestCallback; cryptMethod.encrypt = STUB_CRYPT_EncryptCallback; cryptMethod.decrypt = STUB_CRYPT_DecryptCallback; cryptMethod.cipherFree = CRYPT_DEFAULT_CipherFree; HITLS_CRYPT_RegisterBaseMethod(&cryptMethod); HITLS_CRYPT_EcdhMethod ecdhMethod = { 0 }; ecdhMethod.generateEcdhKeyPair = STUB_CRYPT_GenerateEcdhKeyPairCallback; ecdhMethod.freeEcdhKey = CRYPT_DEFAULT_FreeKey; ecdhMethod.getEcdhPubKey = STUB_CRYPT_GetEcdhEncodedPubKeyCallback; ecdhMethod.calcEcdhSharedSecret = STUB_CRYPT_CalcEcdhSharedSecretCallback; HITLS_CRYPT_RegisterEcdhMethod(&ecdhMethod); HITLS_CRYPT_DhMethod dhMethod = { 0 }; dhMethod.generateDhKeyBySecbits = STUB_CRYPT_GenerateDhKeyBySecbitsCallback; dhMethod.generateDhKeyByParams = STUB_CRYPT_GenerateDhKeyByParamsCallback; dhMethod.freeDhKey = CRYPT_DEFAULT_FreeKey; dhMethod.getDhParameters = STUB_CRYPT_DHGetParametersCallback; dhMethod.getDhPubKey = STUB_CRYPT_GetDhEncodedPubKeyCallback; dhMethod.calcDhSharedSecret = STUB_CRYPT_CalcDhSharedSecretCallback; HITLS_CRYPT_RegisterDhMethod(&dhMethod); #else STUB_Init(); STUB_Replace(&g_tmpRpInfo[0], CRYPT_EAL_RandbytesEx, STUB_CRYPT_RandBytesCallbackLibCtx); STUB_Replace(&g_tmpRpInfo[1], HITLS_CRYPT_HMAC_Init, STUB_CRYPT_HmacInitCallbackLibCtx); STUB_Replace(&g_tmpRpInfo[2], HITLS_CRYPT_HMAC, STUB_CRYPT_HmacCallbackLibCtx); STUB_Replace(&g_tmpRpInfo[3], HITLS_CRYPT_DigestInit, STUB_CRYPT_DigestInitCallbackLibCtx); STUB_Replace(&g_tmpRpInfo[4], HITLS_CRYPT_Digest, STUB_CRYPT_DigestCallbackLibCtx); STUB_Replace(&g_tmpRpInfo[5], HITLS_CRYPT_Encrypt, STUB_CRYPT_EncryptCallbackLibCtx); STUB_Replace(&g_tmpRpInfo[6], HITLS_CRYPT_Decrypt, STUB_CRYPT_DecryptCallbackLibCtx); STUB_Replace(&g_tmpRpInfo[7], HITLS_CRYPT_GenerateEcdhKey, STUB_CRYPT_GenerateEcdhKeyPairCallbackLibCtx); STUB_Replace(&g_tmpRpInfo[8], HITLS_CRYPT_EcdhCalcSharedSecret, STUB_CRYPT_CalcEcdhSharedSecretCallbackLibCtx); STUB_Replace(&g_tmpRpInfo[9], HITLS_CRYPT_GenerateDhKeyByParameters, STUB_CRYPT_GenerateDhKeyByParamsCallbackLibCtx); STUB_Replace(&g_tmpRpInfo[10], HITLS_CRYPT_GenerateDhKeyBySecbits, STUB_CRYPT_GenerateDhKeyBySecbitsCallbackLibCtx); #endif return; } void FRAME_DeRegCryptMethod(void) { #ifndef HITLS_TLS_FEATURE_PROVIDER HITLS_CRYPT_BaseMethod cryptMethod = { 0 }; HITLS_CRYPT_RegisterBaseMethod(&cryptMethod); HITLS_CRYPT_EcdhMethod ecdhMethod = { 0 }; HITLS_CRYPT_RegisterEcdhMethod(&ecdhMethod); HITLS_CRYPT_DhMethod dhMethod = { 0 }; HITLS_CRYPT_RegisterDhMethod(&dhMethod); #else STUB_Reset(&g_tmpRpInfo[0]); STUB_Reset(&g_tmpRpInfo[1]); STUB_Reset(&g_tmpRpInfo[2]); STUB_Reset(&g_tmpRpInfo[3]); STUB_Reset(&g_tmpRpInfo[4]); STUB_Reset(&g_tmpRpInfo[5]); STUB_Reset(&g_tmpRpInfo[6]); STUB_Reset(&g_tmpRpInfo[7]); STUB_Reset(&g_tmpRpInfo[8]); STUB_Reset(&g_tmpRpInfo[9]); STUB_Reset(&g_tmpRpInfo[10]); #endif return; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/crypt/src/stub_crypt.c
C
unknown
27,132
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <string.h> #include "securec.h" #include "bsl_sal.h" #include "hitls_error.h" #include "hs_ctx.h" #include "hs_common.h" #include "change_cipher_spec.h" #include "stub_replace.h" #include "frame_tls.h" #include "frame_io.h" #include "frame_link.h" #include "parse.h" #define ENTER_USER_SPECIFY_STATE (HITLS_UIO_FAIL_START + 0xFFFF) #define READ_BUF_SIZE 18432 HITLS_HandshakeState g_nextState; bool g_isClient; int32_t FRAME_TrasferMsgBetweenLink(FRAME_LinkObj *linkA, FRAME_LinkObj *linkB) { int32_t ret = HITLS_SUCCESS; uint32_t readLen = 0; char *buffer = BSL_SAL_Calloc(1u, MAX_RECORD_LENTH); if (buffer == NULL) { return HITLS_MEMALLOC_FAIL; } // linkA->io->userData to buffer ret = FRAME_TransportSendMsg(linkA->io, buffer, MAX_RECORD_LENTH, &readLen); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(buffer); return ret; } if (readLen == 0) { BSL_SAL_FREE(buffer); return HITLS_SUCCESS; } // buffer to linkB->io->userData ret = FRAME_TransportRecMsg(linkB->io, buffer, readLen); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(buffer); return ret; } BSL_SAL_FREE(buffer); return HITLS_SUCCESS; } static int32_t STUB_ChangeState(TLS_Ctx *ctx, uint32_t nextState) { int32_t ret = HITLS_SUCCESS; if (g_nextState == nextState) { if (g_isClient == ctx->isClient) { HS_CleanMsg(ctx->hsCtx->hsMsg); ctx->hsCtx->hsMsg = NULL; ret = HITLS_REC_NORMAL_RECV_BUF_EMPTY; } } HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; hsCtx->state = nextState; return ret; } static bool StateCompare(FRAME_LinkObj *link, bool isClient, HITLS_HandshakeState state) { if ((isClient == link->ssl->isClient) && (link->ssl->hsCtx != NULL) && (link->ssl->hsCtx->state == state)) { if (state != TRY_RECV_FINISH && state != TRY_RECV_CERTIFICATE) { return true; } /* In tls1.3, if the single-end verification is used, the server may receive the CCS message in the TRY_RECV_FINISH phase */ if (state == TRY_RECV_FINISH){ if (link->needStopBeforeRecvCCS || CCS_IsRecv(link->ssl) == true || (link->ssl->config.tlsConfig.maxVersion == HITLS_VERSION_TLS13 && isClient == true) || (link->ssl->config.tlsConfig.maxVersion == HITLS_VERSION_TLS13 && link->ssl->config.tlsConfig.isSupportClientVerify == true)) { return true; } } // In tls1.3, the server may receive the CCS message in the TRY_RECV_CERTIFICATIONATE phase if (state == TRY_RECV_CERTIFICATE){ if (link->needStopBeforeRecvCCS || CCS_IsRecv(link->ssl) == true || #ifdef HITLS_TLS_PROTO_TLS13 link->ssl->hsCtx->haveHrr == true || #endif /* HITLS_TLS_PROTO_TLS13 */ link->ssl->config.tlsConfig.maxVersion != HITLS_VERSION_TLS13 || isClient == true) { return true; } } } return false; } int32_t FRAME_CreateConnection(FRAME_LinkObj *client, FRAME_LinkObj *server, bool isClient, HITLS_HandshakeState state) { int32_t clientRet; int32_t serverRet; int32_t ret; uint32_t count = 0; if (client == NULL || server == NULL) { return HITLS_NULL_INPUT; } g_isClient = isClient; g_nextState = state; FuncStubInfo tmpRpInfo = {0}; STUB_Init(); STUB_Replace(&tmpRpInfo, HS_ChangeState, STUB_ChangeState); do { // Check whether the client needs to be stopped. If yes, return success if (StateCompare(client, isClient, state)) { ret = HITLS_SUCCESS; break; } // Invoke the client to establish a connection clientRet = HITLS_Connect(client->ssl); if (clientRet != HITLS_SUCCESS) { ret = clientRet; if ((clientRet != HITLS_REC_NORMAL_IO_BUSY) && (clientRet != HITLS_REC_NORMAL_RECV_BUF_EMPTY)) { break; } } // Transfer the message to the server ret = FRAME_TrasferMsgBetweenLink(client, server); if (ret != HITLS_SUCCESS) { break; } // Check whether the server needs to be stopped. If yes, return success if (StateCompare(server, isClient, state)) { ret = HITLS_SUCCESS; break; } // Invoke the server to establish a connection serverRet = HITLS_Accept(server->ssl); if (serverRet != HITLS_SUCCESS) { ret = serverRet; if ((serverRet != HITLS_REC_NORMAL_IO_BUSY) && (serverRet != HITLS_REC_NORMAL_RECV_BUF_EMPTY)) { break; } } // Transfer the message to the client ret = FRAME_TrasferMsgBetweenLink(server, client); if (ret != HITLS_SUCCESS) { break; } /* To receive TLS1.3 new session ticket messages */ if (clientRet == HITLS_SUCCESS) { uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ret = HITLS_Read(client->ssl, readBuf, READ_BUF_SIZE, &readLen); // No application data. return HITLS_REC_NORMAL_RECV_BUF_EMPTY if (ret != HITLS_REC_NORMAL_RECV_BUF_EMPTY) { return ret; } } // If the connection is set up on both sides, return success if (clientRet == HITLS_SUCCESS && serverRet == HITLS_SUCCESS) { ret = HITLS_SUCCESS; break; } count++; ret = HITLS_INTERNAL_EXCEPTION; // Prevent infinite loop. No more than 30 messages are exchanged between the client and server during the handshake } while (count < 30); //Check whether the hsCtx status meets the expectation. If hsCtx is destructed, HITLS_INTERNAL_EXCEPTION is returned if (state != HS_STATE_BUTT) { FRAME_LinkObj *point = (isClient) ? (client) : (server); if (point->ssl->hsCtx == NULL) { ret = HITLS_INTERNAL_EXCEPTION; } else if (point->ssl->hsCtx->state != state) { ret = HITLS_INTERNAL_EXCEPTION; } } STUB_Reset(&tmpRpInfo); return ret; } int32_t FRAME_CreateRenegotiation(FRAME_LinkObj *linkA, FRAME_LinkObj *linkB) { int32_t clientRet; int32_t serverRet; int32_t ret; uint32_t count = 0; // renegotiation signal uint8_t writeBuf[1] = {1}; uint8_t readBuf[32] = {0}; // buffer for receive temporary messages, 32 bytes long uint32_t readBufLen = 0; if (linkA->ssl->state != CM_STATE_RENEGOTIATION) { return HITLS_SUCCESS; } do { uint32_t len = 0; clientRet = HITLS_Write(linkA->ssl, writeBuf, sizeof(writeBuf), &len); if (clientRet != HITLS_SUCCESS) { ret = clientRet; if ((clientRet != HITLS_REC_NORMAL_IO_BUSY) && (clientRet != HITLS_REC_NORMAL_RECV_BUF_EMPTY)) { break; } } ret = FRAME_TrasferMsgBetweenLink(linkA, linkB); if (ret != HITLS_SUCCESS) { break; } readBufLen = 0; (void)memset_s(readBuf, sizeof(readBuf), 0, sizeof(readBuf)); serverRet = HITLS_Read(linkB->ssl, readBuf, sizeof(readBuf), &readBufLen); if (serverRet != HITLS_SUCCESS) { ret = serverRet; if ((serverRet != HITLS_REC_NORMAL_IO_BUSY) && (serverRet != HITLS_REC_NORMAL_RECV_BUF_EMPTY)) { break; } } ret = FRAME_TrasferMsgBetweenLink(linkB, linkA); if (ret != HITLS_SUCCESS) { break; } // If the connection is set up on both sides, return success if (clientRet == HITLS_SUCCESS && serverRet == HITLS_SUCCESS && linkA->ssl->state == CM_STATE_TRANSPORTING && linkB->ssl->state == CM_STATE_TRANSPORTING) { if ((readBufLen != sizeof(writeBuf)) || (memcmp(writeBuf, readBuf, readBufLen) != 0)) { ret = HITLS_INTERNAL_EXCEPTION; } else { ret = HITLS_SUCCESS; } break; } count++; ret = HITLS_INTERNAL_EXCEPTION; // Prevent infinite loop. No more than 30 messages are exchanged between the client and server during the handshake } while (count < 30); return ret; } int32_t FRAME_CreateRenegotiationServer(FRAME_LinkObj *server, FRAME_LinkObj *client) { int32_t clientRet; int32_t serverRet; int32_t ret; uint32_t count = 0; // renegotiation signal uint8_t readBuf[32] = {0}; // buffer for receive temporary messages, 32 bytes long uint32_t readBufLen = 0; if (server->ssl->state != CM_STATE_RENEGOTIATION) { return HITLS_SUCCESS; } do { readBufLen = 0; (void)memset_s(readBuf, sizeof(readBuf), 0, sizeof(readBuf)); serverRet = HITLS_Read(server->ssl, readBuf, sizeof(readBuf), &readBufLen); if (serverRet != HITLS_SUCCESS) { ret = serverRet; if ((serverRet != HITLS_REC_NORMAL_IO_BUSY) && (serverRet != HITLS_REC_NORMAL_RECV_BUF_EMPTY)) { break; } } ret = FRAME_TrasferMsgBetweenLink(server, client); if (ret != HITLS_SUCCESS) { break; } readBufLen = 0; (void)memset_s(readBuf, sizeof(readBuf), 0, sizeof(readBuf)); clientRet = HITLS_Read(client->ssl, readBuf, sizeof(readBuf), &readBufLen); if (clientRet != HITLS_SUCCESS) { ret = clientRet; if ((clientRet != HITLS_REC_NORMAL_IO_BUSY) && (clientRet != HITLS_REC_NORMAL_RECV_BUF_EMPTY)) { break; } } ret = FRAME_TrasferMsgBetweenLink(client, server); if (ret != HITLS_SUCCESS) { break; } // If the connection is set up on both sides, return success if (clientRet == HITLS_REC_NORMAL_RECV_BUF_EMPTY && serverRet == HITLS_REC_NORMAL_RECV_BUF_EMPTY && server->ssl->state == CM_STATE_TRANSPORTING && client->ssl->state == CM_STATE_TRANSPORTING) { ret = HITLS_SUCCESS; break; } count++; ret = HITLS_INTERNAL_EXCEPTION; // Prevent infinite loop. No more than 30 messages are exchanged between the client and server during the handshake } while (count < 30); return ret; } int32_t FRAME_CreateRenegotiationState(FRAME_LinkObj *client, FRAME_LinkObj *server, bool isClient, HITLS_HandshakeState state) { int32_t clientRet; int32_t serverRet; int32_t ret; uint32_t count = 0; // renegotiation signal uint8_t writeBuf[1] = {1}; uint8_t readBuf[32] = {0}; // buffer for receive temporary messages, 32 bytes long uint32_t readBufLen = 0; if (client->ssl->state != CM_STATE_RENEGOTIATION) { return HITLS_SUCCESS; } g_isClient = isClient; g_nextState = state; FuncStubInfo tmpRpInfo = {0}; STUB_Init(); STUB_Replace(&tmpRpInfo, HS_ChangeState, STUB_ChangeState); do { // Check whether the client needs to be stopped. If yes, return success if (StateCompare(client, isClient, state)) { ret = HITLS_SUCCESS; break; } uint32_t len = 0; clientRet = HITLS_Write(client->ssl, writeBuf, sizeof(writeBuf), &len); if (clientRet != HITLS_SUCCESS) { ret = clientRet; if ((clientRet != HITLS_REC_NORMAL_IO_BUSY) && (clientRet != HITLS_REC_NORMAL_RECV_BUF_EMPTY)) { break; } } ret = FRAME_TrasferMsgBetweenLink(client, server); if (ret != HITLS_SUCCESS) { break; } // Check whether the server needs to be stopped. If yes, return success if (StateCompare(server, isClient, state)) { ret = HITLS_SUCCESS; break; } readBufLen = 0; (void)memset_s(readBuf, sizeof(readBuf), 0, sizeof(readBuf)); serverRet = HITLS_Read(server->ssl, readBuf, sizeof(readBuf), &readBufLen); if (serverRet != HITLS_SUCCESS) { ret = serverRet; if ((serverRet != HITLS_REC_NORMAL_IO_BUSY) && (serverRet != HITLS_REC_NORMAL_RECV_BUF_EMPTY)) { break; } } ret = FRAME_TrasferMsgBetweenLink(server, client); if (ret != HITLS_SUCCESS) { break; } // If the connection is set up on both sides, return success if (clientRet == HITLS_SUCCESS && serverRet == HITLS_SUCCESS && client->ssl->state == CM_STATE_TRANSPORTING && server->ssl->state == CM_STATE_TRANSPORTING) { if ((readBufLen != sizeof(writeBuf)) || (memcmp(writeBuf, readBuf, readBufLen) != 0)) { ret = HITLS_INTERNAL_EXCEPTION; } else { ret = HITLS_SUCCESS; } break; } count++; ret = HITLS_INTERNAL_EXCEPTION; // Prevent infinite loop. No more than 30 messages are exchanged between the client and server during the handshake } while (count < 30); //Check whether the hsCtx status meets the expectation. If hsCtx is destructed, HITLS_INTERNAL_EXCEPTION is returned if (state != HS_STATE_BUTT) { FRAME_LinkObj *point = (isClient) ? (client) : (server); if (point->ssl->hsCtx == NULL) { ret = HITLS_INTERNAL_EXCEPTION; } else if (point->ssl->hsCtx->state != state) { ret = HITLS_INTERNAL_EXCEPTION; } } STUB_Reset(&tmpRpInfo); return ret; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/frame/src/frame_connect.c
C
unknown
14,226
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include "hitls_build.h" #include "cert_callback.h" #include "bsl_sal.h" #include "bsl_log.h" #include "bsl_err.h" #include "crypt_algid.h" #include "hitls_crypt_init.h" #include "crypt_eal_rand.h" #include "hitls_cert_init.h" #include "bsl_log.h" static void *StdMalloc(uint32_t len) { return malloc((uint32_t)len); } static void StdFree(void *addr) { free(addr); } static void *StdMallocFail(uint32_t len) { (void)len; return NULL; } void BinLogFixLenFunc(uint32_t logId, uint32_t logLevel, uint32_t logType, void *format, void *para1, void *para2, void *para3, void *para4); void BinLogVarLenFunc(uint32_t logId, uint32_t logLevel, uint32_t logType, void *format, void *para); void FRAME_Init(void) { BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_MALLOC, StdMalloc); BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_FREE, StdFree); BSL_ERR_Init(); #ifdef TLS_DEBUG BSL_LOG_SetBinLogLevel(BSL_LOG_LEVEL_DEBUG); BSL_LOG_BinLogFuncs logFunc = { BinLogFixLenFunc, BinLogVarLenFunc }; BSL_LOG_RegBinLogFunc(&logFunc); #endif #ifdef HITLS_TLS_FEATURE_PROVIDER CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_SHA256, "provider=default", NULL, 0, NULL); #else CRYPT_EAL_RandInit(CRYPT_RAND_SHA256, NULL, NULL, NULL, 0); HITLS_CertMethodInit(); HITLS_CryptMethodInit(); #endif return; } void FRAME_DeInit(void) { BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_MALLOC, StdMallocFail); BSL_SAL_CallBack_Ctrl(BSL_SAL_MEM_FREE, StdFree); BSL_ERR_DeInit(); return; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/frame/src/frame_init.c
C
unknown
2,125
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "securec.h" #include "bsl_sal.h" #include "uio_base.h" #include "uio_abstraction.h" #include "hitls_crypt_type.h" #include "hitls_cert_type.h" #include "hitls_error.h" #include "hlt_type.h" #include "cert_callback.h" #include "frame_tls.h" #include "frame_io.h" #include "frame_link.h" #define MAX_CERT_PATH_LENGTH (1024) HITLS_Ctx *FRAME_CreateDefaultDtlsObj(void) { HITLS_Config *config = HITLS_CFG_NewDTLS12Config(); if (config == NULL) { return NULL; } char verifyPath[MAX_CERT_PATH_LENGTH] = {0}; char chainPath[MAX_CERT_PATH_LENGTH] = {0}; char certPath[MAX_CERT_PATH_LENGTH] = {0}; char keyPath[MAX_CERT_PATH_LENGTH] = {0}; if (sprintf_s(verifyPath, MAX_CERT_PATH_LENGTH, "%s:%s", RSA_SHA_CA_PATH, ECDSA_SHA_CA_PATH) <= 0) { HITLS_CFG_FreeConfig(config); return NULL; } if (sprintf_s(chainPath, MAX_CERT_PATH_LENGTH, "%s:%s", RSA_SHA_CHAIN_PATH, ECDSA_SHA_CHAIN_PATH) <= 0) { HITLS_CFG_FreeConfig(config); return NULL; } if (sprintf_s(certPath, MAX_CERT_PATH_LENGTH, "%s:%s", RSA_SHA256_EE_PATH3, ECDSA_SHA256_EE_PATH) <= 0) { HITLS_CFG_FreeConfig(config); return NULL; } if (sprintf_s(keyPath, MAX_CERT_PATH_LENGTH, "%s:%s", RSA_SHA256_PRIV_PATH3, ECDSA_SHA256_PRIV_PATH) <= 0) { HITLS_CFG_FreeConfig(config); return NULL; } int32_t ret = HiTLS_X509_LoadCertAndKey(config, verifyPath, chainPath, certPath, NULL, keyPath, NULL); if (ret != HITLS_SUCCESS) { HITLS_CFG_FreeConfig(config); return NULL; } HITLS_Ctx *ctx = HITLS_New(config); if (ctx == NULL) { HITLS_CFG_FreeConfig(config); return NULL; } HITLS_CFG_FreeConfig(config); return ctx; } FRAME_LinkObj *CreateLink(HITLS_Config *config, BSL_UIO_TransportType type) { BSL_UIO_Method method = {0}; BSL_UIO *io = NULL; FrameUioUserData *ioUserdata = NULL; const BSL_UIO_Method *ori = NULL; switch (type) { case BSL_UIO_TCP: #ifdef HITLS_BSL_UIO_TCP ori = BSL_UIO_TcpMethod(); #endif break; case BSL_UIO_UDP: #ifdef HITLS_BSL_UIO_UDP ori = BSL_UIO_UdpMethod(); #endif break; default: #ifdef HITLS_BSL_UIO_SCTP ori = BSL_UIO_SctpMethod(); #endif break; } if (memcpy_s(&method, sizeof(BSL_UIO_Method), ori, sizeof(method)) != EOK) { return NULL; } FRAME_LinkObj *linkObj = BSL_SAL_Calloc(1u, sizeof(FRAME_LinkObj)); if (linkObj == NULL) { return NULL; } HITLS_CFG_SetReadAhead(config, 1); #ifdef HITLS_TLS_FEATURE_FLIGHT HITLS_CFG_SetFlightTransmitSwitch(config, false); #endif HITLS_Ctx *sslObj = HITLS_New(config); if (sslObj == NULL) { goto ERR; } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) if (type == BSL_UIO_UDP) { HITLS_SetMtu(sslObj, 16384); } #endif INIT_IO_METHOD(method, type, FRAME_Write, FRAME_Read, FRAME_Ctrl); io = BSL_UIO_New(&method); if (io == NULL) { goto ERR; } ioUserdata = FRAME_IO_CreateUserData(); if (ioUserdata == NULL) { goto ERR; } uint32_t ret = BSL_UIO_SetUserData(io, ioUserdata); if (ret != HITLS_SUCCESS) { goto ERR; } int32_t fd = 666; // Set any fd as the value of the underlying transfer I/O ret = BSL_UIO_Ctrl(io, BSL_UIO_SET_FD, (int32_t)sizeof(fd), &fd); if (ret != HITLS_SUCCESS) { goto ERR; } BSL_UIO_SetInit(io, true); // must return success ret = HITLS_SetUio(sslObj, io); if (ret != HITLS_SUCCESS) { goto ERR; } linkObj->io = io; linkObj->ssl = sslObj; return linkObj; ERR: FRAME_IO_FreeUserData(ioUserdata); BSL_UIO_Free(io); HITLS_Free(sslObj); BSL_SAL_FREE(linkObj); return NULL; } #ifdef HITLS_TLS_PROTO_TLCP11 FRAME_LinkObj *FRAME_CreateTLCPLink(HITLS_Config *config, BSL_UIO_TransportType type, bool isClient) { #ifdef HITLS_TLS_CONFIG_KEY_USAGE HITLS_CFG_SetCheckKeyUsage(config, false); #endif #ifdef HITLS_TLS_FEATURE_SECURITY HITLS_CFG_SetSecurityLevel(config, HITLS_SECURITY_LEVEL_ZERO); #endif /* HITLS_TLS_FEATURE_SECURITY */ int32_t ret; if (isClient) { ret = HiTLS_X509_LoadCertAndKey(config, SM2_VERIFY_PATH, SM2_CHAIN_PATH, SM2_CLIENT_ENC_CERT_PATH, SM2_CLIENT_SIGN_CERT_PATH, SM2_CLIENT_ENC_KEY_PATH, SM2_CLIENT_SIGN_KEY_PATH); } else { ret = HiTLS_X509_LoadCertAndKey(config, SM2_VERIFY_PATH, SM2_CHAIN_PATH, SM2_SERVER_ENC_CERT_PATH, SM2_SERVER_SIGN_CERT_PATH, SM2_SERVER_ENC_KEY_PATH, SM2_SERVER_SIGN_KEY_PATH); } if (ret != HITLS_SUCCESS) { return NULL; } return CreateLink(config, type); } #endif /* HITLS_TLS_PROTO_TLCP11 */ //Set certificate and creating a connection FRAME_LinkObj *FRAME_CreateLinkBase(HITLS_Config *config, BSL_UIO_TransportType type, bool setCertFlag) { int32_t ret; if (setCertFlag) { char verifyPath[MAX_CERT_PATH_LENGTH] = {0}; char chainPath[MAX_CERT_PATH_LENGTH] = {0}; char certPath[MAX_CERT_PATH_LENGTH] = {0}; char keyPath[MAX_CERT_PATH_LENGTH] = {0}; sprintf_s(verifyPath, MAX_CERT_PATH_LENGTH, "%s:%s", ECDSA_SHA_CA_PATH, RSA_SHA_CA_PATH); sprintf_s(chainPath, MAX_CERT_PATH_LENGTH, "%s:%s", ECDSA_SHA_CHAIN_PATH, RSA_SHA_CHAIN_PATH); sprintf_s( certPath, MAX_CERT_PATH_LENGTH, "%s:%s", ECDSA_SHA256_EE_PATH, RSA_SHA256_EE_PATH3); sprintf_s(keyPath, MAX_CERT_PATH_LENGTH, "%s:%s", ECDSA_SHA256_PRIV_PATH, RSA_SHA256_PRIV_PATH3); ret = HiTLS_X509_LoadCertAndKey(config, verifyPath, chainPath, certPath, NULL, keyPath, NULL); if (ret != HITLS_SUCCESS) { return NULL; } } return CreateLink(config, type); } FRAME_LinkObj *FRAME_CreateLink(HITLS_Config *config, BSL_UIO_TransportType type) { #ifdef HITLS_TLS_CONFIG_KEY_USAGE HITLS_CFG_SetCheckKeyUsage(config, false); #endif /* HITLS_TLS_CONFIG_KEY_USAGE */ #ifdef HITLS_TLS_FEATURE_SECURITY HITLS_CFG_SetSecurityLevel(config, HITLS_SECURITY_LEVEL_ZERO); #endif /* HITLS_TLS_FEATURE_SECURITY */ return FRAME_CreateLinkBase(config, type, true); } FRAME_LinkObj *FRAME_CreateLinkEx(HITLS_Config *config, BSL_UIO_TransportType type) { #ifdef HITLS_TLS_CONFIG_KEY_USAGE HITLS_CFG_SetCheckKeyUsage(config, false); #endif /* HITLS_TLS_CONFIG_KEY_USAGE */ #ifdef HITLS_TLS_FEATURE_SECURITY HITLS_CFG_SetSecurityLevel(config, HITLS_SECURITY_LEVEL_ZERO); #endif /* HITLS_TLS_FEATURE_SECURITY */ return FRAME_CreateLinkBase(config, type, false); } FRAME_LinkObj *FRAME_CreateLinkWithCert(HITLS_Config *config, BSL_UIO_TransportType type, const FRAME_CertInfo* certInfo) { #ifdef HITLS_TLS_CONFIG_KEY_USAGE HITLS_CFG_SetCheckKeyUsage(config, false); #endif /* HITLS_TLS_CONFIG_KEY_USAGE */ #ifdef HITLS_TLS_FEATURE_SECURITY if (config->securityLevel == HITLS_SECURITY_LEVEL_ONE) { HITLS_CFG_SetSecurityLevel(config, HITLS_SECURITY_LEVEL_ZERO); } #endif /* HITLS_TLS_FEATURE_SECURITY */ int32_t ret; ret = HiTLS_X509_LoadCertAndKey(config, certInfo->caFile, certInfo->chainFile, certInfo->endEquipmentFile, certInfo->signFile, certInfo->privKeyFile, certInfo->signPrivKeyFile); if (ret != HITLS_SUCCESS) { return NULL; } return CreateLink(config, type); } void FRAME_FreeLink(FRAME_LinkObj *linkObj) { if (linkObj == NULL) { return; } FRAME_IO_FreeUserData(BSL_UIO_GetUserData(linkObj->io)); // BSL_UIO_Free is automatically invoked twice in HITLS_Free #ifdef HITLS_TLS_FEATURE_FLIGHT if (linkObj->io != NULL && linkObj->io->references.count >= 2) { while (linkObj->io->references.count > 2) { BSL_UIO_Free(linkObj->io); } } else { #endif BSL_UIO_Free(linkObj->io); #ifdef HITLS_TLS_FEATURE_FLIGHT } #endif HITLS_Free(linkObj->ssl); BSL_SAL_FREE(linkObj); return; } HITLS_Ctx *FRAME_GetTlsCtx(const FRAME_LinkObj *linkObj) { if (linkObj == NULL) { return NULL; } return linkObj->ssl; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/frame/src/frame_link.c
C
unknown
8,910
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef FRAME_LINK_H #define FRAME_LINK_H #include "hitls.h" #include "bsl_uio.h" #ifdef __cplusplus extern "C" { #endif struct FRAME_LinkObj_ { HITLS_Ctx *ssl; BSL_UIO *io; /* For CCS test, make TRY_RECV_FINISH stop before receiving CCS message */ bool needStopBeforeRecvCCS; }; struct FRAME_CertInfo_ { const char* caFile; const char* chainFile; const char* endEquipmentFile; const char* signFile; // used TLCP const char* privKeyFile; const char* signPrivKeyFile; // used TLCP }; #define INIT_IO_METHOD(method, tp, pfWrite, pfRead, pfCtrl) \ do { \ (method).uioType = tp; \ (method).uioRead = pfRead; \ (method).uioWrite = pfWrite; \ (method).uioCtrl = pfCtrl; \ } while (0) #ifdef __cplusplus } #endif #endif // FRAME_LINK_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/frame/src/frame_link.h
C
unknown
1,538
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "frame_msg.h" #include "hitls_error.h" #include "frame_tls.h" FRAME_Msg *FRAME_GenerateMsgFromBuffer(const FRAME_LinkObj *linkObj, const uint8_t *buffer, uint32_t len) { // Check whether the const Frame_LinkObj *linkObj parameter is required. If the parameter is not required, delete it (void)linkObj; (void)buffer; (void)len; return NULL; } /** * @ingroup Obtain a message from the I/O receiving buffer of the connection * * @return Return the CTX object of the TLS */ int32_t FRAME_GetLinkRecMsg(FRAME_LinkObj *link, uint8_t *buffer, uint32_t len, uint32_t *msgLen) { (void)link; (void)buffer; (void)len; (void)msgLen; return HITLS_SUCCESS; } /** * @ingroup Obtain a message from the I/O sending buffer of the connection * * @return Return the CTX object of the TLS */ int32_t FRAME_GetLinkSndMsg(FRAME_LinkObj *link, uint8_t *buffer, uint32_t len, uint32_t *msgLen) { (void)link; (void)buffer; (void)len; (void)msgLen; return HITLS_SUCCESS; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/frame/src/frame_msg.c
C
unknown
1,561
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef REC_WRAPPER_H #define REC_WRAPPER_H #include "rec.h" #ifdef __cplusplus extern "C" { #endif /** * @brief REC_read, REC_write read/write callback * * @param ctx [IN] TLS context * @param buf [IN/OUT] Read/write buffer * @param bufLen [IN/OUT] Reads and writes len bytes * @param bufSize [IN] Maximum buffer size * @param userData [IN/OUT] User-defined data */ typedef void (*WrapperFunc)(TLS_Ctx *ctx, uint8_t *buf, uint32_t *bufLen, uint32_t bufSize, void* userData); typedef struct { HITLS_HandshakeState ctrlState; REC_Type recordType; bool isRecRead; void *userData; WrapperFunc func; } RecWrapper; void RegisterWrapper(RecWrapper wrapper); void ClearWrapper(void); #ifdef __cplusplus } #endif #endif // REC_WRAPPER_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/func_wrapper/include/rec_wrapper.h
C
unknown
1,315
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "securec.h" #include "hitls_build.h" #include "rec_crypto.h" #include "hs_ctx.h" #include "stub_replace.h" #include "rec_wrapper.h" #define MAX_BUF 16384 static RecWrapper g_recWrapper; static bool g_enableWrapper; static __thread uint8_t g_locBuffer[MAX_BUF] = { 0 }; extern int32_t __real_REC_Read(TLS_Ctx *ctx, REC_Type recordType, uint8_t *data, uint32_t *readLen, uint32_t num); extern int32_t __real_REC_Write(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num); extern int32_t __wrap_REC_Read(TLS_Ctx *ctx, REC_Type recordType, uint8_t *data, uint32_t *readLen, uint32_t num) { return __real_REC_Read(ctx, recordType, data, readLen, num); } extern int32_t __wrap_REC_Write(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num) { // Length that can be manipulated in wrapper uint32_t manipulateLen = num; if (!g_enableWrapper || g_recWrapper.isRecRead || g_recWrapper.recordType != recordType) { return __real_REC_Write(ctx, recordType, data, manipulateLen); } if (g_recWrapper.recordType == REC_TYPE_HANDSHAKE && ctx->hsCtx->state != g_recWrapper.ctrlState) { return __real_REC_Write(ctx, recordType, data, manipulateLen); } (void)memcpy_s(g_locBuffer, MAX_BUF, data, num); // The value of manipulateLen can be greater than or smaller than num g_recWrapper.func(ctx, g_locBuffer, &manipulateLen, MAX_BUF, g_recWrapper.userData); if (ctx->hsCtx->bufferLen < manipulateLen) { uint8_t *tmp = BSL_SAL_Realloc(ctx->hsCtx->msgBuf, manipulateLen, ctx->hsCtx->bufferLen); if (tmp == NULL) { return HITLS_MEMALLOC_FAIL; } ctx->hsCtx->bufferLen = manipulateLen; ctx->hsCtx->msgBuf = tmp; } if (recordType == REC_TYPE_HANDSHAKE) { (void)memcpy_s(ctx->hsCtx->msgBuf, ctx->hsCtx->bufferLen, g_locBuffer, manipulateLen); ctx->hsCtx->msgLen = manipulateLen; } int32_t ret = __real_REC_Write(ctx, recordType, g_locBuffer, manipulateLen); if (recordType == REC_TYPE_HANDSHAKE && ret == HITLS_SUCCESS) { ctx->hsCtx->msgOffset = manipulateLen - num; } return ret; } RecCryptoFunc g_aeadFuncs; RecCryptoFunc g_cbcFuncs; RecCryptoFunc g_plainFuncs; void FRAME_InitRecCrypto(void) { g_plainFuncs = *RecGetCryptoFuncs(NULL); RecConnSuitInfo info = {0}; info.cipherType = HITLS_AEAD_CIPHER; g_aeadFuncs = *RecGetCryptoFuncs(&info); info.cipherType = HITLS_CBC_CIPHER; g_cbcFuncs = *RecGetCryptoFuncs(&info); } static RecCryptoFunc *RecGetOriginCryptFuncs(RecConnSuitInfo *suiteInfo) { if (suiteInfo == NULL) { return &g_plainFuncs; } switch (suiteInfo->cipherType) { case HITLS_AEAD_CIPHER: return &g_aeadFuncs; case HITLS_CBC_CIPHER: return &g_cbcFuncs; default: return &g_plainFuncs; } return &g_plainFuncs; } static int32_t WrapperDecryptFunc(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen) { int32_t ret = RecGetOriginCryptFuncs(state->suiteInfo)->decrypt(ctx, state, cryptMsg, data, dataLen); if (ret == HITLS_SUCCESS && IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask) && g_recWrapper.isRecRead) { if (g_recWrapper.recordType != cryptMsg->type) { return ret; } if (g_recWrapper.recordType == REC_TYPE_HANDSHAKE) { if (ctx->hsCtx == NULL || ctx->hsCtx->state != g_recWrapper.ctrlState) { return ret; } } g_recWrapper.func(ctx, data, dataLen, *dataLen, g_recWrapper.userData); } return ret; } static int32_t WrapperDecryptPostProcess(TLS_Ctx *ctx, RecConnSuitInfo *suitInfo, REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen) { int32_t ret = RecGetOriginCryptFuncs(suitInfo)->decryptPostProcess(ctx, suitInfo, cryptMsg, data, dataLen); if (ret == HITLS_SUCCESS && g_recWrapper.isRecRead) { if (g_recWrapper.recordType != cryptMsg->type) { return ret; } if (g_recWrapper.recordType == REC_TYPE_HANDSHAKE) { if (ctx->hsCtx == NULL || ctx->hsCtx->state != g_recWrapper.ctrlState) { return ret; } } g_recWrapper.func(ctx, data, dataLen, *dataLen, g_recWrapper.userData); } return ret; } static int32_t WrapperCalPlantextBufLenFunc(TLS_Ctx *ctx, RecConnSuitInfo *suitInfo, uint32_t ciphertextLen, uint32_t *offset, uint32_t *plainLen) { (void)ctx; (void)suitInfo; (void)ciphertextLen; (void)offset; *plainLen = 16384 + 2048; return HITLS_SUCCESS; } static RecCryptoFunc *Stub_RecCrypto(RecConnSuitInfo *suiteInfo) { static RecCryptoFunc recCryptoFunc = { 0 }; recCryptoFunc = *RecGetOriginCryptFuncs(suiteInfo); recCryptoFunc.calPlantextBufLen = WrapperCalPlantextBufLenFunc; recCryptoFunc.decrypt = WrapperDecryptFunc; recCryptoFunc.decryptPostProcess = WrapperDecryptPostProcess; return &recCryptoFunc; } FuncStubInfo g_stubRecFuncs; void RegisterWrapper(RecWrapper wrapper) { if (g_enableWrapper) { ClearWrapper(); } FRAME_InitRecCrypto(); STUB_Init(); STUB_Replace(&g_stubRecFuncs, (void *)RecGetCryptoFuncs, (void *)Stub_RecCrypto); g_enableWrapper = true; g_recWrapper = wrapper; } void ClearWrapper(void) { STUB_Reset(&g_stubRecFuncs); g_enableWrapper = false; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/func_wrapper/src/rec_wrapper.c
C
unknown
6,020
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef FRAME_MSG_H #define FRAME_MSG_H #include <stdint.h> #include "hs_msg.h" #include "rec.h" #ifdef __cplusplus extern "C" { #endif /* Used to determine the field status during packing */ typedef enum { /* field is missing. If this state is set, the field will not be packed into the buffer during packing */ MISSING_FIELD = 0, /* field initial status. The field status in the parsed msg structure is filled with the value. */ INITIAL_FIELD, /* Specifies the value of the field. If the field content is modified, set the status to the value. */ ASSIGNED_FIELD, /* Repeat the field. During the packing, the field will be packed again */ DUPLICATE_FIELD, /* Only one byte length is packed and used to construct abnormal messages. It is used for two or more bytes of fields (such as the cipher suite length). */ SET_LEN_TO_ONE_BYTE, } FieldState; // uint64_t data with status typedef struct { FieldState state; /* Field state */ uint64_t data; /* Content */ } FRAME_Integer; // uint8_t data with status typedef struct { FieldState state; /* Field state */ uint32_t size; /* Number of data records */ uint8_t *data; /* Content */ } FRAME_Array8; // uint16_t data with status typedef struct { FieldState state; /* Field state */ uint32_t size; /* Number of data records */ uint16_t *data; /* Content */ } FRAME_Array16; typedef struct { FieldState exState; /* extension Field state */ FRAME_Integer exType; /* extension type */ FRAME_Integer exLen; /* Full length of extension */ FRAME_Integer exDataLen; /* Length of extension content */ FRAME_Array8 exData; /* extension content */ } FRAME_HsExtArray8; // The handshake extension with state carries a variable-length array with uint16_t // such as the signature algorithm extension typedef struct { FieldState exState; /* extension Field state */ FRAME_Integer exType; /* extension type */ FRAME_Integer exLen; /* Full length of extension */ FRAME_Integer exDataLen; /* Length of extension content */ FRAME_Array16 exData; /* extension content */ } FRAME_HsExtArray16; typedef struct { FieldState state; /* Field state */ FRAME_Integer group; /* group */ FRAME_Integer keyExchangeLen; /* key exchange size */ FRAME_Array8 keyExchange; } FRAME_HsKeyShareEntry; typedef struct { FieldState state; /* Field state */ uint32_t size; /* Number of entries */ FRAME_HsKeyShareEntry *data; /* key shareContent */ } FRAME_HsArrayKeyShare; typedef struct { FieldState exState; /* extension Field state */ FRAME_Integer exType; /* extension type */ FRAME_Integer exLen; /* Full length of extension */ FRAME_Integer exKeyShareLen; /* keyshare Array length */ FRAME_HsArrayKeyShare exKeyShares; /* keyshare array content */ } FRAME_HsExtKeyShare; typedef struct { FieldState state; /* Field state */ FRAME_Integer identityLen; FRAME_Array8 identity; FRAME_Integer obfuscatedTicketAge; } FRAME_HsPskIdentity; typedef struct { FieldState state; /* Field state */ uint32_t size; /* Number of identities */ FRAME_HsPskIdentity *data; /* identity Content */ } FRAME_HsArrayPskIdentity; typedef struct { FieldState state; /* Field state */ FRAME_Integer binderLen; FRAME_Array8 binder; } FRAME_HsPskBinder; typedef struct { FieldState state; /* Field state */ uint32_t size; /* Number of identities */ FRAME_HsPskBinder *data; /* identity Content */ } FRAME_HsArrayPskBinder; typedef struct { FieldState exState; /* extension Field state */ FRAME_Integer exType; /* extension type */ FRAME_Integer exLen; /* Full length of extension */ FRAME_Integer identitySize; FRAME_HsArrayPskIdentity identities; FRAME_Integer binderSize; FRAME_HsArrayPskBinder binders; } FRAME_HsExtOfferedPsks; typedef struct { FieldState exState; /* extension Field state */ FRAME_Integer exType; /* extension type */ FRAME_Integer exLen; /* Full length of extension */ FRAME_Array8 list; /* CA list */ FRAME_Integer listSize; /* CA list length */ } FRAME_HsExtCaList; typedef struct { FRAME_Integer version; /* Version number */ FRAME_Array8 randomValue; /* Random number */ FRAME_Integer sessionIdSize; /* session ID length */ FRAME_Array8 sessionId; /* session ID */ FRAME_Integer cookiedLen; /* Cookie length (for DTLS) */ FRAME_Array8 cookie; /* cookie(for DTLS) */ FRAME_Integer cipherSuitesSize; /* cipher suite length */ FRAME_Array16 cipherSuites; /* cipher suite */ FRAME_Integer compressionMethodsLen; /* compression method length */ FRAME_Array8 compressionMethods; /* compression method */ FieldState extensionState; /* Indicates whether the extension is packed */ FRAME_Integer extensionLen; /* Total length of the extension */ FRAME_HsExtArray8 pointFormats; FRAME_HsExtArray16 supportedGroups; FRAME_HsExtArray16 signatureAlgorithms; FRAME_HsExtArray8 encryptThenMac; FRAME_HsExtArray8 extendedMasterSecret; FRAME_HsExtArray8 secRenego; /* security renegotiation */ FRAME_HsExtArray8 sessionTicket; FRAME_HsExtArray8 serverName; /* sni */ FRAME_HsExtArray8 alpn; /* alpn */ FRAME_HsExtArray8 tls13Cookie; /* tls1.3 cookie */ FRAME_HsExtKeyShare keyshares; /* tls1.3 key share */ FRAME_HsExtArray8 pskModes; /* tls1.3 psk exchange mode */ FRAME_HsExtArray16 supportedVersion; /* tls1.3 support version */ FRAME_HsExtOfferedPsks psks; /* tls1.3 psk */ FRAME_HsExtCaList caList; } FRAME_ClientHelloMsg; typedef struct { FieldState exState; /* extension Field state */ FRAME_Integer exType; /* extension type */ FRAME_Integer exLen; /* Full length of extension */ FRAME_Integer data; /* extension content */ } FRAME_HsExtUint16; typedef struct { FieldState exState; /* extension Field state */ FRAME_Integer exType; /* extension type */ FRAME_Integer exLen; /* Full length of extension */ FRAME_HsKeyShareEntry data; /* extension content */ } FRAME_HsExtServerKeyShare; typedef struct { FRAME_Integer version; /* Version number */ FRAME_Array8 randomValue; /* Random number */ FRAME_Integer sessionIdSize; /* session ID length */ FRAME_Array8 sessionId; /* session ID */ FRAME_Integer cipherSuite; FRAME_Integer compressionMethod; FRAME_Integer extensionLen; /* Full length of the extended field */ FRAME_HsExtArray8 pointFormats; FRAME_HsExtArray8 extendedMasterSecret; FRAME_HsExtArray8 secRenego; /* security renegotiation */ FRAME_HsExtArray8 sessionTicket; /* sessionTicket */ FRAME_HsExtArray8 serverName; /* sni */ FRAME_HsExtArray8 alpn; /* alpn */ FRAME_HsExtUint16 supportedVersion; /* tls1.3 supported version */ FRAME_HsExtServerKeyShare keyShare; /* tls1.3 key share */ FRAME_HsExtUint16 pskSelectedIdentity; /* tls1.3 psk extension */ FRAME_HsExtArray8 tls13Cookie; /* tls1.3 cookie */ FRAME_HsExtArray8 encryptThenMac; } FRAME_ServerHelloMsg; typedef struct { FRAME_Array8 extra; /* server hello done is a null message. This field is used to construct abnormal messages */ } FRAME_ServerHelloDoneMsg; typedef struct FrameCertItem_ { FieldState state; /* Certificate Field state */ FRAME_Integer certLen; /* Certificate length */ FRAME_Array8 cert; /* Certificate Content */ FRAME_Integer extensionLen; /* Certificate extension length. only for tls1.3 */ FRAME_Array8 extension; /* Certificate extension Content. only for tls1.3 */ struct FrameCertItem_ *next; } FrameCertItem; typedef struct { FRAME_Integer certsLen; /* Certificate total length */ FrameCertItem *certItem; /* Certificate */ FRAME_Array8 certificateReqCtx; /* For TLS 1.3 */ FRAME_Integer certificateReqCtxSize; /* For TLS 1.3 */ } FRAME_CertificateMsg; typedef struct { FRAME_Integer curveType; /* Curve type */ FRAME_Integer namedcurve; /* Named curve */ FRAME_Integer pubKeySize; /* ecdh public key size */ FRAME_Array8 pubKey; /* ecdh public key content */ FRAME_Integer signAlgorithm; /* Signature hash algorithm, for TLS1.2 and DTLS1.2 */ FRAME_Integer signSize; /* Signature length */ FRAME_Array8 signData; /* Signature Content */ } FRAME_ServerEcdh; typedef struct { FRAME_Integer plen; FRAME_Array8 p; FRAME_Integer glen; FRAME_Array8 g; FRAME_Integer pubKeyLen; /* dh public key */ FRAME_Array8 pubKey; /* dH public key content */ FRAME_Integer signAlgorithm; /* Signature hash algorithm, for TLS1.2 and DTLS1.2 */ FRAME_Integer signSize; /* Signature length */ FRAME_Array8 signData; /* Signature content */ } FRAME_ServerDh; typedef struct { union { FRAME_ServerEcdh ecdh; FRAME_ServerDh dh; } keyEx; } FRAME_ServerKeyExchangeMsg; typedef struct { FRAME_Integer pubKeySize; /* Key exchange data length */ FRAME_Array8 pubKey; /* Key exchange data */ } FRAME_ClientKeyExchangeMsg; typedef struct { FieldState state; /* Field state */ FRAME_Integer certTypesSize; /* certificate type length */ FRAME_Array8 certTypes; /* Certificate type list */ FRAME_Integer signatureAlgorithmsSize; /* signature algorithm length */ FRAME_Array16 signatureAlgorithms; /* signature algorithm list */ FRAME_Integer reserved; /* Four-byte alignment */ FRAME_Integer distinguishedNamesSize; /* DN length */ FRAME_Array8 distinguishedNames; /* DN */ FRAME_Array8 certificateReqCtx; /* For TLS 1.3 */ FRAME_Integer certificateReqCtxSize; /* For TLS 1.3 */ FRAME_Integer exMsgLen; } FRAME_CertificateRequestMsg; /* Used to transmit certificate verification packets. */ typedef struct { FRAME_Integer signHashAlg; /* Signature hash algorithm, used for TLS1.2 and DTLS1.2 */ FRAME_Integer signSize; /* Length of the signature data */ FRAME_Array8 sign; /* Signature data */ } FRAME_CertificateVerifyMsg; typedef struct { FRAME_Integer ticketLifetime; FRAME_Integer ticketAgeAdd; FRAME_Integer ticketNonceSize; FRAME_Array8 ticketNonce; FRAME_Integer ticketSize; FRAME_Array8 ticket; FRAME_Integer extensionLen; /* Total length of the extension */ } FRAME_NewSessionTicketMsg; /* Transmit the Finish message */ typedef struct { FRAME_Array8 verifyData; /* verify data Content */ } FRAME_FinishedMsg; typedef struct { FRAME_Integer type; /* Handshake type */ FRAME_Integer length; /* Length of the handshake message */ /* Sequence number of DTLS handshake messages. Increases by 1 each time a new handshake message is sent. *Does not increase for retransmission */ FRAME_Integer sequence; FRAME_Integer fragmentOffset; /* Fragment offset of DTLS handshake message */ FRAME_Integer fragmentLength; /* DTLS Handshake message Fragment Length */ union { FRAME_ClientHelloMsg clientHello; FRAME_ServerHelloMsg serverHello; FRAME_CertificateMsg certificate; FRAME_ServerKeyExchangeMsg serverKeyExchange; FRAME_CertificateRequestMsg certificateReq; FRAME_ServerHelloDoneMsg serverHelloDone; FRAME_ClientKeyExchangeMsg clientKeyExchange; FRAME_CertificateVerifyMsg certificateVerify; FRAME_NewSessionTicketMsg newSessionTicket; FRAME_FinishedMsg finished; } body; } FRAME_HsMsg; typedef struct { uint8_t level; /* To be deleted. The member is not processed because some code uses it */ uint8_t description; /* To be deleted. The member is not processed because some code uses it */ FRAME_Integer alertLevel; /* Alert level: See ALERT_Level */ FRAME_Integer alertDescription; /* Alert description: See ALERT_Description */ FRAME_Array8 extra; /* This field is used to construct abnormal messages */ } FRAME_AlertMsg; typedef struct { uint8_t type; /* To be deleted. The member is not processed because some code uses it */ FRAME_Integer ccsType; /* ccs type */ FRAME_Array8 extra; /* This field is used to construct abnormal messages */ } FRAME_CcsMsg; typedef struct { char *buffer; /* To be deleted. The member is not processed because some code uses it */ uint32_t len; /* To be deleted. The member is not processed because some code uses it */ FRAME_Array8 appData; /* app data */ } FRAME_AppMsg; typedef struct { uint8_t type; /* To be deleted. The member is not processed because some code uses it */ uint8_t reverse; /* To be deleted. The member is not processed because some code uses it */ uint16_t version; /* To be deleted. The member is not processed because some code uses it */ uint16_t bodyLen; /* To be deleted. The member is not processed because some code uses it */ BSL_UIO_TransportType transportType; uint64_t epochSeq; /* To be deleted. The member is not processed because some code uses it */ FRAME_Integer recType; /* record the message type */ FRAME_Integer recVersion; /* record version */ FRAME_Integer epoch; /* Counter value that increases each time the password status changes. This counter is used by DTLS */ FRAME_Integer sequence; /* Record message sequence number, for DTLS */ FRAME_Integer length; /* Length of the record message */ union { HS_Msg handshakeMsg; /* To be deleted. The member is not processed because some code uses it */ FRAME_HsMsg hsMsg; FRAME_AlertMsg alertMsg; FRAME_CcsMsg ccsMsg; FRAME_AppMsg appMsg; } body; uint8_t *buffer; /* To be deleted. The member is not processed because some code uses it */ uint32_t len; /* To be deleted. The member is not processed because some code uses it */ } FRAME_Msg; /* Used to transfer the message type. The framework packs and parses the corresponding message based on the field value * of this structure */ typedef struct { uint16_t versionType; /* To ensure that the memory can be released normally, a value is assigned to the member during parsing */ REC_Type recordType; /* To ensure that the memory can be released normally, a value is assigned to the member during parsing */ HS_MsgType handshakeType; HITLS_KeyExchAlgo keyExType; BSL_UIO_TransportType transportType; } FRAME_Type; /** * @brief Generate a TLS record byte stream based on the specified parameter of frameType * and the field content of the msg structure and save the stream to the buffer * @param frameType [IN] Specified packing parameters * @param msg [IN] Message structure * @param buf [OUT] Returned handshake message * @param bufLen [IN] Input buffer size * @param usedLen [OUT] Returned message length * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t FRAME_PackMsg(FRAME_Type *frameType, const FRAME_Msg *msg, uint8_t *buffer, uint32_t bufLen, uint32_t *usedLen); /** * @brief Generate tls13 handshake message according to type * @param type [IN] Specified packing parameters * @param buf [OUT] Returned handshake message * @param bufLen [IN] Input buffer size * @param usedLen [OUT] Returned message length * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t FRAME_GetTls13DisorderHsMsg(HS_MsgType type, uint8_t *buffer, uint32_t bufLen, uint32_t *usedLen); /** * @brief Generate a TLS record body byte stream based on the specified parameter of frameType * and the field content of the msg structure and save the byte stream to the buffer. * * @param frameType [IN] Specified packing parameters * @param msg [IN] Message structure * @param buffer [OUT] Returned handshake message * @param bufLen [IN] Input buffer size * @param usedLen [OUT] Returned message length * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t FRAME_PackRecordBody(FRAME_Type *frameType, const FRAME_Msg *msg, uint8_t *buffer, uint32_t bufLen, uint32_t *usedLen); /** * @brief Parse the MSG structure based on the specified parameter of frameType and the TLS record byte stream. * Only the record message header is parsed * * @param frameType [IN] Specified parsing parameter, mainly versionType * @param buffer [IN] TLS record byte stream * @param bufLen [IN] Input buffer size * @param msg [OUT] Parsed Message structure * @param parseLen [OUT] Length of the parsed message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t FRAME_ParseMsgHeader(FRAME_Type *frameType, const uint8_t *buffer, uint32_t bufLen, FRAME_Msg *msg, uint32_t *parseLen); /** * @brief parse TLS record header * * @param buffer [IN] TLS record byte stream * @param bufferLen [IN] Input buffer size * @param msg [OUT] Parsed Message structure * @param headerLen [OUT] Length of the parsed message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t FRAME_ParseTLSRecordHeader(const uint8_t *buffer, uint32_t bufferLen, FRAME_Msg *msg, uint32_t *parseLen); /** * @brief Parse the body of the TLS non-handshake record * * @param buffer [IN] TLS record byte stream * @param bufferLen [IN] Input buffer size * @param msg [OUT] Parsed Message structure * @param headerLen [OUT] Length of the parsed message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t FRAME_ParseTLSNonHsRecordBody(const uint8_t *buffer, uint32_t bufferLen, FRAME_Msg *msg, uint32_t *parseLen); /** * @brief Parse the TLS non-handshake record * * @param buffer [IN] TLS record byte stream * @param bufferLen [IN] Input buffer size * @param msg [OUT] Parsed Message structure * @param headerLen [OUT] Length of the parsed message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t FRAME_ParseTLSNonHsRecord(const uint8_t *buffer, uint32_t bufferLen, FRAME_Msg *msg, uint32_t *parseLen); /** * @brief Parse the record of the handshake type * * @param buffer [IN] TLS record byte stream * @param bufferLen [IN] Input buffer size * @param msg [OUT] Parsed Message structure * @param headerLen [OUT] Length of the parsed message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t FRAME_ParseHsRecord(FRAME_Type *frameType, const uint8_t *buffer, uint32_t bufferLen, FRAME_Msg *msg, uint32_t *parseLen); /** * @brief Parse the MSG structure based on the specified parameter of frameType and the TLS record byte stream. * Only the record message body is parsed * * @attention Invoke the Frame_ParseMsgHeader interface to parse the message header * * @param frameType [IN] Specified parsing parameters, mainly versionType and keyExType * @param buffer [IN] TLS record byte stream * @param bufLen [IN] Input buffer size * @param msg [OUT] Parsed Message structure * @param parseLen [OUT] Length of the parsed message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t FRAME_ParseMsgBody(FRAME_Type *frameType, const uint8_t *buffer, uint32_t bufLen, FRAME_Msg *msg, uint32_t *parseLen); /** * @brief Parse the message into the msg structure based on the specified parameter of frameType and * the TLS record byte stream * * @param frameType [IN] Specified parsing parameters, mainly versionType and keyExType * @param buffer [IN] TLS record byte stream * @param bufLen [IN] Input buffer size * @param msg [OUT] Parsed Message structure * @param parseLen [OUT] Length of the parsed message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t FRAME_ParseMsg(FRAME_Type *frameType, const uint8_t *buffer, uint32_t bufLen, FRAME_Msg *msg, uint32_t *parseLen); /** * @brief Clear the memory allocated during parsing * * @param frameType [IN] Specified parsing parameters, mainly versionType and keyExType * @param msg [IN] Message structure */ void FRAME_CleanMsg(FRAME_Type *frameType, FRAME_Msg *msg); /** * @brief Clear the memory allocated during parsing * * @param recType [IN] Specified record type * @param msg [IN] Message structure */ void FRAME_CleanNonHsRecord(REC_Type recType, FRAME_Msg *msg); /** * @brief Obtain a structure of a specified message type * * @attention This interface does not set the callback function. User need to set the callback interface first * This interface obtains only the HANDSHAKE,Change_CIPHER_SPEC, and ALERT messages * The existing framework does not support parsing of encrypted finished messages. * Therefore, the finished messages cannot be obtained. * * @param frameType [IN] Specified message parameters * @param msg [OUT] Returned Message structure * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t FRAME_GetDefaultMsg(FRAME_Type *frameType, FRAME_Msg *msg); /** * @brief Modify a message field * This method is used to modify the contents of integer fields in a message, such as the message type, * version number, and field length * * @param data [IN] Data content * @param frameInteger [IN/OUT] IN original field; OUT New field * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t FRAME_ModifyMsgInteger(const uint64_t data, FRAME_Integer *frameInteger); /** * @brief Modify the message field content. User can increase or decrease the length of the message field and modify * the field content. * (This implementation performs deep copy of the data content.) * This method is used to modify the content of the uint8_t array field in a message, such as the session ID, * cookie, and signature data * * @param data [IN] Data content * @param dataLen [IN] Number of data records * @param frameArray [IN/OUT] IN original field; OUT New field * @param frameArrayLen [IN/OUT] IN Original field length; Length of the new field in the OUT field. This parameter * can be none * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t FRAME_ModifyMsgArray8(const uint8_t *data, uint32_t dataLen, FRAME_Array8 *frameArray, FRAME_Integer *frameArrayLen); /** * @brief Retain the original handshake message field content and add a string of data data to the end of the data. * (This implementation performs deep copy of the data content.) * This method is used to modify the content of the uint8_t array field in a message, such as the session ID, * cookie, and signature data. * * @param data [IN] Data content * @param dataLen [IN] Number of data records * @param frameArray [IN/OUT] IN original field; OUT New field * @param frameArrayLen [IN/OUT] IN Original field length; Length of the new field in the OUT field. This parameter * can be none * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t FRAME_AppendMsgArray8(const uint8_t *data, uint32_t dataLen, FRAME_Array8 *frameArray, FRAME_Integer *frameArrayLen); /** * @brief Modify the message field content. User can increase or decrease the length of the message field and modify * the field content. * (This implementation performs deep copy of the data content.) * This method is used to modify the uint16_t array field in a message, for example, cipher suite and support * group extension * * @param data [IN] Data content * @param dataLen [IN] Number of data records * @param frameArray [IN/OUT] IN original field; OUT New field * @param frameArrayLen [IN/OUT] IN Original field length; Length of the new field in the OUT field. This parameter * can be none * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t FRAME_ModifyMsgArray16(const uint16_t *data, uint32_t dataLen, FRAME_Array16 *frameArray, FRAME_Integer *frameArrayLen); /** * @brief Retain the original handshake message field content and add a string of data data to the end of the data. * (This implementation performs deep copy of the data content.) * This method is used to modify the uint16_t array field in a message, for example, the cipher suite and * support group extension * * @param data [IN] Data content * @param dataLen [IN] Number of data records * @param frameArray [IN/OUT] IN original field; OUT New field * @param frameArrayLen [IN/OUT] IN Original field length; Length of the new field in the OUT field. This parameter * can be none * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t FRAME_AppendMsgArray16(const uint16_t *data, uint32_t dataLen, FRAME_Array16 *frameArray, FRAME_Integer *frameArrayLen); #ifdef __cplusplus } #endif #endif // FRAME_MSG_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/include/frame_msg.h
C
unknown
26,690
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef FRAME_TLS_H #define FRAME_TLS_H #include "bsl_uio.h" #include "hs_ctx.h" #include "frame_msg.h" #ifdef __cplusplus extern "C" { #endif typedef struct FRAME_LinkObj_ FRAME_LinkObj; typedef struct FRAME_CertInfo_ FRAME_CertInfo; typedef struct SSL_LINK_OBJ_ SSL_LINK_OBJ; HITLS_Ctx *FRAME_CreateDefaultDtlsObj(void); /** * @brief Load the certificate to the connection configuration context resource. * * @return If the value 0 is returned, the certificate is loaded successfully. * Otherwise, the certificate fails to be loaded */ int32_t FRAME_LoadCertToConfig(HITLS_Config *config, const char *verifyCert, const char *chainCert, const char *eeCert, const char *prvKey); /** * @brief Create a TLCP connection. This interface loads the certificate, applies for SSL CTX, and creates the underlying UIO * * @return Return the connection object, which can be used by the test framework to perform operations */ FRAME_LinkObj *FRAME_CreateTLCPLink(HITLS_Config *config, BSL_UIO_TransportType type, bool isClient); /** * @brief Create an SSL connection. This interface will complete the SSL CTX application, bottom-layer UIO creation, and load the default certificate * * @return Return the connection object, which can be used by the test framework to perform operations */ FRAME_LinkObj *FRAME_CreateLink(HITLS_Config *config, BSL_UIO_TransportType type); // This interface is used to create an SSL connection. // The SSL CTX application and bottom-layer UIO creation are completed. The default certificate is not loaded. FRAME_LinkObj *FRAME_CreateLinkEx(HITLS_Config *config, BSL_UIO_TransportType type); FRAME_LinkObj *FRAME_CreateLinkWithCert( HITLS_Config *config, BSL_UIO_TransportType type, const FRAME_CertInfo *certInfo); /** * @brief Create an SSL connection with configurable certificate loading. * This interface will complete the SSL CTX application and bottom-layer UIO creation. * The setCertFlag parameter controls whether to load the default certificate. * * @param config [IN] TLS configuration * @param type [IN] Transport type * @param setCertFlag [IN] Whether to load default certificate * * @return Return the connection object, which can be used by the test framework to perform operations */ FRAME_LinkObj *FRAME_CreateLinkBase(HITLS_Config *config, BSL_UIO_TransportType type, bool setCertFlag); /** * @brief Releases an SSL connection, which corresponds to Frame_CreateLink * * @return */ void FRAME_FreeLink(FRAME_LinkObj *linkObj); /** * @brief Obtain the TLS ctx from the Frame_LinkObj to facilitate the test of HiTLS APIs because HiTLS APIs use * HITLS_Ctx as the input parameter. * Do not call HiTLS_Free to release the return values of this API. * The values will be released in the Frame_FreeLink. * * @return Return the CTX object of the TLS */ HITLS_Ctx *FRAME_GetTlsCtx(const FRAME_LinkObj *linkObj); /* * @brief Simulate link establishment or simulate an SSL link in a certain state. * For example, if state is TRY_RECV_SERVER_HELLO, the client is ready to receive the SERVER Hello message, * and The server link is just sent SERVER_HELLO. * * @return If the operation is successful, HITLS_SUCCESS is returned. */ int32_t FRAME_CreateConnection(FRAME_LinkObj *client, FRAME_LinkObj *server, bool isClient, HITLS_HandshakeState state); /** * @brief Simulate renegotiation * @attention Internally invokes HITLS_Write and HITLS_Read to perform renegotiation. * Ensure that linkA is the initiator of the renegotiation request and * linkB is the receiver of the renegotiation request * * @param server [IN] Initiator of the renegotiation request * @param client [IN] Recipient of the renegotiation request * * @return If the operation is successful, HITLS_SUCCESS is returned */ int32_t FRAME_CreateRenegotiationServer(FRAME_LinkObj *server, FRAME_LinkObj *client); /* * @ingroup Simulate connection establishment or an SSL connection in a certain state. * For example, if the value of state is TRY_RECV_SERVER_HELLO, * the client is ready to receive the SERVER Hello message, * and the server connection is SERVER_HELLO has just been sent. * * * @return If the operation is successful, HITLS_SUCCESS is returned */ int32_t FRAME_CreateRenegotiationState(FRAME_LinkObj *client, FRAME_LinkObj *server, bool isClient, HITLS_HandshakeState state); /** * @brief Simulate renegotiation * @attention Internally invokes HITLS_Write and HITLS_Read to perform renegotiation. * Ensure that linkA is the initiator of the renegotiation request and * linkB is the receiver of the renegotiation request * * @param linkA [IN] Initiator of the renegotiation request * @param linkB [IN] Recipient of the renegotiation request * * @return If the operation is successful, HITLS_SUCCESS is returned */ int32_t FRAME_CreateRenegotiation(FRAME_LinkObj *linkA, FRAME_LinkObj *linkB); /** * @brief Obtain a message from the I/O receiving buffer of the connection * * @return If the operation is successful, HITLS_SUCCESS is returned */ int32_t FRAME_GetLinkRecMsg(FRAME_LinkObj *link, uint8_t *buffer, uint32_t len, uint32_t *msgLen); /** * @brief Obtain a message from the I/O sending buffer of the connection. * * @return If the operation is successful, HITLS_SUCCESS is returned. */ int32_t FRAME_GetLinkSndMsg(FRAME_LinkObj *link, uint8_t *buffer, uint32_t len, uint32_t *msgLen); /** * @brief Generate a framework message based on the content in the message buffer * * @return Return the Constructed Frame_Msg object */ FRAME_Msg *FRAME_GenerateMsgFromBuffer(const FRAME_LinkObj *linkObj, const uint8_t *buffer, uint32_t len); /** * @brief Send data from connection A to connection B * * @return If the operation is successful, HITLS_SUCCESS is returned */ int32_t FRAME_TrasferMsgBetweenLink(FRAME_LinkObj *linkA, FRAME_LinkObj *linkB); /** * @brief Initialize the framework */ void FRAME_Init(void); /** * @brief Deinitialize the framework */ void FRAME_DeInit(void); #ifdef __cplusplus } #endif #endif // FRAME_TLS_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/include/frame_tls.h
C
unknown
6,723
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HLT_H #define HLT_H #include <stddef.h> #include "hlt_type.h" #ifdef __cplusplus extern "C" { #endif void HLT_ConfigTimeOut(const char* timeout); void HLT_UnsetTimeOut(); // Create a process HLT_Process* InitSrcProcess(TLS_TYPE tlsType, char* srcDomainPath); HLT_Process* InitPeerProcess(TLS_TYPE tlsType, HILT_TransportType connType, int port, bool isBlock); #define HLT_InitLocalProcess(tlsType) InitSrcProcess(tlsType, __FILE__) #define HLT_CreateRemoteProcess(tlsType) InitPeerProcess(tlsType, NONE_TYPE, 0, 0) #define HLT_LinkRemoteProcess(tlsType, connType, port, isBlock) InitPeerProcess(tlsType, connType, port, isBlock) // Clear all process resources void HLT_FreeAllProcess(void); int HLT_FreeResFormSsl(const void *ssl); // Create a local data connection HLT_FD HLT_CreateDataChannel(HLT_Process* process1, HLT_Process* process2, DataChannelParam channelParam); int HLT_DataChannelConnect(DataChannelParam* dstChannelParam); pthread_t HLT_DataChannelAccept(DataChannelParam* channelParam); void HLT_CloseFd(int fd, int linkType); // Interface for setting connection information int HLT_SetVersion(HLT_Ctx_Config* ctxConfig, uint16_t minVersion, uint16_t maxVersion); int HLT_SetSecurityLevel(HLT_Ctx_Config *ctxConfig, int32_t level); int HLT_SetRenegotiationSupport(HLT_Ctx_Config* ctxConfig, bool support); int HLT_SetLegacyRenegotiateSupport(HLT_Ctx_Config* ctxConfig, bool support); int HLT_SetClientRenegotiateSupport(HLT_Ctx_Config* ctxConfig, bool support); int HLT_SetEmptyRecordsNum(HLT_Ctx_Config *ctxConfig, uint32_t emptyNum); int HLT_SetFlightTransmitSwitch(HLT_Ctx_Config *ctxConfig, bool support); int HLT_SetKeyLogCb(HLT_Ctx_Config *ctxConfig, char *SetKeyLogCb); int HLT_SetClientVerifySupport(HLT_Ctx_Config* ctxConfig, bool support); int HLT_SetNoClientCertSupport(HLT_Ctx_Config* ctxConfig, bool support); int HLT_SetPostHandshakeAuth(HLT_Ctx_Config *ctxConfig, bool support); int HLT_SetExtenedMasterSecretSupport(HLT_Ctx_Config* ctxConfig, bool support); int HLT_SetEncryptThenMac(HLT_Ctx_Config *ctxConfig, int support); int HLT_SetMiddleBoxCompat(HLT_Ctx_Config *ctxConfig, int support); int HLT_SetModeSupport(HLT_Ctx_Config *ctxConfig, uint32_t mode); int HLT_SetCipherSuites(HLT_Ctx_Config* ctxConfig, const char* cipherSuites); int HLT_SetProviderPath(HLT_Ctx_Config *ctxConfig, char *providerPath); int HLT_SetProviderAttrName(HLT_Ctx_Config *ctxConfig, char *attrName); int HLT_AddProviderInfo(HLT_Ctx_Config *ctxConfig, char *providerName, int providerLibFmt); int HLT_SetTls13CipherSuites(HLT_Ctx_Config *ctxConfig, const char *cipherSuites); int HLT_SetEcPointFormats(HLT_Ctx_Config* ctxConfig, const char* pointFormat); int HLT_SetGroups(HLT_Ctx_Config* ctxConfig, const char* groups); int HLT_SetSignature(HLT_Ctx_Config* ctxConfig, const char* signature); int HLT_SetCaCertPath(HLT_Ctx_Config* ctxConfig, const char* caCertPath); int HLT_SetChainCertPath(HLT_Ctx_Config* ctxConfig, const char* chainCertPath); int HLT_SetEeCertPath(HLT_Ctx_Config* ctxConfig, const char* eeCertPath); int HLT_SetPrivKeyPath(HLT_Ctx_Config* ctxConfig, const char* privKeyPath); int HLT_SetPassword(HLT_Ctx_Config* ctxConfig, const char* password); void HLT_SetCertPath(HLT_Ctx_Config* ctxConfig, const char *caPath, const char *chainPath, const char *EePath, const char *PrivPath, const char *signCert, const char *signPrivKey); int HLT_SetPsk(HLT_Ctx_Config *ctxConfig, char *psk); int HLT_SetKeyExchMode(HLT_Ctx_Config *config, uint32_t mode); int HLT_SetTicketKeyCb(HLT_Ctx_Config *ctxConfig, char *ticketKeyCbName); int HLT_SetServerName(HLT_Ctx_Config *ctxConfig, const char *serverName); int HLT_SetServerNameArg(HLT_Ctx_Config *ctxConfig, char *arg); int HLT_SetServerNameCb(HLT_Ctx_Config *ctxConfig, char *sniCbName); int HLT_SetAlpnProtos(HLT_Ctx_Config *ctxConfig, const char *alpnProtos); int HLT_SetAlpnProtosSelectCb(HLT_Ctx_Config *ctxConfig, char *callback, char *userData); // Interface for setting abnormal message operations int HLT_SetFrameHandle(HLT_FrameHandle *frameHandle); void HLT_CleanFrameHandle(void); int HLT_FreeResFromSsl(const void *ssl); int HLT_SetClientHelloCb(HLT_Ctx_Config *ctxConfig, HITLS_ClientHelloCb callback, void *arg); int HLT_SetCertCb(HLT_Ctx_Config *ctxConfig, HITLS_CertCb certCb, void *arg); int HLT_SetCAList(HLT_Ctx_Config *ctxConfig, HITLS_TrustedCAList *caList); // General initialization interface int HLT_LibraryInit(TLS_TYPE tlsType); // The local process invokes TLS functions HLT_Tls_Res* HLT_ProcessTlsInit(HLT_Process *process, TLS_VERSION tlsVersion, HLT_Ctx_Config *ctxConfig, HLT_Ssl_Config *sslConfig); void* HLT_TlsNewCtx(TLS_VERSION tlsVersion); void* HLT_TlsProviderNewCtx(char *providerPath, char (*providerNames)[MAX_PROVIDER_NAME_LEN], int *providerLibFmts, int providerCnt, char *attrName, TLS_VERSION tlsVersion); HLT_Ctx_Config* HLT_NewCtxConfig(char* setFile, const char* key); HLT_Ctx_Config* HLT_NewCtxConfigTLCP(char *setFile, const char *key, bool isClient); int HLT_TlsSetCtx(void* ctx, HLT_Ctx_Config* config); HLT_Ssl_Config* HLT_NewSslConfig(char* setFile); void* HLT_TlsNewSsl(void* ctx); int HLT_TlsSetSsl(void* ssl, HLT_Ssl_Config* config); unsigned long int HLT_TlsListen(void *ssl); unsigned long int HLT_TlsAccept(void* ssl); int HLT_TlsListenBlock(void* ssl); int HLT_TlsAcceptBlock(void* ssl); int HLT_GetTlsAcceptResultFromId(unsigned long int threadId); int HLT_GetTlsAcceptResult(HLT_Tls_Res* tlsRes); int HLT_TlsConnect(void* ssl); int HLT_TlsRead(void* ssl, uint8_t *data, uint32_t bufSize, uint32_t *readLen); int HLT_TlsWrite(void* ssl, uint8_t *data, uint32_t dataLen); int HLT_TlsRegCallback(TlsCallbackType type); int HLT_TlsRenegotiate(void *ssl); int HLT_TlsVerifyClientPostHandshake(void *ssl); int HLT_TlsClose(void *ssl); int HLT_TlsSetSession(void *ssl, void *session); int HLT_TlsSessionReused(void *ssl); void *HLT_TlsGet1Session(void *ssl); int32_t HLT_SetSessionCacheMode(HLT_Ctx_Config* config, HITLS_SESS_CACHE_MODE mode); int32_t HLT_SetSessionTicketSupport(HLT_Ctx_Config* config, bool issupport); int HLT_TlsSessionHasTicket(void *session); int HLT_TlsSessionIsResumable(void *session); void HLT_TlsFreeSession(void *session); // The RPC controls the remote process to invoke TLS functions int HLT_RpcTlsNewCtx(HLT_Process* peerProcess, TLS_VERSION tlsVersion, bool isClient); int HLT_RpcProviderTlsNewCtx(HLT_Process *peerProcess, TLS_VERSION tlsVersion, bool isClient, char *providerPath, char (*providerNames)[MAX_PROVIDER_NAME_LEN], int32_t *providerLibFmts, int32_t providerCnt, char *attrName); int HLT_RpcTlsSetCtx(HLT_Process* peerProcess, int ctxId, HLT_Ctx_Config* config); int HLT_RpcTlsNewSsl(HLT_Process* peerProcess, int ctxId); int HLT_RpcTlsSetSsl(HLT_Process* peerProcess, int sslId, HLT_Ssl_Config* config); int HLT_RpcTlsListen(HLT_Process* peerProcess, int sslId); int HLT_RpcTlsAccept(HLT_Process* peerProcess, int sslId); int HLT_RpcGetTlsListenResult(int acceptId); int HLT_RpcGetTlsAcceptResult(int acceptId); int HLT_RpcTlsConnect(HLT_Process* peerProcess, int sslId); int HLT_RpcTlsConnectUnBlock(HLT_Process *peerProcess, int sslId); int HLT_RpcGetTlsConnectResult(int cmdIndex); int HLT_RpcTlsRead(HLT_Process* peerProcess, int sslId, uint8_t *data, uint32_t bufSize, uint32_t *readLen); int HLT_RpcTlsReadUnBlock(HLT_Process *peerProcess, int sslId, uint8_t *data, uint32_t bufSize, uint32_t *readLen); int HLT_RpcGetTlsReadResult(int cmdIndex, uint8_t *data, uint32_t bufSize, uint32_t *readLen); int HLT_RpcTlsWrite(HLT_Process* peerProcess, int sslId, uint8_t *data, uint32_t bufSize); int HLT_RpcTlsWriteUnBlock(HLT_Process *peerProcess, int sslId, uint8_t *data, uint32_t bufSize); int HLT_RpcGetTlsWriteResult(int cmdIndex); int HLT_RpcTlsRenegotiate(HLT_Process *peerProcess, int sslId); int HLT_RpcTlsVerifyClientPostHandshake(HLT_Process *peerProcess, int sslId); int HLT_RpcTlsRegCallback(HLT_Process* peerProcess, TlsCallbackType type); int HLT_RpcProcessExit(HLT_Process* peerProcess); int HLT_RpcDataChannelBind(HLT_Process *peerProcess, DataChannelParam *channelParam); int HLT_RpcDataChannelAccept(HLT_Process* peerProcess, DataChannelParam* channelParam); int HLT_RpcGetAcceptFd(int acceptId); int HLT_RpcDataChannelConnect(HLT_Process* peerProcess, DataChannelParam* channelParam); int HLT_RpcTlsGetStatus(HLT_Process *peerProcess, int sslId); int HLT_RpcTlsGetAlertFlag(HLT_Process *peerProcess, int sslId); int HLT_RpcTlsGetAlertLevel(HLT_Process *peerProcess, int sslId); int HLT_RpcTlsGetAlertDescription(HLT_Process *peerProcess, int sslId); int HLT_RpcTlsClose(HLT_Process *peerProcess, int sslId); int HLT_RpcFreeResFormSsl(HLT_Process *peerProcess, int sslId); int HLT_RpcSctpClose(HLT_Process *peerProcess, int fd); int HLT_RpcCloseFd(HLT_Process *peerProcess, int fd, int linkType); int HLT_RpcTlsSetMtu(HLT_Process *peerProcess, int sslId, uint16_t mtu); int HLT_RpcTlsGetErrorCode(HLT_Process *peerProcess, int sslId); // TLS connection establishment encapsulation interface HLT_Tls_Res* HLT_ProcessTlsAccept(HLT_Process *process, TLS_VERSION tlsVersion, HLT_Ctx_Config *ctxConfig, HLT_Ssl_Config *sslConfig); HLT_Tls_Res* HLT_ProcessTlsConnect(HLT_Process *process, TLS_VERSION tlsVersion, HLT_Ctx_Config *ctxConfig, HLT_Ssl_Config *sslConfig); int HLT_ProcessTlsRead(HLT_Process *process, HLT_Tls_Res* tlsRes, uint8_t *data, uint32_t bufSize, uint32_t *dataLen); int HLT_ProcessTlsWrite(HLT_Process *process, HLT_Tls_Res* tlsRes, uint8_t *data, uint32_t dataLen); int HLT_TlsSetMtu(void *ssl, uint16_t mtu); int HLT_TlsGetErrorCode(void *ssl); bool IsEnableSctpAuth(void); #ifdef __cplusplus } #endif #endif // HLT_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/include/hlt.h
C
unknown
10,222
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HLT_TYPE_H #define HLT_TYPE_H #include <stdint.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <stdbool.h> #include "uio_base.h" #include "bsl_uio.h" #include "hitls_type.h" #include "tls_config.h" #ifdef __cplusplus extern "C" { #endif #define IP_LEN (32) #define MAX_CIPHERSUITES_LEN (512) #define MAX_POINTFORMATS_LEN (512) #define MAX_GROUPS_LEN (512) #define MAX_SIGNALGORITHMS_LEN (512) #define MAX_CERT_LEN (512) #define PSK_MAX_LEN (256) #define TICKET_KEY_CB_NAME_LEN (50) #define MAX_SERVER_NAME_LEN (256) #define SERVER_NAME_CB_NAME_LEN (50) #define SERVER_NAME_ARG_NAME_LEN (50) #define MAX_ALPN_LEN (256) #define ALPN_CB_NAME_LEN (50) #define ALPN_DATA_NAME_LEN (50) #define MAX_NO_RENEGOTIATIONCB_LEN (1024) #define MAX_PROVIDER_NAME_LEN (256) #define MAX_ATTR_NAME_LEN (256) #define MAX_PROVIDER_PATH_LEN (256) #define MAX_PROVIDER_COUNT (10) #define KEY_LOG_CB_LEN (1024) #define DEFAULT_CERT_PATH "../../testcode/testdata/tls/certificate/der/" #define RSAPSS_SHA256_CA_PATH "rsa_pss_sha256/rsa_pss_root.der:rsa_pss_sha256/rsa_pss_intCa.der" #define RSAPSS_SHA256_CHAIN_PATH "rsa_pss_sha256/rsa_pss_intCa.der" #define RSAPSS_SHA256_EE_PATH "rsa_pss_sha256/rsa_pss_dev.der" #define RSAPSS_SHA256_PRIV_PATH "rsa_pss_sha256/rsa_pss_dev.key.der" #define RSAPSS_RSAE_CA_PATH "rsa_pss_rsae/rsa_root.der:rsa_pss_rsae/rsa_intCa.der" #define RSAPSS_RSAE_CHAIN_PATH "rsa_pss_rsae/rsa_intCa.der" #define RSAPSS_RSAE_EE_PATH "rsa_pss_rsae/rsa_dev.der" #define RSAPSS_RSAE_PRIV_PATH "rsa_pss_rsae/rsa_dev.key.der" #define RSA_SHA_CA_PATH "rsa_sha/ca-3072.der:rsa_sha/inter-3072.der" #define RSA_SHA_CHAIN_PATH "rsa_sha/inter-3072.der" #define RSA_SHA1_EE_PATH "rsa_sha/end-sha1.der" #define RSA_SHA1_PRIV_PATH "rsa_sha/end-sha1.key.der" #define RSA_SHA384_EE_PATH "rsa_sha/end-sha384.der" #define RSA_SHA384_PRIV_PATH "rsa_sha/end-sha384.key.der" #define RSA_SHA512_EE_PATH "rsa_sha/end-sha512.der" #define RSA_SHA512_PRIV_PATH "rsa_sha/end-sha512.key.der" #define ED25519_SHA512_CA_PATH "ed25519/ed25519.ca.der:ed25519/ed25519.intca.der" #define ED25519_SHA512_CHAIN_PATH "ed25519/ed25519.intca.der" #define ED25519_SHA512_EE_PATH "ed25519/ed25519.end.der" #define ED25519_SHA512_PRIV_PATH "ed25519/ed25519.end.key.der" #define ECDSA_SHA_CA_PATH "ecdsa/ca-nist521.der:ecdsa/inter-nist521.der" #define ECDSA_SHA_CHAIN_PATH "ecdsa/inter-nist521.der" #define ECDSA_SHA256_EE_PATH "ecdsa/end256-sha256.der" #define ECDSA_SHA256_PRIV_PATH "ecdsa/end256-sha256.key.der" #define ECDSA_SHA384_EE_PATH "ecdsa/end384-sha384.der" #define ECDSA_SHA384_PRIV_PATH "ecdsa/end384-sha384.key.der" #define ECDSA_SHA512_EE_PATH "ecdsa/end521-sha512.der" #define ECDSA_SHA512_PRIV_PATH "ecdsa/end521-sha512.key.der" #define ECDSA_SHA1_CA_PATH "ecdsa_sha1/ca-nist521.der:ecdsa_sha1/inter-nist521.der" #define ECDSA_SHA1_CHAIN_PATH "ecdsa_sha1/inter-nist521.der" #define ECDSA_SHA1_EE_PATH "ecdsa_sha1/end384-sha1.der" #define ECDSA_SHA1_PRIV_PATH "ecdsa_sha1/end384-sha1.key.der" #define RSA_SHA256_CA_PATH "rsa_sha256/ca.der:rsa_sha256/inter.der" #define RSA_SHA256_CHAIN_PATH "rsa_sha256/inter.der" #define RSA_SHA256_EE_PATH1 "rsa_sha256/server.der" #define RSA_SHA256_PRIV_PATH1 "rsa_sha256/server.key.der" #define RSA_SHA256_EE_PATH2 "rsa_sha256/client.der" #define RSA_SHA256_PRIV_PATH2 "rsa_sha256/client.key.der" #define RSA_SHA256_EE_PATH3 "rsa_sha/end-sha256.der" #define RSA_SHA256_PRIV_PATH3 "rsa_sha/end-sha256.key.der" #define ECDSA_SHA256_CA_PATH "ecdsa_sha256/ca.der:ecdsa_sha256/inter.der" #define ECDSA_SHA256_CHAIN_PATH "ecdsa_sha256/inter.der" #define ECDSA_SHA256_EE_PATH1 "ecdsa_sha256/server.der" #define ECDSA_SHA256_PRIV_PATH1 "ecdsa_sha256/server.key.der" #define ECDSA_SHA256_EE_PATH2 "ecdsa_sha256/client.der" #define ECDSA_SHA256_PRIV_PATH2 "ecdsa_sha256/client.key.der" #define SM2_VERIFY_PATH "sm2_with_userid/ca.der:sm2_with_userid/inter.der" #define SM2_CHAIN_PATH "sm2_with_userid/inter.der" #define SM2_SERVER_ENC_CERT_PATH "sm2_with_userid/enc.der" #define SM2_SERVER_ENC_KEY_PATH "sm2_with_userid/enc.key.der" #define SM2_SERVER_SIGN_CERT_PATH "sm2_with_userid/sign.der" #define SM2_SERVER_SIGN_KEY_PATH "sm2_with_userid/sign.key.der" #define SM2_CLIENT_ENC_CERT_PATH "sm2_with_userid/enc22.der" #define SM2_CLIENT_ENC_KEY_PATH "sm2_with_userid/enc22.key.der" #define SM2_CLIENT_SIGN_CERT_PATH "sm2_with_userid/sign22.der" #define SM2_CLIENT_SIGN_KEY_PATH "sm2_with_userid/sign22.key.der" typedef struct ProcessSt HLT_Process; typedef enum { HITLS, HITLS_PROVIDER, } TLS_TYPE; typedef enum { CLIENT, SERVER } TLS_ROLE; typedef enum { DTLS_ALL, DTLS1_0, DTLS1_2, TLS_ALL, SSL3_0, TLS1_0, TLS1_1, TLS1_2, TLS1_3, TLCP1_1, DTLCP1_1, } TLS_VERSION; typedef enum { TCP = 0, /**< TCP protocol */ SCTP = 1, /**< SCTP protocol */ UDP = 2, /**< UDP protocol */ NONE_TYPE = 10, } HILT_TransportType; typedef enum { CERT_CALLBACK_DEFAULT, } CertCallbackType; typedef enum { MEM_CALLBACK_DEFAULT, } MemCallbackType; typedef enum { HITLS_CALLBACK_DEFAULT, } TlsCallbackType; typedef enum { COOKIE_CB_DEFAULT, // Normal cookie callback COOKIE_CB_LEN_0, // The length of the generated cookie is 0 } CookieCallbackType; typedef struct { struct sockaddr_in sockAddr; HILT_TransportType type; char ip[IP_LEN]; int port; int bindFd; bool isBlock; } DataChannelParam; typedef struct { struct sockaddr_in sockAddr; int connPort; int srcFd; int peerFd; } HLT_FD; typedef enum { SERVER_CTX_SET_TRUE = 1, SERVER_CTX_SET_FALSE = 2, SERVER_CFG_SET_TRUE = 3, SERVER_CFG_SET_FALSE = 4, } HILT_SupportType; typedef struct { uint16_t mtu; // Set the MTU in the dtls. // The maximum version number and minimum version number must be both TLS and DTLS. // Currently, only DTLS 1.2 is supported uint32_t minVersion; uint32_t maxVersion; char cipherSuites[MAX_CIPHERSUITES_LEN]; // cipher suite char tls13CipherSuites[MAX_CIPHERSUITES_LEN]; // TLS13 cipher suite char pointFormats[MAX_POINTFORMATS_LEN]; // ec Point Format // According to RFC 8446 4.2.7, before TLS 1.3: ec curves; TLS 1.3: group supported by the key exchange. char groups[MAX_GROUPS_LEN]; char signAlgorithms[MAX_SIGNALGORITHMS_LEN]; // signature algorithm char serverName[MAX_SERVER_NAME_LEN]; // Client server_name // Name of the server_name callback function for processing the first handshake on the server char sniDealCb[SERVER_NAME_CB_NAME_LEN]; // name of the value function related to the server_name registered by the product char sniArg[SERVER_NAME_ARG_NAME_LEN]; char alpnList[MAX_ALPN_LEN]; // alpn char alpnUserData[ALPN_CB_NAME_LEN]; char alpnSelectCb[ALPN_DATA_NAME_LEN]; // Application Layer Protocol Select Callback char keyLogCb[KEY_LOG_CB_LEN]; // Indicates whether renegotiation is supported. The default value is False, indicating that renegotiation is not // supported bool isSupportRenegotiation; bool allowClientRenegotiate; /* allow a renegotiation initiated by the client */ bool allowLegacyRenegotiate; /* whether to abort handshake when server doesn't support SecRenegotiation */ int SupportType; // 1:The server algorithm is preferred bool needCheckKeyUsage; // Client verification is supported. The default value is False // Indicates whether to allow the empty certificate list on the client. The default value is False bool isSupportClientVerify; bool isSupportNoClientCert; // supports extended master keys. The default value is True // The handshake will be continued regardless of the verification result. for server and client bool isSupportVerifyNone; bool isSupportPostHandshakeAuth; // Indicates whether to support post handshake auth. The default value is false. bool isSupportExtendMasterSecret; // supports extended master keys. The default value is True bool isSupportSessionTicket; // Support session ticket bool isEncryptThenMac; // Encrypt-then-mac is supported // Users can set the DH parameter to be automatically selected. If the switch is enabled, // the DH parameter is automatically selected based on the length of the certificate private key bool isSupportDhAuto; int32_t setSessionCache; // Setting the Session Storage Mode uint32_t keyExchMode; // TLS1.3 key exchange mode void *infoCb; // connection establishment callback function void *msgCb; // Message callback function void *msgArg; // Message callback parameter function void *certCb; void *certArg; void *clientHelloCb; void *clientHelloArg; // Indicates whether to enable the function of sending handshake information by flight bool isFlightTransmitEnable; bool isNoSetCert; // Indicates whether the certificate does not need to be set int32_t securitylevel; // Security level int32_t readAhead; void *caList; char psk[PSK_MAX_LEN]; // psk password char ticketKeyCb[TICKET_KEY_CB_NAME_LEN]; // ticket key Callback Function Name char eeCert[MAX_CERT_LEN]; char privKey[MAX_CERT_LEN]; char signCert[MAX_CERT_LEN]; char signPrivKey[MAX_CERT_LEN]; char password[MAX_CERT_LEN]; char caCert[MAX_CERT_LEN]; char chainCert[MAX_CERT_LEN]; bool isClient; uint32_t emptyRecordsNum; char providerPath[MAX_PROVIDER_PATH_LEN]; char providerNames[MAX_PROVIDER_COUNT][MAX_PROVIDER_NAME_LEN]; int32_t providerLibFmts[MAX_PROVIDER_COUNT]; int32_t providerCnt; char attrName[MAX_ATTR_NAME_LEN]; uint32_t modeSupport; // support features, such as HITLS_MODE_SEND_FALLBACK_SCSV. All mode at hitls_type.h bool isMiddleBoxCompat; // Indicates whether to enable the middle box compatibility mode. } HLT_Ctx_Config; typedef struct { struct sockaddr_in sockAddr; int connPort; int sockFd; HILT_TransportType connType; int SupportType; // 3:The server algorithm is preferred int sctpCtrlCmd; } HLT_Ssl_Config; typedef struct { void *ctx; // hitls config void *ssl; // hitls ctx int ctxId; int sslId; unsigned long int acceptId; } HLT_Tls_Res; typedef enum { EXP_NONE, EXP_IO_BUSY, EXP_RECV_BUF_EMPTY, } HLT_ExpectIoState; typedef enum { POINT_NONE, POINT_RECV, POINT_SEND, } HLT_PointType; /** * @brief msg processing callback */ typedef void (*HLT_FrameCallBack)(void *msg, void *userData); typedef struct { BSL_UIO_Method method; /**< User-defined message sending and receiving control function */ HLT_FrameCallBack frameCallBack; /**< msg processing callback */ void *ctx; /**< TLS context */ int32_t expectReType; /**< Corresponding enumeration REC_Type */ int32_t expectHsType; /**< Corresponding enumerated value HS_MsgType */ HLT_ExpectIoState ioState; /**< customized I/O status */ HLT_PointType pointType; /**< Callback function for recording keys */ void *userData; /**< Customized data, which will be transferred to the msg processing callback */ } HLT_FrameHandle; #if (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) #define TIME_OUT_SEC 50 #else #define TIME_OUT_SEC 8 #endif #ifdef __cplusplus } #endif #endif // HLT_TYPE_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/include/hlt_type.h
C
unknown
12,384
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef FRAME_IO_H #define FRAME_IO_H #include "bsl_errno.h" #include "bsl_uio.h" #ifdef __cplusplus extern "C" { #endif #define MAX_RECORD_LENTH (20 * 1024) // Simulates the bottom-layer sending and receiving processing of the DT framework. typedef struct FrameUioUserData_ FrameUioUserData; /** * @brief SCTP bottom-layer I/O function, which is used to simulate the SCTP message sending interface. * * @par Description: * SCTP bottom-layer I/O function, which is used to simulate the SCTP message sending interface. * * @attention * @return If the operation is successful, success is returned. Otherwise, other values are returned. In this framework, * a success message is returned without special reasons. */ int32_t FRAME_Write(BSL_UIO *uio, const void *buf, uint32_t len, uint32_t *writeLen); /** * @brief SCTP bottom-layer I/O function, which is used to simulate the SCTP message receiving interface. * * @par Description: * SCTP bottom-layer I/O function, which is used to simulate the SCTP message receiving interface. * * @attention * @return If the operation is successful, success is returned. Otherwise, other values are returned. */ int32_t FRAME_Read(BSL_UIO *uio, void *buf, uint32_t len, uint32_t *readLen); /** * @brief SCTP bottom-layer I/O function, which is used to simulate the SCTP control interface. * * @par Description: * SCTP bottom-layer I/O function, which is used to simulate the SCTP control interface. * * @attention * @return If the operation is successful, success is returned. Otherwise, other values are returned. */ int32_t FRAME_Ctrl(BSL_UIO *uio, int32_t cmd, int32_t larg, void *param); /** * @brief Create a UIO user data. The user data must be used when the I/O of the test framework is used. The user data * stores the data to be sent and received by the I/O. * * @return If the operation is successful, the pointer of userdata is returned. */ FrameUioUserData *FRAME_IO_CreateUserData(void); /** * @brief Releases userdata created by the Frame_IO_CreateUserData function. * * @return NA */ void FRAME_IO_FreeUserData(FrameUioUserData *userData); /** * @brief Frame_TransportSendMsg sends the messages in the sending buffer in the I/O. * * @return If the operation is successful, 0 is returned. Otherwise, another value is returned. */ int32_t FRAME_TransportSendMsg(BSL_UIO *uio, void *buf, uint32_t len, uint32_t *readLen); /** * @brief Frame_TransportRecMsg simulates receiving messages from the I/O. * * @return If the operation is successful, 0 is returned. Otherwise, another value is returned. */ int32_t FRAME_TransportRecMsg(BSL_UIO *uio, void *buf, uint32_t len); #ifdef __cplusplus } #endif #endif // FRAME_IO_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/io/include/frame_io.h
C
unknown
3,272
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "simulate_io.h" #include "hitls_error.h" #include "bsl_sal.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_errno.h" #include "bsl_uio.h" #include "securec.h" #define FAKE_BSL_UIO_FD 666 FrameUioUserData *FRAME_IO_CreateUserData(void) { FrameUioUserData *userData = BSL_SAL_Calloc(1u, sizeof(FrameUioUserData)); if (userData == NULL) { return NULL; } return userData; } void FRAME_IO_FreeUserData(FrameUioUserData *userData) { if (userData == NULL) { return; } BSL_SAL_FREE(userData); return; } int32_t FRAME_Write(BSL_UIO *uio, const void *buf, uint32_t len, uint32_t *writeLen) { *writeLen = 0; FrameUioUserData *ioUserData = BSL_UIO_GetUserData(uio); if (ioUserData == NULL) { return BSL_NULL_INPUT; } // This indicates that there is still a message in the buffer. The second message can be sent only after the peer // end receives the message. if (ioUserData->sndMsg.len != 0) { return BSL_SUCCESS; } memcpy_s(ioUserData->sndMsg.msg, MAX_RECORD_LENTH, buf, len); ioUserData->sndMsg.len = len; *writeLen = len; return BSL_SUCCESS; } int32_t FRAME_Read(BSL_UIO *uio, void *buf, uint32_t len, uint32_t *readLen) { *readLen = 0; FrameUioUserData *ioUserData = BSL_UIO_GetUserData(uio); if (ioUserData == NULL) { return BSL_NULL_INPUT; } // This indicates that the user inserts data. Therefore, the simulated data inserted by the user is received first. if (ioUserData->userInsertMsg.len != 0) { if (len < ioUserData->userInsertMsg.len) { return BSL_UIO_FAIL; } memcpy_s(buf, len, ioUserData->userInsertMsg.msg, ioUserData->userInsertMsg.len); *readLen = ioUserData->userInsertMsg.len; ioUserData->userInsertMsg.len = 0; return BSL_SUCCESS; } else if (ioUserData->recMsg.len != 0) { uint32_t copyLen = len < ioUserData->recMsg.len ? len : ioUserData->recMsg.len; memcpy_s(buf, len, ioUserData->recMsg.msg, copyLen); *readLen = copyLen; if (copyLen < ioUserData->recMsg.len) { memmove_s(ioUserData->recMsg.msg, ioUserData->recMsg.len, &ioUserData->recMsg.msg[copyLen], ioUserData->recMsg.len - copyLen); } ioUserData->recMsg.len -= copyLen; return BSL_SUCCESS; } // If there is no data in the receive buffer, a success message is returned and *readLen is set to 0. return BSL_SUCCESS; } int32_t FRAME_Ctrl(BSL_UIO *uio, int32_t cmd, int32_t larg, void *param) { (void)uio; (void)larg; if (cmd == BSL_UIO_SCTP_SND_BUFF_IS_EMPTY) { *(uint8_t *)param = true; } if (cmd == BSL_UIO_GET_FD) { *(int32_t *)param = FAKE_BSL_UIO_FD; } return BSL_SUCCESS; } /* Frame_TransportSendMsg: Sends messages in the send buffer in the I/O. Copy uio->userData to the buffer. */ int32_t FRAME_TransportSendMsg(BSL_UIO *uio, void *buf, uint32_t len, uint32_t *readLen) { *readLen = 0; FrameUioUserData *ioUserData = BSL_UIO_GetUserData(uio); if (ioUserData == NULL) { return HITLS_NULL_INPUT; } if (ioUserData->sndMsg.len != 0) { // The length of the data in the buffer exceeds len. if (len < ioUserData->sndMsg.len) { return HITLS_UIO_FAIL; } memcpy_s(buf, len, ioUserData->sndMsg.msg, ioUserData->sndMsg.len); *readLen = ioUserData->sndMsg.len; ioUserData->sndMsg.len = 0; } // If there is no data in the receive buffer, a success message is returned and *readLen is set to 0. return HITLS_SUCCESS; } /* Frame_TransportRecMsg simulates receiving messages from the I/O. Copy the data in the buffer to uio->userData. */ int32_t FRAME_TransportRecMsg(BSL_UIO *uio, void *buf, uint32_t len) { FrameUioUserData *ioUserData = BSL_UIO_GetUserData(uio); if (ioUserData == NULL) { return HITLS_NULL_INPUT; } if (ioUserData->recMsg.len != 0 || len > MAX_RECORD_LENTH) { return HITLS_UIO_FAIL; } memcpy_s(ioUserData->recMsg.msg, MAX_RECORD_LENTH, buf, len); ioUserData->recMsg.len = len; return HITLS_SUCCESS; } #ifdef __cplusplus } #endif
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/io/src/simulate_io.c
C
unknown
4,808
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef SIMULATE_IO_H #define SIMULATE_IO_H #include "frame_io.h" #include "bsl_bytes.h" #ifdef __cplusplus extern "C" { #endif typedef struct { uint8_t msg[MAX_RECORD_LENTH]; uint32_t len; } FrameMsg; struct FrameUioUserData_ { FrameMsg sndMsg; FrameMsg recMsg; FrameMsg userInsertMsg; }; #define REC_RECORD_DTLS_EPOCH_OFFSET 3 #define REC_RECORD_DTLS_LENGTH_OFFSET 11 #ifdef __cplusplus } #endif #endif // SIMULATE_IO_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/io/src/simulate_io.h
C
unknown
994
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef PACK_FRAME_MSG_H #define PACK_FRAME_MSG_H #include "frame_msg.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Generate a framework message based on the content in the message buffer. * * @return Returns the CTX object of the TLS. */ int32_t PackFrameMsg(FRAME_Msg *msg); #ifdef __cplusplus } #endif #endif // PACK_FRAME_MSG_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/msg/include/pack_frame_msg.h
C
unknown
889
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef PARSER_FRAME_MSG_H #define PARSER_FRAME_MSG_H #include "frame_msg.h" #ifdef __cplusplus extern "C" { #endif int32_t ParserRecordHeader(FRAME_Msg *frameMsg, const uint8_t *buffer, uint32_t len, uint32_t *parserLen); int32_t ParserRecordBody(const FRAME_LinkObj *linkObj, FRAME_Msg *frameMsg, const uint8_t *buffer, uint32_t len, uint32_t *parserLen); int32_t ParserTotalRecord(const FRAME_LinkObj *linkObj, FRAME_Msg *frameMsg, const uint8_t *buffer, uint32_t len, uint32_t *parserLen); void CleanRecordBody(FRAME_Msg *frameMsg); #ifdef __cplusplus } #endif #endif // PARSER_FRAME_MSG_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/msg/include/parser_frame_msg.h
C
unknown
1,151
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "securec.h" #include "bsl_sal.h" #include "hitls.h" #include "hitls_config.h" #include "hitls_error.h" #include "hitls_type.h" #include "frame_tls.h" #include "frame_msg.h" #include "frame_link.h" #include "frame_io.h" #include "simulate_io.h" #define DEFAUTL_COOKIE_LEN 32 /* Used to establish a link and stop in the state. */ typedef struct { HITLS_Config *config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_HandshakeState state; bool isClient; BSL_UIO_TransportType transportType; } LinkPara; static void CleanLinkPara(LinkPara *linkPara) { HITLS_CFG_FreeConfig(linkPara->config); FRAME_FreeLink(linkPara->client); FRAME_FreeLink(linkPara->server); } static int32_t PauseState(LinkPara *linkPara, uint16_t version) { (void)version; BSL_UIO_TransportType transportType = linkPara->transportType; #ifdef HITLS_TLS_PROTO_TLCP11 /* Constructing a Link */ if ( version == HITLS_VERSION_TLCP_DTLCP11 ) { linkPara->client = FRAME_CreateTLCPLink(linkPara->config, transportType, true); linkPara->server = FRAME_CreateTLCPLink(linkPara->config, transportType, false); } else #endif /* HITLS_TLS_PROTO_TLCP11 */ { linkPara->client = FRAME_CreateLink(linkPara->config, transportType); linkPara->server = FRAME_CreateLink(linkPara->config, transportType); } if (linkPara->client == NULL || linkPara->server == NULL) { return HITLS_INTERNAL_EXCEPTION; } /* Establish a link and stop in a certain state. */ if (FRAME_CreateConnection(linkPara->client, linkPara->server, linkPara->isClient, linkPara->state) != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } /* Check whether the status is consistent. */ HITLS_Ctx *ctx = linkPara->isClient ? linkPara->client->ssl : linkPara->server->ssl; if ((ctx->hsCtx == NULL) || (ctx->hsCtx->state != linkPara->state)) { return HITLS_INTERNAL_EXCEPTION; } return HITLS_SUCCESS; } static int32_t SetLinkState(HS_MsgType hsType, LinkPara *linkPara) { linkPara->isClient = true; switch (hsType) { case CLIENT_HELLO: linkPara->isClient = false; linkPara->state = TRY_RECV_CLIENT_HELLO; return HITLS_SUCCESS; case SERVER_HELLO: linkPara->state = TRY_RECV_SERVER_HELLO; return HITLS_SUCCESS; case CERTIFICATE: linkPara->state = TRY_RECV_CERTIFICATE; return HITLS_SUCCESS; case SERVER_KEY_EXCHANGE: linkPara->state = TRY_RECV_SERVER_KEY_EXCHANGE; return HITLS_SUCCESS; case CERTIFICATE_REQUEST: linkPara->state = TRY_RECV_CERTIFICATE_REQUEST; return HITLS_SUCCESS; case SERVER_HELLO_DONE: linkPara->state = TRY_RECV_SERVER_HELLO_DONE; return HITLS_SUCCESS; case CERTIFICATE_VERIFY: linkPara->isClient = false; linkPara->state = TRY_RECV_CERTIFICATE_VERIFY; return HITLS_SUCCESS; case CLIENT_KEY_EXCHANGE: linkPara->isClient = false; linkPara->state = TRY_RECV_CLIENT_KEY_EXCHANGE; return HITLS_SUCCESS; case FINISHED: // The existing framework does not support parsing of encrypted finished messages. // Therefore, finished messages cannot be obtained. break; default: break; } return HITLS_INTERNAL_EXCEPTION; } static int32_t SetLinkConfig(uint16_t version, HITLS_KeyExchAlgo keyExAlgo, LinkPara *linkPara) { if (linkPara == NULL) { return HITLS_INTERNAL_EXCEPTION; } linkPara->config = NULL; if (IS_DTLS_VERSION(version)) { linkPara->config = HITLS_CFG_NewDTLS12Config(); } else if (version == HITLS_VERSION_TLS12) { linkPara->config = HITLS_CFG_NewTLS12Config(); } else if (version == HITLS_VERSION_TLS13) { linkPara->config = HITLS_CFG_NewTLS13Config(); } else if (version == HITLS_VERSION_TLCP_DTLCP11) { if (IS_TRANSTYPE_DATAGRAM(linkPara->transportType)) { linkPara->config = HITLS_CFG_NewDTLCPConfig(); } else { linkPara->config = HITLS_CFG_NewTLCPConfig(); } return HITLS_SUCCESS; } #ifdef HITLS_TLS_CONFIG_KEY_USAGE HITLS_CFG_SetCheckKeyUsage(linkPara->config, false); #endif /* HITLS_TLS_CONFIG_KEY_USAGE */ #ifdef HITLS_TLS_FEATURE_CERT_MODE int32_t ret = HITLS_CFG_SetClientVerifySupport(linkPara->config, true); if (ret != HITLS_SUCCESS) { return ret; } #endif /* HITLS_TLS_FEATURE_CERT_MODE */ if (keyExAlgo == HITLS_KEY_EXCH_DHE) { uint16_t cipherSuites[] = {HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256}; HITLS_CFG_SetCipherSuites(linkPara->config, cipherSuites, sizeof(cipherSuites) / sizeof(uint16_t)); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256}; HITLS_CFG_SetSignature(linkPara->config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); } else { uint16_t groups[] = {HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(linkPara->config, groups, sizeof(groups) / sizeof(uint16_t)); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(linkPara->config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); } return HITLS_SUCCESS; } static int32_t GetdefaultHsMsg(FRAME_Type *frameType, FRAME_Msg *parsedMsg) { int32_t ret; LinkPara linkPara = {0}; /* Configure config. */ linkPara.transportType = frameType->transportType; ret = SetLinkConfig(frameType->versionType, frameType->keyExType, &linkPara); if (ret != HITLS_SUCCESS) { CleanLinkPara(&linkPara); return ret; } /* Setting the parked state */ ret = SetLinkState(frameType->handshakeType, &linkPara); if (ret != HITLS_SUCCESS) { CleanLinkPara(&linkPara); return ret; } /* Stop in this state */ ret = PauseState(&linkPara, frameType->versionType); if (ret != HITLS_SUCCESS) { CleanLinkPara(&linkPara); return ret; } /* Obtain the message buffer. */ FRAME_LinkObj *link = linkPara.isClient ? linkPara.client : linkPara.server; FrameUioUserData *ioUserData = BSL_UIO_GetUserData(link->io); uint8_t *buffer = ioUserData->recMsg.msg; uint32_t len = ioUserData->recMsg.len; if (len == 0) { CleanLinkPara(&linkPara); return HITLS_INTERNAL_EXCEPTION; } /* Parse to msg structure */ uint32_t parseLen = 0; ret = FRAME_ParseMsg(frameType, buffer, len, parsedMsg, &parseLen); if ((ret != HITLS_SUCCESS) || (len != parseLen)) { CleanLinkPara(&linkPara); return HITLS_INTERNAL_EXCEPTION; } CleanLinkPara(&linkPara); return HITLS_SUCCESS; } static void SetDefaultRecordHeader(FRAME_Type *frameType, FRAME_Msg *msg, REC_Type recType) { msg->recType.state = INITIAL_FIELD; msg->recType.data = recType; msg->recVersion.state = INITIAL_FIELD; if (IS_DTLS_VERSION(frameType->versionType)) { msg->recVersion.data = HITLS_VERSION_DTLS12; } else if (frameType->versionType == HITLS_VERSION_TLCP_DTLCP11) { msg->recVersion.data = HITLS_VERSION_TLCP_DTLCP11; } else { msg->recVersion.data = HITLS_VERSION_TLS12; } msg->epoch.state = INITIAL_FIELD; /* In the default message, the value is set to 0 by default. You need to assign a value to the value. */ msg->epoch.data = 0; msg->sequence.state = INITIAL_FIELD; /* In the default message, the value is set to 0 by default. You need to assign a value to the value. */ msg->sequence.data = 0; msg->length.state = INITIAL_FIELD; /* The value of length is automatically calculated during assembly. * Therefore, the value of length is initialized to 0. */ msg->length.data = 0; } static int32_t GetdefaultCcsMsg(FRAME_Type *frameType, FRAME_Msg *msg) { SetDefaultRecordHeader(frameType, msg, REC_TYPE_CHANGE_CIPHER_SPEC); /* Setting the Default Record Header */ msg->body.ccsMsg.ccsType.state = INITIAL_FIELD; msg->body.ccsMsg.ccsType.data = 1u; /* In the protocol, the CCS type has only this value. */ return HITLS_SUCCESS; } static int32_t GetdefaultAlertMsg(FRAME_Type *frameType, FRAME_Msg *msg) { SetDefaultRecordHeader(frameType, msg, REC_TYPE_ALERT); /* Setting the Default Record Header */ msg->body.alertMsg.alertLevel.state = INITIAL_FIELD; /*Default value. You can change the default value as required. */ msg->body.alertMsg.alertLevel.data = ALERT_LEVEL_FATAL; msg->body.alertMsg.alertDescription.state = INITIAL_FIELD; /*Default value. You can change the default value as required. */ msg->body.alertMsg.alertDescription.data = ALERT_HANDSHAKE_FAILURE; return HITLS_SUCCESS; } int32_t FRAME_GetDefaultMsg(FRAME_Type *frameType, FRAME_Msg *msg) { if ((frameType == NULL) || (msg == NULL)) { return HITLS_INTERNAL_EXCEPTION; } switch (frameType->recordType) { case REC_TYPE_HANDSHAKE: return GetdefaultHsMsg(frameType, msg); case REC_TYPE_CHANGE_CIPHER_SPEC: return GetdefaultCcsMsg(frameType, msg); case REC_TYPE_ALERT: return GetdefaultAlertMsg(frameType, msg); default: break; } return HITLS_INTERNAL_EXCEPTION; } int32_t FRAME_ModifyMsgInteger(const uint64_t data, FRAME_Integer *frameInteger) { if (frameInteger == NULL) { return HITLS_INTERNAL_EXCEPTION; } frameInteger->state = ASSIGNED_FIELD; frameInteger->data = data; return HITLS_SUCCESS; } int32_t FRAME_ModifyMsgArray8(const uint8_t *data, uint32_t dataLen, FRAME_Array8 *frameArray, FRAME_Integer *frameArrayLen) { if ((data == NULL) || (frameArray == NULL) || (dataLen == 0)) { return HITLS_INTERNAL_EXCEPTION; } BSL_SAL_FREE(frameArray->data); /* Clear the old memory. */ frameArray->data = BSL_SAL_Dump(data, dataLen); if (frameArray->data == NULL) { return HITLS_MEMALLOC_FAIL; } frameArray->state = ASSIGNED_FIELD; frameArray->size = dataLen; if (frameArrayLen != NULL) { frameArrayLen->state = ASSIGNED_FIELD; frameArrayLen->data = dataLen; } return HITLS_SUCCESS; } int32_t FRAME_AppendMsgArray8(const uint8_t *data, uint32_t dataLen, FRAME_Array8 *frameArray, FRAME_Integer *frameArrayLen) { if ((data == NULL) || (frameArray == NULL) || (dataLen == 0)) { return HITLS_INTERNAL_EXCEPTION; } /* extended memory */ uint32_t newDataLen = dataLen + frameArray->size; uint8_t *newData = (uint8_t *)BSL_SAL_Calloc(1u, newDataLen); if (newData == NULL) { return HITLS_MEMALLOC_FAIL; } if (memcpy_s(newData, newDataLen, frameArray->data, frameArray->size) != EOK) { BSL_SAL_FREE(newData); return HITLS_MEMCPY_FAIL; } if (memcpy_s(&newData[frameArray->size], newDataLen - frameArray->size, data, dataLen) != EOK) { BSL_SAL_FREE(newData); return HITLS_MEMCPY_FAIL; } BSL_SAL_FREE(frameArray->data); /* Clear the old memory. */ frameArray->state = ASSIGNED_FIELD; frameArray->data = newData; frameArray->size = newDataLen; if (frameArrayLen != NULL) { frameArrayLen->state = ASSIGNED_FIELD; frameArrayLen->data = newDataLen; } return HITLS_SUCCESS; } int32_t FRAME_ModifyMsgArray16(const uint16_t *data, uint32_t dataLen, FRAME_Array16 *frameArray, FRAME_Integer *frameArrayLen) { if ((data == NULL) || (frameArray == NULL) || (dataLen == 0)) { return HITLS_INTERNAL_EXCEPTION; } BSL_SAL_FREE(frameArray->data); /* Clear the old memory. */ frameArray->data = (uint16_t *)BSL_SAL_Dump(data, dataLen * sizeof(uint16_t)); if (frameArray->data == NULL) { return HITLS_MEMALLOC_FAIL; } frameArray->state = ASSIGNED_FIELD; frameArray->size = dataLen; if (frameArrayLen != NULL) { frameArrayLen->state = ASSIGNED_FIELD; frameArrayLen->data = dataLen * sizeof(uint16_t); } return HITLS_SUCCESS; } int32_t FRAME_AppendMsgArray16(const uint16_t *data, uint32_t dataLen, FRAME_Array16 *frameArray, FRAME_Integer *frameArrayLen) { if ((data == NULL) || (frameArray == NULL) || (dataLen == 0)) { return HITLS_INTERNAL_EXCEPTION; } /* extended memory */ uint32_t newDataLen = (frameArray->size + dataLen) * sizeof(uint16_t); /* Data length */ uint16_t *newData = (uint16_t *)BSL_SAL_Calloc(1u, newDataLen); if (newData == NULL) { return HITLS_MEMALLOC_FAIL; } for (uint32_t i = 0; i < frameArray->size; i++) { newData[i] = frameArray->data[i]; } for (uint32_t i = 0; i < dataLen; i++) { newData[frameArray->size + i] = data[i]; } BSL_SAL_FREE(frameArray->data); /* Clear the old memory. */ frameArray->state = ASSIGNED_FIELD; frameArray->data = newData; frameArray->size = newDataLen / sizeof(uint16_t); /* Number of data records */ if (frameArrayLen != NULL) { frameArrayLen->state = ASSIGNED_FIELD; frameArrayLen->data = newDataLen; } return HITLS_SUCCESS; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/msg/src/frame_msg_method.c
C
unknown
14,060
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "securec.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "hitls.h" #include "tls.h" #include "hs_ctx.h" #include "frame_msg.h" #include "hs_extensions.h" #define TLS_RECORD_HEADER_LEN 5 #define DTLS_RECORD_HEADER_LEN 13 #define SIZE_OF_UINT24 3 #define SIZE_OF_UINT32 4 #define SIZE_OF_UINT48 6 #define ONE_TIME 1 #define TWO_TIMES 2 // Assemble 8-bit data(1 byte) static int32_t PackInteger8(const FRAME_Integer *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { uint32_t repeats = ONE_TIME; uint32_t bufOffset = 0; // No assembly required if (field->state == MISSING_FIELD) { return HITLS_SUCCESS; } // Repeated assembly if (field->state == DUPLICATE_FIELD) { repeats = TWO_TIMES; } // Not enough to assemble if (bufLen < (sizeof(uint8_t) * repeats)) { return HITLS_INTERNAL_EXCEPTION; } for (uint32_t i = 0; i < repeats; i++) { uint8_t data = (uint8_t)(field->data); buf[bufOffset] = data; bufOffset += sizeof(uint8_t); *offset += sizeof(uint8_t); } return HITLS_SUCCESS; } // Assemble 16-bit data(2 bytes) static int32_t PackInteger16(const FRAME_Integer *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { uint32_t repeats = ONE_TIME; uint32_t bufOffset = 0; // No assembly required if (field->state == MISSING_FIELD) { return HITLS_SUCCESS; } // Repeated assembly if (field->state == DUPLICATE_FIELD) { repeats = TWO_TIMES; } // Not enough to assemble if (bufLen < (sizeof(uint16_t) * repeats)) { return HITLS_INTERNAL_EXCEPTION; } if (field->state == SET_LEN_TO_ONE_BYTE) { uint8_t data = (uint8_t)field->data; buf[0] = data; *offset += sizeof(uint8_t); return HITLS_SUCCESS; } for (uint32_t i = 0; i < repeats; i++) { uint16_t data = (uint16_t)(field->data); BSL_Uint16ToByte(data, &buf[bufOffset]); bufOffset += sizeof(uint16_t); *offset += sizeof(uint16_t); } return HITLS_SUCCESS; } // Assemble 24-bit data(3 bytes) static int32_t PackInteger24(const FRAME_Integer *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { uint32_t repeats = ONE_TIME; uint32_t bufOffset = 0; // No assembly required if (field->state == MISSING_FIELD) { return HITLS_SUCCESS; } // Repeated assembly if (field->state == DUPLICATE_FIELD) { repeats = TWO_TIMES; } // Not enough to assemble if (bufLen < (SIZE_OF_UINT24 * repeats)) { return HITLS_INTERNAL_EXCEPTION; } if (field->state == SET_LEN_TO_ONE_BYTE) { uint8_t data = (uint8_t)field->data; buf[0] = data; *offset += sizeof(uint8_t); return HITLS_SUCCESS; } for (uint32_t i = 0; i < repeats; i++) { uint32_t data = (uint32_t)field->data; BSL_Uint24ToByte(data, &buf[bufOffset]); bufOffset += SIZE_OF_UINT24; *offset += SIZE_OF_UINT24; } return HITLS_SUCCESS; } // Assemble 32-bit data(8 bytes) static int32_t PackInteger32(const FRAME_Integer *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { uint32_t repeats = ONE_TIME; uint32_t bufOffset = 0; // No assembly required if (field->state == MISSING_FIELD) { return HITLS_SUCCESS; } // Repeated assembly if (field->state == DUPLICATE_FIELD) { repeats = TWO_TIMES; } // Not enough to assemble if (bufLen < (SIZE_OF_UINT32 * repeats)) { return HITLS_INTERNAL_EXCEPTION; } if (field->state == SET_LEN_TO_ONE_BYTE) { uint8_t data = (uint8_t)field->data; buf[0] = data; *offset += sizeof(uint8_t); return HITLS_SUCCESS; } for (uint32_t i = 0; i < repeats; i++) { uint32_t data = (uint32_t)field->data; BSL_Uint32ToByte(data, &buf[bufOffset]); bufOffset += SIZE_OF_UINT32; *offset += SIZE_OF_UINT32; } return HITLS_SUCCESS; } // Assemble 48-bit data(8 bytes) static int32_t PackInteger48(const FRAME_Integer *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { uint32_t repeats = ONE_TIME; uint32_t bufOffset = 0; // No assembly required if (field->state == MISSING_FIELD) { return HITLS_SUCCESS; } // Repeated assembly if (field->state == DUPLICATE_FIELD) { repeats = TWO_TIMES; } // Not enough to assemble if (bufLen < (SIZE_OF_UINT48 * repeats)) { return HITLS_INTERNAL_EXCEPTION; } if (field->state == SET_LEN_TO_ONE_BYTE) { uint8_t data = (uint8_t)field->data; buf[0] = data; *offset += sizeof(uint8_t); return HITLS_SUCCESS; } for (uint32_t i = 0; i < repeats; i++) { uint64_t data = (uint64_t)field->data; BSL_Uint48ToByte(data, &buf[bufOffset]); bufOffset += SIZE_OF_UINT48; *offset += SIZE_OF_UINT48; } return HITLS_SUCCESS; } // Assembles the buffer of 8-bit data.(1 byte * n) static int32_t PackArray8(const FRAME_Array8 *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { // No assembly required if (field->state == MISSING_FIELD) { return HITLS_SUCCESS; } // Total length to be assembled uint32_t length = field->size; // Not enough to assemble if (bufLen < length) { return HITLS_INTERNAL_EXCEPTION; } if (memcpy_s(buf, bufLen, field->data, field->size) != EOK) { return HITLS_MEMCPY_FAIL; } *offset += length; return HITLS_SUCCESS; } // Assemble the buffer of 16-bit data.(2 bytes * n) static int32_t PackArray16(const FRAME_Array16 *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { // No assembly required if (field->state == MISSING_FIELD) { return HITLS_SUCCESS; } // Total length to be assembled uint32_t length = field->size * sizeof(uint16_t); // Not enough to assemble if (bufLen < length) { return HITLS_INTERNAL_EXCEPTION; } uint32_t bufoffset = 0; for (uint32_t i = 0; i < field->size; i++) { BSL_Uint16ToByte(field->data[i], &buf[bufoffset]); bufoffset += sizeof(uint16_t); } *offset += length; return HITLS_SUCCESS; } static int32_t PackHsExtArray8(const FRAME_HsExtArray8 *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { uint32_t repeats = ONE_TIME; // This extension does not need to be assembled. if (field->exState == MISSING_FIELD) { return HITLS_SUCCESS; } // Currently, duplicate extension types can be assembled. Only one extension type can be assembled. if (field->exState == DUPLICATE_FIELD) { repeats = TWO_TIMES; } // Calculate the total length to be assembled uint32_t length = 0; length += ((field->exType.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->exLen.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->exDataLen.state == MISSING_FIELD) ? 0 : sizeof(uint8_t)); length += ((field->exData.state == MISSING_FIELD) ? 0 : sizeof(uint8_t) * field->exData.size); length *= repeats; // Not enough to assemble if (bufLen < length) { return HITLS_INTERNAL_EXCEPTION; } // Assembly extension type. Duplicate extensions exist. Currently, assembly is performed twice consecutively. uint32_t bufoffset = 0; uint32_t tmpOffset; for (uint32_t i = 0; i < repeats; i++) { PackInteger16(&field->exType, &buf[bufoffset], bufLen - bufoffset, &bufoffset); tmpOffset = bufoffset; PackInteger16(&field->exLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackInteger8(&field->exDataLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackArray8(&field->exData, &buf[bufoffset], bufLen - bufoffset, &bufoffset); if (field->exLen.state == INITIAL_FIELD) { uint32_t len = bufoffset - sizeof(uint16_t) - tmpOffset; BSL_Uint16ToByte(len, &buf[tmpOffset]); } } *offset += bufoffset; return HITLS_SUCCESS; } static int32_t PackHsExtArrayForList(const FRAME_HsExtArray8 *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { uint32_t repeats = ONE_TIME; // This extension does not need to be assembled. if (field->exState == MISSING_FIELD) { return HITLS_SUCCESS; } // Currently, duplicate extension types can be assembled. Only one extension type can be assembled. if (field->exState == DUPLICATE_FIELD) { repeats = TWO_TIMES; } // Calculate the total length to be assembled uint32_t length = 0; length += ((field->exType.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->exLen.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->exDataLen.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->exData.state == MISSING_FIELD) ? 0 : sizeof(uint8_t) * field->exData.size); length *= repeats; // Not enough to assemble if (bufLen < length) { return HITLS_INTERNAL_EXCEPTION; } // Assembly extension type. Duplicate extensions exist. Currently, assembly is performed twice consecutively. uint32_t bufoffset = 0; uint32_t tmpOffset; for (uint32_t i = 0; i < repeats; i++) { PackInteger16(&field->exType, &buf[bufoffset], bufLen - bufoffset, &bufoffset); tmpOffset = bufoffset; PackInteger16(&field->exLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackInteger16(&field->exDataLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackArray8(&field->exData, &buf[bufoffset], bufLen - bufoffset, &bufoffset); if (field->exLen.state == INITIAL_FIELD) { uint32_t len = bufoffset - sizeof(uint16_t) - tmpOffset; BSL_Uint16ToByte(len, &buf[tmpOffset]); } } *offset += bufoffset; return HITLS_SUCCESS; } static int32_t PackHsExtArrayForTicket(const FRAME_HsExtArray8 *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { uint32_t repeats = ONE_TIME; // This extension does not need to be assembled. if (field->exState == MISSING_FIELD) { return HITLS_SUCCESS; } // Currently, duplicate extension types can be assembled. Only one extension type can be assembled. if (field->exState == DUPLICATE_FIELD) { repeats = TWO_TIMES; } // Calculate the total length to be assembled uint32_t length = 0; length += ((field->exType.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->exDataLen.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->exData.state == MISSING_FIELD) ? 0 : sizeof(uint8_t) * field->exData.size); length *= repeats; // Not enough to assemble if (bufLen < length) { return HITLS_INTERNAL_EXCEPTION; } // Assembly extension type. Duplicate extensions exist. Currently, assembly is performed twice consecutively. uint32_t bufoffset = 0; uint32_t tmpOffset; for (uint32_t i = 0; i < repeats; i++) { PackInteger16(&field->exType, &buf[bufoffset], bufLen - bufoffset, &bufoffset); tmpOffset = bufoffset; PackInteger16(&field->exDataLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackArray8(&field->exData, &buf[bufoffset], bufLen - bufoffset, &bufoffset); if (field->exDataLen.state == INITIAL_FIELD) { uint32_t len = bufoffset - sizeof(uint16_t) - tmpOffset; BSL_Uint16ToByte(len, &buf[tmpOffset]); } } *offset += bufoffset; return HITLS_SUCCESS; } static int32_t PackHsExtArray16(const FRAME_HsExtArray16 *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { uint32_t repeats = ONE_TIME; // This extension does not need to be assembled. if (field->exState == MISSING_FIELD) { return HITLS_SUCCESS; } // Currently, duplicate extension types can be assembled. Only one extension type can be assembled. if (field->exState == DUPLICATE_FIELD) { repeats = TWO_TIMES; } // Calculate the total length to be assembled uint32_t length = 0; length += ((field->exType.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->exLen.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->exDataLen.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->exData.state == MISSING_FIELD) ? 0 : sizeof(uint16_t) * field->exData.size); length *= repeats; // Not enough to assemble if (bufLen < length) { return HITLS_INTERNAL_EXCEPTION; } // Assembly extension type. Duplicate extensions exist. Currently, assembly is performed twice consecutively. uint32_t bufoffset = 0; uint32_t tmpOffset; for (uint32_t i = 0; i < repeats; i++) { PackInteger16(&field->exType, &buf[bufoffset], bufLen - bufoffset, &bufoffset); tmpOffset = bufoffset; PackInteger16(&field->exLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackInteger16(&field->exDataLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackArray16(&field->exData, &buf[bufoffset], bufLen - bufoffset, &bufoffset); if (field->exLen.state == INITIAL_FIELD) { uint32_t len = bufoffset - sizeof(uint16_t) - tmpOffset; BSL_Uint16ToByte(len, &buf[tmpOffset]); } } *offset += bufoffset; return HITLS_SUCCESS; } static int32_t PackPskIdentity(const FRAME_HsArrayPskIdentity *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { // This extension does not need to be assembled. if (field->state == MISSING_FIELD) { return HITLS_SUCCESS; } // Duplicate identity arrays are meaningless. The configuration value can be duplicated. uint32_t bufoffset = 0; uint32_t tmpOffset = 0; for (uint32_t j = 0; j < field->size; j++) { uint32_t innerRepeat = ONE_TIME; if (field->data[j].state == MISSING_FIELD) { continue; } if (field->data[j].state == DUPLICATE_FIELD) { innerRepeat = TWO_TIMES; } for (uint32_t k = 0; k < innerRepeat; k++) { tmpOffset = bufoffset; PackInteger16(&field->data[j].identityLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackArray8(&field->data[j].identity, &buf[bufoffset], bufLen - bufoffset, &bufoffset); if (field->data[j].identityLen.state == INITIAL_FIELD) { BSL_Uint16ToByte(field->data[j].identity.size, &buf[tmpOffset]); } PackInteger32(&field->data[j].obfuscatedTicketAge, &buf[bufoffset], bufLen - bufoffset, &bufoffset); } } *offset += bufoffset; return HITLS_SUCCESS; } static int32_t PackPskBinder(const FRAME_HsArrayPskBinder *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { // This extension does not need to be assembled. if (field->state == MISSING_FIELD) { return HITLS_SUCCESS; } // Duplicate identity arrays are meaningless. The configuration value can be duplicated. uint32_t bufoffset = 0; uint32_t tmpOffset = 0; for (uint32_t j = 0; j < field->size; j++) { uint32_t innerRepeat = ONE_TIME; if (field->data[j].state == MISSING_FIELD) { continue; } if (field->data[j].state == DUPLICATE_FIELD) { innerRepeat = TWO_TIMES; } for (uint32_t k = 0; k < innerRepeat; k++) { tmpOffset = bufoffset; PackInteger8(&field->data[j].binderLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackArray8(&field->data[j].binder, &buf[bufoffset], bufLen - bufoffset, &bufoffset); if (field->data[j].binderLen.state == INITIAL_FIELD) { buf[tmpOffset] = field->data[j].binder.size; } } } *offset += bufoffset; return HITLS_SUCCESS; } static int32_t PackHsExtCaList(const FRAME_HsExtCaList *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { if (field->exState == MISSING_FIELD) { return HITLS_SUCCESS; } // Calculate the total length to be assembled uint32_t length = 0; length += ((field->exType.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->exLen.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->listSize.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->list.state == MISSING_FIELD) ? 0 : sizeof(uint8_t) * field->list.size); if (bufLen < length) { return HITLS_INTERNAL_EXCEPTION; } uint32_t bufoffset = 0; uint32_t tmpOffset = 0; PackInteger16(&field->exType, &buf[bufoffset], bufLen - bufoffset, &bufoffset); tmpOffset = bufoffset; PackInteger16(&field->exLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackInteger16(&field->listSize, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackArray8(&field->list, &buf[bufoffset], bufLen - bufoffset, &bufoffset); if (field->exLen.state == INITIAL_FIELD) { uint32_t len = bufoffset - sizeof(uint16_t) - tmpOffset; BSL_Uint16ToByte(len, &buf[tmpOffset]); } *offset += bufoffset; return HITLS_SUCCESS; } static int32_t PackHsExtOfferedPsks(const FRAME_HsExtOfferedPsks *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { uint32_t repeats = ONE_TIME; // This extension does not need to be assembled. if (field->exState == MISSING_FIELD) { return HITLS_SUCCESS; } // Currently, duplicate extension types can be assembled. Only one extension type can be assembled. if (field->exState == DUPLICATE_FIELD) { repeats = TWO_TIMES; } // Calculate the total length to be assembled uint32_t length = 0; length += ((field->exType.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->exLen.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += field->exLen.data; length *= repeats; // Not enough to assemble if (bufLen < length) { return HITLS_INTERNAL_EXCEPTION; } uint32_t bufoffset = 0; uint32_t tmpOffset = 0; for (uint32_t i = 0; i < repeats; i++) { PackInteger16(&field->exType, &buf[bufoffset], bufLen - bufoffset, &bufoffset); tmpOffset = bufoffset; PackInteger16(&field->exLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackInteger16(&field->identitySize, &buf[bufoffset], bufLen - bufoffset, &bufoffset); // identity len INITIAL_FIELD Not supported currently PackPskIdentity(&field->identities, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackInteger16(&field->binderSize, &buf[bufoffset], bufLen - bufoffset, &bufoffset); // binder len INITIAL_FIELD Not supported currently PackPskBinder(&field->binders, &buf[bufoffset], bufLen - bufoffset, &bufoffset); if (field->exLen.state == INITIAL_FIELD) { uint32_t len = bufoffset - sizeof(uint16_t) - tmpOffset; BSL_Uint16ToByte(len, &buf[tmpOffset]); } } *offset += bufoffset; return HITLS_SUCCESS; } static int32_t PackKeyShareArray(const FRAME_HsArrayKeyShare *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { // This extension does not need to be assembled. if (field->state == MISSING_FIELD) { return HITLS_SUCCESS; } // Duplicate key share arrays are meaningless. The configuration value can be duplicated. uint32_t bufoffset = 0; uint32_t tmpOffset = 0; for (uint32_t j = 0; j < field->size; j++) { uint32_t innerRepeat = ONE_TIME; if (field->data[j].state == MISSING_FIELD) { continue; } if (field->data[j].state == DUPLICATE_FIELD) { innerRepeat = TWO_TIMES; } for (uint32_t k = 0; k < innerRepeat; k++) { PackInteger16(&field->data[j].group, &buf[bufoffset], bufLen - bufoffset, &bufoffset); tmpOffset = bufoffset; PackInteger16(&field->data[j].keyExchangeLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackArray8(&field->data[j].keyExchange, &buf[bufoffset], bufLen - bufoffset, &bufoffset); if (field->data[j].keyExchangeLen.state == INITIAL_FIELD) { BSL_Uint16ToByte(field->data[j].keyExchange.size, &buf[tmpOffset]); } } } *offset += bufoffset; return HITLS_SUCCESS; } static int32_t PackHsExtKeyShare(const FRAME_HsExtKeyShare *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { uint32_t repeats = ONE_TIME; // This extension does not need to be assembled. if (field->exState == MISSING_FIELD) { return HITLS_SUCCESS; } // Currently, duplicate extension types can be assembled. Only one extension type can be assembled. if (field->exState == DUPLICATE_FIELD) { repeats = TWO_TIMES; } // Calculate the total length to be assembled uint32_t length = 0; length += ((field->exType.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->exLen.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += field->exLen.data; length *= repeats; // Not enough to assemble if (bufLen < length) { return HITLS_INTERNAL_EXCEPTION; } uint32_t bufoffset = 0; uint32_t tmpOffset = 0; for (uint32_t i = 0; i < repeats; i++) { PackInteger16(&field->exType, &buf[bufoffset], bufLen - bufoffset, &bufoffset); tmpOffset = bufoffset; PackInteger16(&field->exLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackInteger16(&field->exKeyShareLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); // exKeyShareLen INITIAL_FIELD Not supported currently PackKeyShareArray(&field->exKeyShares, &buf[bufoffset], bufLen - bufoffset, &bufoffset); if (field->exLen.state == INITIAL_FIELD) { uint32_t len = bufoffset - sizeof(uint16_t) - tmpOffset; BSL_Uint16ToByte(len, &buf[tmpOffset]); } } *offset += bufoffset; return HITLS_SUCCESS; } static int32_t PackHsExtSupportedVersion(const FRAME_HsExtArray16 *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { uint32_t repeats = ONE_TIME; // This extension does not need to be assembled. if (field->exState == MISSING_FIELD) { return HITLS_SUCCESS; } // Currently, duplicate extension types can be assembled. Only one extension type can be assembled. if (field->exState == DUPLICATE_FIELD) { repeats = TWO_TIMES; } // Calculate the total length to be assembled uint32_t length = 0; length += ((field->exType.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->exLen.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->exDataLen.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->exData.state == MISSING_FIELD) ? 0 : sizeof(uint16_t) * field->exData.size); length *= repeats; // Not enough to assemble if (bufLen < length) { return HITLS_INTERNAL_EXCEPTION; } // Assembly extension type. Duplicate extensions exist. Currently, assembly is performed twice consecutively. uint32_t bufoffset = 0; uint32_t tmpOffset; for (uint32_t i = 0; i < repeats; i++) { PackInteger16(&field->exType, &buf[bufoffset], bufLen - bufoffset, &bufoffset); tmpOffset = bufoffset; PackInteger16(&field->exLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackInteger8(&field->exDataLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackArray16(&field->exData, &buf[bufoffset], bufLen - bufoffset, &bufoffset); if (field->exLen.state == INITIAL_FIELD) { uint32_t len = bufoffset - sizeof(uint16_t) - tmpOffset; BSL_Uint16ToByte(len, &buf[tmpOffset]); } } *offset += bufoffset; return HITLS_SUCCESS; } static int32_t PackClientHelloMsg(const FRAME_ClientHelloMsg *clientHello, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { uint32_t offset = 0; uint32_t bufOffset; PackInteger16(&clientHello->version, &buf[offset], bufLen, &offset); PackArray8(&clientHello->randomValue, &buf[offset], bufLen - offset, &offset); PackInteger8(&clientHello->sessionIdSize, &buf[offset], bufLen - offset, &offset); PackArray8(&clientHello->sessionId, &buf[offset], bufLen - offset, &offset); PackInteger8(&clientHello->cookiedLen, &buf[offset], bufLen - offset, &offset); PackArray8(&clientHello->cookie, &buf[offset], bufLen - offset, &offset); PackInteger16(&clientHello->cipherSuitesSize, &buf[offset], bufLen - offset, &offset); PackArray16(&clientHello->cipherSuites, &buf[offset], bufLen - offset, &offset); PackInteger8(&clientHello->compressionMethodsLen, &buf[offset], bufLen - offset, &offset); PackArray8(&clientHello->compressionMethods, &buf[offset], bufLen - offset, &offset); bufOffset = offset; if (clientHello->extensionState != MISSING_FIELD) { PackInteger16(&clientHello->extensionLen, &buf[offset], bufLen - offset, &offset); if (clientHello->extensionLen.state == SET_LEN_TO_ONE_BYTE) { goto EXIT; } PackHsExtArrayForList(&clientHello->serverName, &buf[offset], bufLen - offset, &offset); PackHsExtArray16(&clientHello->signatureAlgorithms, &buf[offset], bufLen - offset, &offset); PackHsExtArray16(&clientHello->supportedGroups, &buf[offset], bufLen - offset, &offset); PackHsExtArray8(&clientHello->pointFormats, &buf[offset], bufLen - offset, &offset); PackHsExtSupportedVersion(&clientHello->supportedVersion, &buf[offset], bufLen - offset, &offset); PackHsExtArrayForList(&clientHello->tls13Cookie, &buf[offset], bufLen - offset, &offset); PackHsExtArray8(&clientHello->extendedMasterSecret, &buf[offset], bufLen - offset, &offset); PackHsExtArrayForList(&clientHello->alpn, &buf[offset], bufLen - offset, &offset); PackHsExtArray8(&clientHello->pskModes, &buf[offset], bufLen - offset, &offset); PackHsExtKeyShare(&clientHello->keyshares, &buf[offset], bufLen - offset, &offset); PackHsExtArray8(&clientHello->secRenego, &buf[offset], bufLen - offset, &offset); PackHsExtArrayForTicket(&clientHello->sessionTicket, &buf[offset], bufLen - offset, &offset); PackHsExtArray8(&clientHello->encryptThenMac, &buf[offset], bufLen - offset, &offset); PackHsExtOfferedPsks(&clientHello->psks, &buf[offset], bufLen - offset, &offset); PackHsExtCaList(&clientHello->caList, &buf[offset], bufLen - offset, &offset); if (clientHello->extensionLen.state == INITIAL_FIELD) { uint32_t extensionLen = offset - sizeof(uint16_t) - bufOffset; BSL_Uint16ToByte(extensionLen, &buf[bufOffset]); } } EXIT: *usedLen = offset; return HITLS_SUCCESS; } static int32_t PackHsExtUint16(const FRAME_HsExtUint16 *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { uint32_t repeats = ONE_TIME; // This extension does not need to be assembled. if (field->exState == MISSING_FIELD) { return HITLS_SUCCESS; } // Currently, duplicate extension types can be assembled. Only one extension type can be assembled. if (field->exState == DUPLICATE_FIELD) { repeats = TWO_TIMES; } // Calculate the total length to be assembled uint32_t length = 0; length += ((field->exType.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->exLen.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += field->exLen.data; length *= repeats; // Not enough to assemble if (bufLen < length) { return HITLS_INTERNAL_EXCEPTION; } // Assembly extension type. Duplicate extensions exist. Currently, assembly is performed twice consecutively. uint32_t bufoffset = 0; uint32_t tmpOffset; for (uint32_t i = 0; i < repeats; i++) { PackInteger16(&field->exType, &buf[bufoffset], bufLen - bufoffset, &bufoffset); tmpOffset = bufoffset; PackInteger16(&field->exLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackInteger16(&field->data, &buf[bufoffset], bufLen - bufoffset, &bufoffset); if (field->exLen.state == INITIAL_FIELD) { uint32_t len = bufoffset - sizeof(uint16_t) - tmpOffset; BSL_Uint16ToByte(len, &buf[tmpOffset]); } } *offset += bufoffset; return HITLS_SUCCESS; } static int32_t PackHsExtServerKeyShare( const FRAME_HsExtServerKeyShare *field, uint8_t *buf, uint32_t bufLen, uint32_t *offset) { uint32_t repeats = ONE_TIME; // This extension does not need to be assembled. if (field->exState == MISSING_FIELD) { return HITLS_SUCCESS; } // Currently, duplicate extension types can be assembled. Only one extension type can be assembled. if (field->exState == DUPLICATE_FIELD) { repeats = TWO_TIMES; } // Calculate the total length to be assembled uint32_t length = 0; length += ((field->exType.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += ((field->exLen.state == MISSING_FIELD) ? 0 : sizeof(uint16_t)); length += field->exLen.data; length *= repeats; // Not enough to assemble if (bufLen < length) { return HITLS_INTERNAL_EXCEPTION; } // Assembly extension type. Duplicate extensions exist. Currently, assembly is performed twice consecutively. uint32_t bufoffset = 0; uint32_t tmpOffset; for (uint32_t i = 0; i < repeats; i++) { PackInteger16(&field->exType, &buf[bufoffset], bufLen - bufoffset, &bufoffset); tmpOffset = bufoffset; PackInteger16(&field->exLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackInteger16(&field->data.group, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackInteger16(&field->data.keyExchangeLen, &buf[bufoffset], bufLen - bufoffset, &bufoffset); PackArray8(&field->data.keyExchange, &buf[bufoffset], bufLen - bufoffset, &bufoffset); if (field->exLen.state == INITIAL_FIELD) { uint32_t len = bufoffset - sizeof(uint16_t) - tmpOffset; BSL_Uint16ToByte(len, &buf[tmpOffset]); } } *offset += bufoffset; return HITLS_SUCCESS; } static int32_t PackServerHelloMsg(const FRAME_ServerHelloMsg *serverHello, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { uint32_t offset = 0; uint32_t bufOffset; PackInteger16(&serverHello->version, &buf[offset], bufLen, &offset); PackArray8(&serverHello->randomValue, &buf[offset], bufLen - offset, &offset); PackInteger8(&serverHello->sessionIdSize, &buf[offset], bufLen - offset, &offset); PackArray8(&serverHello->sessionId, &buf[offset], bufLen - offset, &offset); PackInteger16(&serverHello->cipherSuite, &buf[offset], bufLen - offset, &offset); PackInteger8(&serverHello->compressionMethod, &buf[offset], bufLen - offset, &offset); bufOffset = offset; PackInteger16(&serverHello->extensionLen, &buf[offset], bufLen - offset, &offset); PackHsExtArrayForList(&serverHello->serverName, &buf[offset], bufLen - offset, &offset); PackHsExtArrayForList(&serverHello->tls13Cookie, &buf[offset], bufLen - offset, &offset); PackHsExtArrayForTicket(&serverHello->sessionTicket, &buf[offset], bufLen - offset, &offset); PackHsExtUint16(&serverHello->supportedVersion, &buf[offset], bufLen - offset, &offset); PackHsExtArray8(&serverHello->extendedMasterSecret, &buf[offset], bufLen - offset, &offset); PackHsExtArrayForList(&serverHello->alpn, &buf[offset], bufLen - offset, &offset); PackHsExtServerKeyShare(&serverHello->keyShare, &buf[offset], bufLen - offset, &offset); // hello retry request key share PackHsExtArray8(&serverHello->secRenego, &buf[offset], bufLen - offset, &offset); PackHsExtArray8(&serverHello->pointFormats, &buf[offset], bufLen - offset, &offset); PackHsExtUint16(&serverHello->pskSelectedIdentity, &buf[offset], bufLen - offset, &offset); // encrypt then mac PackHsExtArray8(&serverHello->encryptThenMac, &buf[offset], bufLen - offset, &offset); if (serverHello->extensionLen.state == INITIAL_FIELD) { uint32_t extensionLen = offset - sizeof(uint16_t) - bufOffset; BSL_Uint16ToByte(extensionLen, &buf[bufOffset]); } *usedLen = offset; return HITLS_SUCCESS; } static int32_t PackCertificateMsg(FRAME_Type *type, const FRAME_CertificateMsg *certificate, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { uint32_t offset = 0; uint32_t bufOffset; if (type->versionType == HITLS_VERSION_TLS13) { PackInteger8(&certificate->certificateReqCtxSize, &buf[offset], bufLen - offset, &offset); PackArray8(&certificate->certificateReqCtx, &buf[offset], bufLen - offset, &offset); } bufOffset = offset; PackInteger24(&certificate->certsLen, &buf[offset], bufLen - offset, &offset); const FrameCertItem *next = certificate->certItem; while (next != NULL) { if (next->state == MISSING_FIELD) { break; } PackInteger24(&next->certLen, &buf[offset], bufLen - offset, &offset); PackArray8(&next->cert, &buf[offset], bufLen - offset, &offset); if (type->versionType == HITLS_VERSION_TLS13) { PackInteger16(&next->extensionLen, &buf[offset], bufLen - offset, &offset); PackArray8(&next->extension, &buf[offset], bufLen - offset, &offset); } next = next->next; } if (certificate->certsLen.state == INITIAL_FIELD) { uint32_t certsLen = offset - SIZE_OF_UINT24 - bufOffset; BSL_Uint24ToByte(certsLen, &buf[bufOffset]); } *usedLen = offset; return HITLS_SUCCESS; } static int32_t PackServerEcdheMsg(FRAME_Type *type, const FRAME_ServerKeyExchangeMsg *serverKeyExchange, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { uint32_t offset = 0; // Fill in the following values in sequence: curve type, curve ID, pubkeylen, pubkey value, signature algorithm, // signature len, and signature value. PackInteger8(&serverKeyExchange->keyEx.ecdh.curveType, &buf[offset], bufLen, &offset); PackInteger16(&serverKeyExchange->keyEx.ecdh.namedcurve, &buf[offset], bufLen - offset, &offset); PackInteger8(&serverKeyExchange->keyEx.ecdh.pubKeySize, &buf[offset], bufLen- offset, &offset); PackArray8(&serverKeyExchange->keyEx.ecdh.pubKey, &buf[offset], bufLen- offset, &offset); if (((IS_DTLS_VERSION(type->versionType)) && (type->versionType <= HITLS_VERSION_DTLS12)) || ((!IS_DTLS_VERSION(type->versionType)) && (type->versionType >= HITLS_VERSION_TLS12))) { // DTLS1.2, TLS1.2, and later versions PackInteger16(&serverKeyExchange->keyEx.ecdh.signAlgorithm, &buf[offset], bufLen- offset, &offset); } PackInteger16(&serverKeyExchange->keyEx.ecdh.signSize, &buf[offset], bufLen- offset, &offset); PackArray8(&serverKeyExchange->keyEx.ecdh.signData, &buf[offset], bufLen- offset, &offset); *usedLen = offset; return HITLS_SUCCESS; } static int32_t PackServerDheMsg(FRAME_Type *type, const FRAME_ServerKeyExchangeMsg *serverKeyExchange, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { uint32_t offset = 0; // Fill in the following values in sequence: plen, p value, glen, g value, pubkeylen, pubkey value, // signature algorithm, signature len, and signature value. PackInteger16(&serverKeyExchange->keyEx.dh.plen, &buf[offset], bufLen, &offset); PackArray8(&serverKeyExchange->keyEx.dh.p, &buf[offset], bufLen - offset, &offset); PackInteger16(&serverKeyExchange->keyEx.dh.glen, &buf[offset], bufLen - offset, &offset); PackArray8(&serverKeyExchange->keyEx.dh.g, &buf[offset], bufLen - offset, &offset); PackInteger16(&serverKeyExchange->keyEx.dh.pubKeyLen, &buf[offset], bufLen- offset, &offset); PackArray8(&serverKeyExchange->keyEx.dh.pubKey, &buf[offset], bufLen- offset, &offset); if (((IS_DTLS_VERSION(type->versionType)) && (type->versionType <= HITLS_VERSION_DTLS12)) || ((!IS_DTLS_VERSION(type->versionType)) && (type->versionType >= HITLS_VERSION_TLS12))) { // DTLS1.2, TLS1.2, and later versions PackInteger16(&serverKeyExchange->keyEx.dh.signAlgorithm, &buf[offset], bufLen- offset, &offset); } PackInteger16(&serverKeyExchange->keyEx.dh.signSize, &buf[offset], bufLen- offset, &offset); PackArray8(&serverKeyExchange->keyEx.dh.signData, &buf[offset], bufLen- offset, &offset); *usedLen = offset; return HITLS_SUCCESS; } static int32_t PackServerEccMsg(const FRAME_ServerKeyExchangeMsg *serverKeyExchange, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { uint32_t offset = 0; PackInteger16(&serverKeyExchange->keyEx.ecdh.signSize, &buf[offset], bufLen- offset, &offset); PackArray8(&serverKeyExchange->keyEx.ecdh.signData, &buf[offset], bufLen- offset, &offset); *usedLen = offset; return HITLS_SUCCESS; } static int32_t PackServerKeyExchangeMsg(FRAME_Type *type, const FRAME_ServerKeyExchangeMsg *serverKeyExchange, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { // Currently, ECDHE and DHE key exchange packets can be assembled. if (type->keyExType == HITLS_KEY_EXCH_ECDHE) { return PackServerEcdheMsg(type, serverKeyExchange, buf, bufLen, usedLen); } else if (type->keyExType == HITLS_KEY_EXCH_DHE) { return PackServerDheMsg(type, serverKeyExchange, buf, bufLen, usedLen); } else if (type->keyExType == HITLS_KEY_EXCH_ECC) { return PackServerEccMsg(serverKeyExchange, buf, bufLen, usedLen); } return HITLS_PACK_UNSUPPORT_KX_ALG; } static int32_t PackCertificateRequestExt(uint32_t type, const FRAME_CertificateRequestMsg *certificateRequest, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { uint32_t offset = 0; FRAME_Integer exType; FRAME_Integer size; switch (type) { case HS_EX_TYPE_SIGNATURE_ALGORITHMS: exType.data = HS_EX_TYPE_SIGNATURE_ALGORITHMS; exType.state = INITIAL_FIELD; PackInteger16(&exType, &buf[offset], bufLen, &offset); size.data = certificateRequest->signatureAlgorithmsSize.data + sizeof(uint16_t); size.state = INITIAL_FIELD; PackInteger16(&size, &buf[offset], bufLen, &offset); PackInteger16(&certificateRequest->signatureAlgorithmsSize, &buf[offset], bufLen, &offset); PackArray16(&certificateRequest->signatureAlgorithms, &buf[offset], bufLen - offset, &offset); break; default: break; } *usedLen += offset; return HITLS_SUCCESS; } static int32_t PackCertificateRequestMsg(FRAME_Type *type, const FRAME_CertificateRequestMsg *certificateRequest, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { uint32_t offset = 0; if (certificateRequest->state == MISSING_FIELD){ return HITLS_SUCCESS; } if (type->versionType != HITLS_VERSION_TLS13) { PackInteger8(&certificateRequest->certTypesSize, &buf[offset], bufLen, &offset); PackArray8(&certificateRequest->certTypes, &buf[offset], bufLen - offset, &offset); PackInteger16(&certificateRequest->signatureAlgorithmsSize, &buf[offset], bufLen, &offset); PackArray16(&certificateRequest->signatureAlgorithms, &buf[offset], bufLen - offset, &offset); PackInteger16(&certificateRequest->distinguishedNamesSize, &buf[offset], bufLen, &offset); PackArray8(&certificateRequest->distinguishedNames, &buf[offset], bufLen - offset, &offset); } else { PackInteger8(&certificateRequest->certificateReqCtxSize, &buf[offset], bufLen, &offset); PackArray8(&certificateRequest->certificateReqCtx, &buf[offset], bufLen - offset, &offset); // Packaged extension uint32_t tmpOffset = offset; PackInteger16(&certificateRequest->exMsgLen, &buf[offset], bufLen, &offset); bool ifPackSign = (certificateRequest->signatureAlgorithmsSize.state != MISSING_FIELD); // Package HS_EX_TYPE_SIGNATURE_ALGORITHMS Extensions if(ifPackSign) { PackCertificateRequestExt(HS_EX_TYPE_SIGNATURE_ALGORITHMS, certificateRequest, &buf[offset], bufLen - offset, &offset); } if(certificateRequest->signatureAlgorithmsSize.state == DUPLICATE_FIELD) { PackCertificateRequestExt(HS_EX_TYPE_SIGNATURE_ALGORITHMS, certificateRequest, &buf[offset], bufLen - offset, &offset); } if (certificateRequest->exMsgLen.state == INITIAL_FIELD) { uint32_t len = offset - sizeof(uint16_t) - tmpOffset; BSL_Uint16ToByte(len, &buf[tmpOffset]); } } *usedLen = offset; return HITLS_SUCCESS; } static int32_t PackServerHelloDoneMsg(const FRAME_ServerHelloDoneMsg *serverHelloDone, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { uint32_t offset = 0; /* The ServerHelloDone packet is an empty packet. Extra data is assembled here to construct abnormal packets. */ PackArray8(&serverHelloDone->extra, &buf[offset], bufLen, &offset); *usedLen = offset; return HITLS_SUCCESS; } static int32_t PackClientEcdheMsg(FRAME_Type *type, const FRAME_ClientKeyExchangeMsg *clientKeyExchange, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { uint32_t offset = 0; if (type->versionType == HITLS_VERSION_TLCP_DTLCP11) { /* Three bytes are added to the client key exchange. */ buf[offset] = HITLS_EC_CURVE_TYPE_NAMED_CURVE; offset += sizeof(uint8_t); BSL_Uint16ToByte(HITLS_EC_GROUP_SM2, &buf[offset]); offset += sizeof(uint16_t); } PackInteger8(&clientKeyExchange->pubKeySize, &buf[offset], bufLen, &offset); PackArray8(&clientKeyExchange->pubKey, &buf[offset], bufLen - offset, &offset); *usedLen = offset; return HITLS_SUCCESS; } static int32_t PackClientDheMsg(const FRAME_ClientKeyExchangeMsg *clientKeyExchange, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { uint32_t offset = 0; PackInteger16(&clientKeyExchange->pubKeySize, &buf[offset], bufLen, &offset); PackArray8(&clientKeyExchange->pubKey, &buf[offset], bufLen - offset, &offset); *usedLen = offset; return HITLS_SUCCESS; } static int32_t PackClientKeyExchangeMsg(FRAME_Type *type, const FRAME_ClientKeyExchangeMsg *clientKeyExchange, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { // Currently, ECDHE and DHE key exchange packets can be assembled. if (type->keyExType == HITLS_KEY_EXCH_ECDHE) { return PackClientEcdheMsg(type, clientKeyExchange, buf, bufLen, usedLen); } else if (type->keyExType == HITLS_KEY_EXCH_DHE || type->keyExType == HITLS_KEY_EXCH_RSA) { return PackClientDheMsg(clientKeyExchange, buf, bufLen, usedLen); } return HITLS_PACK_UNSUPPORT_KX_ALG; } static int32_t PackCertificateVerifyMsg(FRAME_Type *type, const FRAME_CertificateVerifyMsg *certificateVerify, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { uint32_t offset = 0; if (((IS_DTLS_VERSION(type->versionType)) && (type->versionType <= HITLS_VERSION_DTLS12)) || ((!IS_DTLS_VERSION(type->versionType)) && (type->versionType >= HITLS_VERSION_TLS12))) { // DTLS1.2, TLS1.2, and later versions PackInteger16(&certificateVerify->signHashAlg, &buf[offset], bufLen, &offset); } PackInteger16(&certificateVerify->signSize, &buf[offset], bufLen - offset, &offset); PackArray8(&certificateVerify->sign, &buf[offset], bufLen - offset, &offset); *usedLen = offset; return HITLS_SUCCESS; } static int32_t PackFinishedMsg(const FRAME_FinishedMsg *finished, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { uint32_t offset = 0; PackArray8(&finished->verifyData, &buf[offset], bufLen - offset, &offset); *usedLen = offset; return HITLS_SUCCESS; } static void PackHsMsgHeader(uint16_t version, const FRAME_HsMsg *hsMsg, uint32_t bodyLen, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen, BSL_UIO_TransportType transportType) { (void)version; uint32_t offset = 0; uint32_t bufOffset; PackInteger8(&hsMsg->type, &buf[offset], bufLen, &offset); bufOffset = offset; PackInteger24(&hsMsg->length, &buf[offset], bufLen - offset, &offset); if (IS_TRANSTYPE_DATAGRAM(transportType)) { PackInteger16(&hsMsg->sequence, &buf[offset], bufLen - offset, &offset); PackInteger24(&hsMsg->fragmentOffset, &buf[offset], bufLen - offset, &offset); if (hsMsg->fragmentLength.state == INITIAL_FIELD) { BSL_Uint24ToByte(bodyLen, &buf[offset]); offset += SIZE_OF_UINT24; } else { PackInteger24(&hsMsg->fragmentLength, &buf[offset], bufLen - offset, &offset); } } if (hsMsg->length.state == INITIAL_FIELD) { BSL_Uint24ToByte(bodyLen, &buf[bufOffset]); } *usedLen = offset; } static int32_t PackNewSessionTicketMsg(FRAME_Type *type, const FRAME_NewSessionTicketMsg *newSessionTicket, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { uint32_t offset = 0; PackInteger32(&newSessionTicket->ticketLifetime, &buf[offset], bufLen - offset, &offset); if (type->versionType != HITLS_VERSION_TLS13) { PackInteger16(&newSessionTicket->ticketSize, &buf[offset], bufLen - offset, &offset); PackArray8(&newSessionTicket->ticket, &buf[offset], bufLen - offset, &offset); } else { PackInteger32(&newSessionTicket->ticketAgeAdd, &buf[offset], bufLen - offset, &offset); PackInteger8(&newSessionTicket->ticketNonceSize, &buf[offset], bufLen - offset, &offset); PackArray8(&newSessionTicket->ticketNonce, &buf[offset], bufLen - offset, &offset); PackInteger16(&newSessionTicket->ticketSize, &buf[offset], bufLen - offset, &offset); PackArray8(&newSessionTicket->ticket, &buf[offset], bufLen - offset, &offset); PackInteger16(&newSessionTicket->extensionLen, &buf[offset], bufLen - offset, &offset); } *usedLen = offset; if (offset != bufLen) { return HITLS_PACK_UNSUPPORT_HANDSHAKE_MSG; } return HITLS_SUCCESS; } static int32_t PackHsMsgBody(FRAME_Type *type, const FRAME_Msg *msg, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { int32_t ret; const FRAME_HsMsg *hsMsg = &(msg->body.hsMsg); switch (type->handshakeType) { case CLIENT_HELLO: ret = PackClientHelloMsg(&(hsMsg->body.clientHello), buf, bufLen, usedLen); break; case SERVER_HELLO: ret = PackServerHelloMsg(&(hsMsg->body.serverHello), buf, bufLen, usedLen); break; case CERTIFICATE: ret = PackCertificateMsg(type, &(hsMsg->body.certificate), buf, bufLen, usedLen); break; case SERVER_KEY_EXCHANGE: ret = PackServerKeyExchangeMsg(type, &(hsMsg->body.serverKeyExchange), buf, bufLen, usedLen); break; case CERTIFICATE_REQUEST: ret = PackCertificateRequestMsg(type, &(hsMsg->body.certificateReq), buf, bufLen, usedLen); break; case SERVER_HELLO_DONE: ret = PackServerHelloDoneMsg(&(hsMsg->body.serverHelloDone), buf, bufLen, usedLen); break; case CLIENT_KEY_EXCHANGE: ret = PackClientKeyExchangeMsg(type, &(hsMsg->body.clientKeyExchange), buf, bufLen, usedLen); break; case CERTIFICATE_VERIFY: ret = PackCertificateVerifyMsg(type, &(hsMsg->body.certificateVerify), buf, bufLen, usedLen); break; case FINISHED: ret = PackFinishedMsg(&(hsMsg->body.finished), buf, bufLen, usedLen); break; case NEW_SESSION_TICKET: ret = PackNewSessionTicketMsg(type, &(hsMsg->body.newSessionTicket), buf, bufLen, usedLen); break; default: ret = HITLS_PACK_UNSUPPORT_HANDSHAKE_MSG; break; } return ret; } static int32_t PackHandShakeMsg(FRAME_Type *type, const FRAME_Msg *msg, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { const FRAME_HsMsg *hsMsg = &(msg->body.hsMsg); uint32_t ret; uint32_t offset; uint32_t bodyMaxLen; uint32_t headerLen; uint32_t bodyLen = 0; if (IS_TRANSTYPE_DATAGRAM(type->transportType)) { // DTLS if (bufLen < DTLS_HS_MSG_HEADER_SIZE) { return HITLS_INTERNAL_EXCEPTION; } bodyMaxLen = bufLen - DTLS_HS_MSG_HEADER_SIZE; offset = DTLS_HS_MSG_HEADER_SIZE; headerLen = DTLS_HS_MSG_HEADER_SIZE; } else { // TLS if (bufLen < HS_MSG_HEADER_SIZE) { return HITLS_INTERNAL_EXCEPTION; } bodyMaxLen = bufLen - HS_MSG_HEADER_SIZE; offset = HS_MSG_HEADER_SIZE; headerLen = HS_MSG_HEADER_SIZE; } // Assemble the body of the handshake message. ret = PackHsMsgBody(type, msg, &buf[offset], bodyMaxLen, &bodyLen); if (ret != HITLS_SUCCESS) { return ret; } // Assemble the handshake packet header. PackHsMsgHeader(type->versionType, hsMsg, bodyLen, buf, headerLen, &headerLen, type->transportType); // Splicing body and head // If some fields are missing in the header, the packet body is filled with an offset forward. if (headerLen != offset) { ret = memmove_s(&buf[headerLen], bufLen - headerLen, &buf[offset], bodyLen); if (ret != EOK) { return ret; } } *usedLen = headerLen + bodyLen; return ret; } static int32_t PackCcsMsg(const FRAME_Msg *msg, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { uint32_t offset = 0; PackInteger8(&msg->body.ccsMsg.ccsType, &buf[offset], bufLen, &offset); /* Extra data is used to construct abnormal packets. */ PackArray8(&msg->body.ccsMsg.extra, &buf[offset], bufLen - offset, &offset); *usedLen = offset; return HITLS_SUCCESS; } static int32_t PackAlertMsg(const FRAME_Msg *msg, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { uint32_t offset = 0; PackInteger8(&msg->body.alertMsg.alertLevel, &buf[offset], bufLen, &offset); PackInteger8(&msg->body.alertMsg.alertDescription, &buf[offset], bufLen - offset, &offset); /* Extra data is used to construct abnormal packets. */ PackArray8(&msg->body.alertMsg.extra, &buf[offset], bufLen - offset, &offset); *usedLen = offset; return HITLS_SUCCESS; } static int32_t PackAppMsg(const FRAME_Msg *msg, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { uint32_t offset = 0; PackArray8(&msg->body.appMsg.appData, &buf[offset], bufLen, &offset); *usedLen = offset; return HITLS_SUCCESS; } static int32_t PackRecordHeader(uint16_t version, const FRAME_Msg *msg, uint32_t bodyLen, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen, BSL_UIO_TransportType transportType) { (void)version; uint32_t offset = 0; PackInteger8(&msg->recType, &buf[offset], bufLen, &offset); PackInteger16(&msg->recVersion, &buf[offset], bufLen - offset, &offset); if (IS_TRANSTYPE_DATAGRAM(transportType)) { PackInteger16(&msg->epoch, &buf[offset], bufLen - offset, &offset); PackInteger48(&msg->sequence, &buf[offset], bufLen - offset, &offset); } if (msg->length.state == INITIAL_FIELD) { BSL_Uint16ToByte(bodyLen, &buf[offset]); offset += sizeof(uint16_t); } else { PackInteger16(&msg->length, &buf[offset], bufLen - offset, &offset); } *usedLen = offset; return HITLS_SUCCESS; } int32_t FRAME_PackRecordBody(FRAME_Type *frameType, const FRAME_Msg *msg, uint8_t *buffer, uint32_t bufLen, uint32_t *usedLen) { int32_t ret; // pack Body switch (frameType->recordType) { case REC_TYPE_HANDSHAKE: ret = PackHandShakeMsg(frameType, msg, buffer, bufLen, usedLen); break; case REC_TYPE_CHANGE_CIPHER_SPEC: ret = PackCcsMsg(msg, buffer, bufLen, usedLen); break; case REC_TYPE_ALERT: ret = PackAlertMsg(msg, buffer, bufLen, usedLen); break; case REC_TYPE_APP: ret = PackAppMsg(msg, buffer, bufLen, usedLen); break; default: ret = HITLS_INTERNAL_EXCEPTION; break; } return ret; } int32_t FRAME_PackMsg(FRAME_Type *frameType, const FRAME_Msg *msg, uint8_t *buffer, uint32_t bufLen, uint32_t *usedLen) { int32_t ret; uint32_t offset; uint32_t bodyMaxLen; uint32_t headerLen; uint32_t bodyLen = 0; if (msg == NULL || buffer == NULL || usedLen == NULL) { return HITLS_INTERNAL_EXCEPTION; } if (IS_TRANSTYPE_DATAGRAM(frameType->transportType)) { // DTLS if (bufLen < DTLS_RECORD_HEADER_LEN) { return HITLS_INTERNAL_EXCEPTION; } bodyMaxLen = bufLen - DTLS_RECORD_HEADER_LEN; offset = DTLS_RECORD_HEADER_LEN; headerLen = DTLS_RECORD_HEADER_LEN; } else { // TLS if (bufLen < TLS_RECORD_HEADER_LEN) { return HITLS_INTERNAL_EXCEPTION; } bodyMaxLen = bufLen - TLS_RECORD_HEADER_LEN; offset = TLS_RECORD_HEADER_LEN; headerLen = TLS_RECORD_HEADER_LEN; } // Assemble the message body. ret = FRAME_PackRecordBody(frameType, msg, &buffer[offset], bodyMaxLen, &bodyLen); if (ret != HITLS_SUCCESS) { return ret; } // Assemble the packet header. PackRecordHeader(frameType->versionType, msg, bodyLen, buffer, headerLen, &headerLen, frameType->transportType); // Splicing body and head // If some fields are missing in the header, the packet body is filled with an offset forward. if (headerLen != offset) { ret = memmove_s(&buffer[headerLen], bufLen - headerLen, &buffer[offset], bodyLen); if (ret != EOK) { return ret; } } *usedLen = headerLen + bodyLen; return ret; } int32_t FRAME_GetTls13DisorderHsMsg(HS_MsgType type, uint8_t *buffer, uint32_t bufLen, uint32_t *usedLen) { if (bufLen < 5) { return HITLS_INTERNAL_EXCEPTION; } buffer[0] = type; buffer[1] = 0; buffer[2] = 0; buffer[3] = 1; buffer[4] = 0; *usedLen = 5; return HITLS_SUCCESS; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/msg/src/frame_pack_msg.c
C
unknown
55,281
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "securec.h" #include "bsl_bytes.h" #include "bsl_sal.h" #include "hitls_error.h" #include "hitls_crypt_type.h" #include "tls.h" #include "hs_ctx.h" #include "hs_extensions.h" #include "frame_tls.h" #include "frame_msg.h" #define SIZE_OF_UINT_24 3u #define SIZE_OF_UINT_48 6u static int32_t ParseFieldInteger8(const uint8_t *buffer, uint32_t bufLen, FRAME_Integer *field, uint32_t *offset) { if (bufLen < sizeof(uint8_t)) { return HITLS_PARSE_INVALID_MSG_LEN; } field->state = INITIAL_FIELD; field->data = buffer[0]; *offset += sizeof(uint8_t); return HITLS_SUCCESS; } static int32_t ParseFieldInteger16(const uint8_t *buffer, uint32_t bufLen, FRAME_Integer *field, uint32_t *offset) { if (bufLen < sizeof(uint16_t)) { return HITLS_PARSE_INVALID_MSG_LEN; } field->state = INITIAL_FIELD; field->data = BSL_ByteToUint16(buffer); *offset += sizeof(uint16_t); return HITLS_SUCCESS; } static int32_t ParseFieldInteger24(const uint8_t *buffer, uint32_t bufLen, FRAME_Integer *field, uint32_t *offset) { if (bufLen < SIZE_OF_UINT_24) { return HITLS_PARSE_INVALID_MSG_LEN; } field->state = INITIAL_FIELD; field->data = BSL_ByteToUint24(buffer); *offset += SIZE_OF_UINT_24; return HITLS_SUCCESS; } static int32_t ParseFieldInteger32(const uint8_t *buffer, uint32_t bufLen, FRAME_Integer *field, uint32_t *offset) { if (bufLen < sizeof(uint32_t)) { return HITLS_PARSE_INVALID_MSG_LEN; } field->state = INITIAL_FIELD; field->data = BSL_ByteToUint32(buffer); *offset += sizeof(uint32_t); return HITLS_SUCCESS; } static int32_t ParseFieldInteger48(const uint8_t *buffer, uint32_t bufLen, FRAME_Integer *field, uint32_t *offset) { if (bufLen < SIZE_OF_UINT_48) { return HITLS_PARSE_INVALID_MSG_LEN; } field->state = INITIAL_FIELD; field->data = BSL_ByteToUint48(buffer); *offset += SIZE_OF_UINT_48; return HITLS_SUCCESS; } static int32_t ParseFieldArray8(const uint8_t *buffer, uint32_t bufLen, FRAME_Array8 *field, uint32_t fieldLen, uint32_t *offset) { if (bufLen < fieldLen) { return HITLS_PARSE_INVALID_MSG_LEN; } BSL_SAL_FREE(field->data); field->data = BSL_SAL_Dump(buffer, fieldLen); if (field->data == NULL) { return HITLS_MEMALLOC_FAIL; } field->size = fieldLen; field->state = INITIAL_FIELD; *offset += fieldLen; return HITLS_SUCCESS; } static int32_t ParseFieldArray16(const uint8_t *buffer, uint32_t bufLen, FRAME_Array16 *field, uint32_t fieldLen, uint32_t *offset) { if ((bufLen < fieldLen) || (fieldLen % sizeof(uint16_t) != 0)) { return HITLS_PARSE_INVALID_MSG_LEN; } field->data = BSL_SAL_Calloc(1u, fieldLen); if (field->data == NULL) { return HITLS_MEMALLOC_FAIL; } field->size = fieldLen / sizeof(uint16_t); for (uint32_t i = 0; i < field->size; i++) { field->data[i] = BSL_ByteToUint16(&buffer[i * sizeof(uint16_t)]); } field->state = INITIAL_FIELD; *offset += fieldLen; return HITLS_SUCCESS; } static int32_t ParseHsExtArray8(const uint8_t *buffer, uint32_t bufLen, FRAME_HsExtArray8 *field, uint32_t *offset) { uint32_t exOffset = 0; field->exState = INITIAL_FIELD; ParseFieldInteger16(&buffer[0], bufLen, &field->exType, &exOffset); ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->exLen, &exOffset); if (field->exLen.data == 0u) { *offset += exOffset; return HITLS_SUCCESS; } ParseFieldInteger8(&buffer[exOffset], bufLen - exOffset, &field->exDataLen, &exOffset); ParseFieldArray8(&buffer[exOffset], bufLen - exOffset, &field->exData, field->exDataLen.data, &exOffset); *offset += exOffset; return HITLS_SUCCESS; } static int32_t ParseHsExtArrayForList( const uint8_t *buffer, uint32_t bufLen, FRAME_HsExtArray8 *field, uint32_t *offset) { uint32_t exOffset = 0; field->exState = INITIAL_FIELD; ParseFieldInteger16(&buffer[0], bufLen, &field->exType, &exOffset); ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->exLen, &exOffset); if (field->exLen.data == 0u) { *offset += exOffset; return HITLS_SUCCESS; } ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->exDataLen, &exOffset); ParseFieldArray8(&buffer[exOffset], bufLen - exOffset, &field->exData, field->exDataLen.data, &exOffset); *offset += exOffset; return HITLS_SUCCESS; } static int32_t ParseHsSessionTicketExtArray8( const uint8_t *buffer, uint32_t bufLen, FRAME_HsExtArray8 *field, uint32_t *offset) { uint32_t exOffset = 0; field->exState = INITIAL_FIELD; ParseFieldInteger16(&buffer[0], bufLen, &field->exType, &exOffset); ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->exDataLen, &exOffset); if (field->exDataLen.data == 0u) { *offset += exOffset; return HITLS_SUCCESS; } ParseFieldArray8(&buffer[exOffset], bufLen - exOffset, &field->exData, field->exDataLen.data, &exOffset); *offset += exOffset; return HITLS_SUCCESS; } static int32_t ParseHsExtArray16(const uint8_t *buffer, uint32_t bufLen, FRAME_HsExtArray16 *field, uint32_t *offset) { uint32_t exOffset = 0; field->exState = INITIAL_FIELD; ParseFieldInteger16(&buffer[0], bufLen - exOffset, &field->exType, &exOffset); ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->exLen, &exOffset); if (field->exLen.data == 0u) { *offset += exOffset; return HITLS_SUCCESS; } ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->exDataLen, &exOffset); ParseFieldArray16(&buffer[exOffset], bufLen - exOffset, &field->exData, field->exDataLen.data, &exOffset); *offset += exOffset; return HITLS_SUCCESS; } static int32_t ParseHsExtPskIdentity(const uint8_t *buffer, uint32_t bufLen, FRAME_HsArrayPskIdentity *field, uint32_t fieldLen, uint32_t *offset) { uint32_t exOffset = 0; field->state = INITIAL_FIELD; uint32_t size = 0; FRAME_Integer tmpIdentityLen = { 0 }; while (exOffset < fieldLen) { ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &tmpIdentityLen, &exOffset); exOffset += (tmpIdentityLen.data + sizeof(uint32_t)); if (exOffset <= fieldLen) { size++; } } if (size == 0) { return HITLS_SUCCESS; } field->data = BSL_SAL_Calloc(size, sizeof(FRAME_HsPskIdentity)); if (field->data == NULL) { return HITLS_MEMALLOC_FAIL; } field->size = size; exOffset = 0; for (uint32_t i = 0; i < size; i++) { field->data[i].state = INITIAL_FIELD; ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->data[i].identityLen, &exOffset); ParseFieldArray8(&buffer[exOffset], bufLen - exOffset, &field->data[i].identity, field->data[i].identityLen.data, &exOffset); ParseFieldInteger32(&buffer[exOffset], bufLen - exOffset, &field->data[i].obfuscatedTicketAge, &exOffset); } *offset += exOffset; return HITLS_SUCCESS; } static int32_t ParseHsExtPskBinder(const uint8_t *buffer, uint32_t bufLen, FRAME_HsArrayPskBinder *field, uint32_t fieldLen, uint32_t *offset) { uint32_t exOffset = 0; field->state = INITIAL_FIELD; uint32_t size = 0; FRAME_Integer tmpBinderLen = { 0 }; while (exOffset < fieldLen) { ParseFieldInteger8(&buffer[exOffset], bufLen - exOffset, &tmpBinderLen, &exOffset); exOffset += tmpBinderLen.data; if (exOffset <= fieldLen) { size++; } } if (size == 0) { return HITLS_SUCCESS; } field->data = BSL_SAL_Calloc(size, sizeof(FRAME_HsPskBinder)); if (field->data == NULL) { return HITLS_MEMALLOC_FAIL; } field->size = size; exOffset = 0; for (uint32_t i = 0; i < size; i++) { field->data[i].state = INITIAL_FIELD; ParseFieldInteger8(&buffer[exOffset], bufLen - exOffset, &field->data[i].binderLen, &exOffset); ParseFieldArray8(&buffer[exOffset], bufLen - exOffset, &field->data[i].binder, field->data[i].binderLen.data, &exOffset); } *offset += exOffset; return HITLS_SUCCESS; } static int32_t ParseHsExtPsk(const uint8_t *buffer, uint32_t bufLen, FRAME_HsExtOfferedPsks *field, uint32_t *offset) { uint32_t exOffset = 0; field->exState = INITIAL_FIELD; ParseFieldInteger16(&buffer[0], bufLen - exOffset, &field->exType, &exOffset); ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->exLen, &exOffset); if (field->exLen.data == 0u) { *offset += exOffset; return HITLS_SUCCESS; } ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->identitySize, &exOffset); ParseHsExtPskIdentity(&buffer[exOffset], bufLen - exOffset, &field->identities, field->identitySize.data, &exOffset); ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->binderSize, &exOffset); ParseHsExtPskBinder(&buffer[exOffset], bufLen - exOffset, &field->binders, field->binderSize.data, &exOffset); *offset += exOffset; return HITLS_SUCCESS; } static int32_t ParseHsExtArrayKeyShare(const uint8_t *buffer, uint32_t bufLen, FRAME_HsArrayKeyShare *field, uint32_t fieldLen, uint32_t *offset) { uint32_t exOffset = 0; field->state = INITIAL_FIELD; uint32_t size = 0; FRAME_Integer tmpIdentityLen = { 0 }; while (exOffset < fieldLen) { ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &tmpIdentityLen, &exOffset); // group ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &tmpIdentityLen, &exOffset); // key_exchange len exOffset += tmpIdentityLen.data; if (exOffset <= fieldLen) { size++; } } if (size == 0) { return HITLS_SUCCESS; } field->data = BSL_SAL_Calloc(size, sizeof(FRAME_HsKeyShareEntry)); if (field->data == NULL) { return HITLS_MEMALLOC_FAIL; } field->size = size; exOffset = 0; for (uint32_t i = 0; i < size; i++) { field->data[i].state = INITIAL_FIELD; ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->data[i].group, &exOffset); ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->data[i].keyExchangeLen, &exOffset); ParseFieldArray8(&buffer[exOffset], bufLen - exOffset, &field->data[i].keyExchange, field->data[i].keyExchangeLen.data, &exOffset); } *offset += exOffset; return HITLS_SUCCESS; } static int32_t ParseHsExtKeyShare(const uint8_t *buffer, uint32_t bufLen, FRAME_HsExtKeyShare *field, uint32_t *offset) { uint32_t exOffset = 0; field->exState = INITIAL_FIELD; ParseFieldInteger16(&buffer[0], bufLen - exOffset, &field->exType, &exOffset); ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->exLen, &exOffset); if (field->exLen.data == 0u) { *offset += exOffset; return HITLS_SUCCESS; } ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->exKeyShareLen, &exOffset); ParseHsExtArrayKeyShare(&buffer[exOffset], bufLen - exOffset, &field->exKeyShares, field->exKeyShareLen.data, &exOffset); *offset += exOffset; return HITLS_SUCCESS; } static int32_t ParseHsSupportedVersion(const uint8_t *buffer, uint32_t bufLen, FRAME_HsExtArray16 *field, uint32_t *offset) { uint32_t exOffset = 0; field->exState = INITIAL_FIELD; ParseFieldInteger16(&buffer[0], bufLen - exOffset, &field->exType, &exOffset); ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->exLen, &exOffset); if (field->exLen.data == 0u) { *offset += exOffset; return HITLS_SUCCESS; } ParseFieldInteger8(&buffer[exOffset], bufLen - exOffset, &field->exDataLen, &exOffset); ParseFieldArray16(&buffer[exOffset], bufLen - exOffset, &field->exData, field->exDataLen.data, &exOffset); *offset += exOffset; return HITLS_SUCCESS; } static int32_t ParseClientHelloMsg(FRAME_Type *frameType, const uint8_t *buffer, uint32_t bufLen, FRAME_ClientHelloMsg *clientHello, uint32_t *parseLen) { uint32_t offset = 0; ParseFieldInteger16(&buffer[0], bufLen, &clientHello->version, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &clientHello->randomValue, HS_RANDOM_SIZE, &offset); ParseFieldInteger8(&buffer[offset], bufLen - offset, &clientHello->sessionIdSize, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &clientHello->sessionId, clientHello->sessionIdSize.data, &offset); if (IS_TRANSTYPE_DATAGRAM(frameType->transportType)) { ParseFieldInteger8(&buffer[offset], bufLen - offset, &clientHello->cookiedLen, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &clientHello->cookie, clientHello->cookiedLen.data, &offset); } ParseFieldInteger16(&buffer[offset], bufLen - offset, &clientHello->cipherSuitesSize, &offset); ParseFieldArray16(&buffer[offset], bufLen - offset, &clientHello->cipherSuites, clientHello->cipherSuitesSize.data, &offset); ParseFieldInteger8(&buffer[offset], bufLen - offset, &clientHello->compressionMethodsLen, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &clientHello->compressionMethods, clientHello->compressionMethodsLen.data, &offset); ParseFieldInteger16(&buffer[offset], bufLen - offset, &clientHello->extensionLen, &offset); clientHello->extensionState = INITIAL_FIELD; /* Parsing extended fields */ while (offset < bufLen) { FRAME_Integer tmpField = {0}; uint32_t tmpOffset = offset; ParseFieldInteger16(&buffer[tmpOffset], bufLen - tmpOffset, &tmpField, &tmpOffset); switch (tmpField.data) { case HS_EX_TYPE_POINT_FORMATS: ParseHsExtArray8(&buffer[offset], bufLen - offset, &clientHello->pointFormats, &offset); break; case HS_EX_TYPE_SUPPORTED_GROUPS: ParseHsExtArray16(&buffer[offset], bufLen - offset, &clientHello->supportedGroups, &offset); break; case HS_EX_TYPE_SIGNATURE_ALGORITHMS: ParseHsExtArray16(&buffer[offset], bufLen - offset, &clientHello->signatureAlgorithms, &offset); break; case HS_EX_TYPE_EXTENDED_MASTER_SECRET: ParseHsExtArray8(&buffer[offset], bufLen - offset, &clientHello->extendedMasterSecret, &offset); break; case HS_EX_TYPE_RENEGOTIATION_INFO: ParseHsExtArray8(&buffer[offset], bufLen - offset, &clientHello->secRenego, &offset); break; case HS_EX_TYPE_SESSION_TICKET: ParseHsSessionTicketExtArray8(&buffer[offset], bufLen - offset, &clientHello->sessionTicket, &offset); break; case HS_EX_TYPE_SERVER_NAME: ParseHsExtArrayForList(&buffer[offset], bufLen - offset, &clientHello->serverName, &offset); break; case HS_EX_TYPE_APP_LAYER_PROTOCOLS: ParseHsExtArrayForList(&buffer[offset], bufLen - offset, &clientHello->alpn, &offset); break; case HS_EX_TYPE_KEY_SHARE: ParseHsExtKeyShare(&buffer[offset], bufLen - offset, &clientHello->keyshares, &offset); break; case HS_EX_TYPE_PRE_SHARED_KEY: ParseHsExtPsk(&buffer[offset], bufLen - offset, &clientHello->psks, &offset); break; case HS_EX_TYPE_PSK_KEY_EXCHANGE_MODES: ParseHsExtArray8(&buffer[offset], bufLen - offset, &clientHello->pskModes, &offset); break; case HS_EX_TYPE_SUPPORTED_VERSIONS: ParseHsSupportedVersion(&buffer[offset], bufLen - offset, &clientHello->supportedVersion, &offset); break; case HS_EX_TYPE_COOKIE: ParseHsExtArrayForList(&buffer[offset], bufLen - offset, &clientHello->tls13Cookie, &offset); break; case HS_EX_TYPE_ENCRYPT_THEN_MAC: ParseHsExtArray8(&buffer[offset], bufLen - offset, &clientHello->encryptThenMac, &offset); break; default: /* Unrecognized extension. Skip parsing the extension. */ ParseFieldInteger16(&buffer[tmpOffset], bufLen - tmpOffset, &tmpField, &tmpOffset); tmpOffset += tmpField.data; offset = tmpOffset; break; } if (tmpOffset == offset) { break; } } *parseLen += offset; return HITLS_SUCCESS; } static void CleanClientHelloMsg(FRAME_ClientHelloMsg *clientHello) { BSL_SAL_FREE(clientHello->randomValue.data); BSL_SAL_FREE(clientHello->sessionId.data); BSL_SAL_FREE(clientHello->cookie.data); BSL_SAL_FREE(clientHello->cipherSuites.data); BSL_SAL_FREE(clientHello->compressionMethods.data); BSL_SAL_FREE(clientHello->pointFormats.exData.data); BSL_SAL_FREE(clientHello->supportedGroups.exData.data); BSL_SAL_FREE(clientHello->signatureAlgorithms.exData.data); BSL_SAL_FREE(clientHello->extendedMasterSecret.exData.data); BSL_SAL_FREE(clientHello->secRenego.exData.data); BSL_SAL_FREE(clientHello->sessionTicket.exData.data); BSL_SAL_FREE(clientHello->serverName.exData.data); BSL_SAL_FREE(clientHello->alpn.exData.data); for (uint32_t i = 0; i < clientHello->keyshares.exKeyShares.size; i++) { BSL_SAL_FREE(clientHello->keyshares.exKeyShares.data[i].keyExchange.data); } for (uint32_t i = 0; i < clientHello->psks.identities.size; i++) { BSL_SAL_FREE(clientHello->psks.identities.data[i].identity.data); } for (uint32_t i = 0; i < clientHello->psks.binders.size; i++) { BSL_SAL_FREE(clientHello->psks.binders.data[i].binder.data); } BSL_SAL_FREE(clientHello->keyshares.exKeyShares.data); BSL_SAL_FREE(clientHello->psks.binders.data); BSL_SAL_FREE(clientHello->psks.identities.data); BSL_SAL_FREE(clientHello->supportedVersion.exData.data); BSL_SAL_FREE(clientHello->tls13Cookie.exData.data); BSL_SAL_FREE(clientHello->pskModes.exData.data); BSL_SAL_FREE(clientHello->caList.list.data); return; } static int32_t ParseHsExtUint16(const uint8_t *buffer, uint32_t bufLen, FRAME_HsExtUint16 *field, uint32_t *offset) { uint32_t exOffset = 0; field->exState = INITIAL_FIELD; ParseFieldInteger16(&buffer[0], bufLen, &field->exType, &exOffset); ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->exLen, &exOffset); if (field->exLen.data == 0u) { *offset += exOffset; return HITLS_SUCCESS; } ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->data, &exOffset); *offset += exOffset; return HITLS_SUCCESS; } static int32_t ParseHsExtServerKeyShare(const uint8_t *buffer, uint32_t bufLen, FRAME_HsExtServerKeyShare *field, uint32_t *offset) { uint32_t exOffset = 0; field->exState = INITIAL_FIELD; ParseFieldInteger16(&buffer[0], bufLen, &field->exType, &exOffset); ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->exLen, &exOffset); if (field->exLen.data == 0u) { *offset += exOffset; return HITLS_SUCCESS; } field->data.state = INITIAL_FIELD; ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->data.group, &exOffset); ParseFieldInteger16(&buffer[exOffset], bufLen - exOffset, &field->data.keyExchangeLen, &exOffset); ParseFieldArray8(&buffer[exOffset], bufLen - exOffset, &field->data.keyExchange, field->data.keyExchangeLen.data, &exOffset); *offset += exOffset; return HITLS_SUCCESS; } static int32_t ParseServerHelloMsg(const uint8_t *buffer, uint32_t bufLen, FRAME_ServerHelloMsg *serverHello, uint32_t *parseLen) { uint32_t offset = 0; ParseFieldInteger16(&buffer[0], bufLen, &serverHello->version, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &serverHello->randomValue, HS_RANDOM_SIZE, &offset); ParseFieldInteger8(&buffer[offset], bufLen - offset, &serverHello->sessionIdSize, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &serverHello->sessionId, serverHello->sessionIdSize.data, &offset); ParseFieldInteger16(&buffer[offset], bufLen - offset, &serverHello->cipherSuite, &offset); ParseFieldInteger8(&buffer[offset], bufLen - offset, &serverHello->compressionMethod, &offset); ParseFieldInteger16(&buffer[offset], bufLen - offset, &serverHello->extensionLen, &offset); /* Parsing extended fields */ while (offset < bufLen) { FRAME_Integer tmpField = {0}; uint32_t tmpOffset = offset; ParseFieldInteger16(&buffer[tmpOffset], bufLen - tmpOffset, &tmpField, &tmpOffset); switch (tmpField.data) { case HS_EX_TYPE_POINT_FORMATS: ParseHsExtArray8(&buffer[offset], bufLen - offset, &serverHello->pointFormats, &offset); break; case HS_EX_TYPE_EXTENDED_MASTER_SECRET: ParseHsExtArray8(&buffer[offset], bufLen - offset, &serverHello->extendedMasterSecret, &offset); break; case HS_EX_TYPE_RENEGOTIATION_INFO: ParseHsExtArray8(&buffer[offset], bufLen - offset, &serverHello->secRenego, &offset); break; case HS_EX_TYPE_SESSION_TICKET: ParseHsSessionTicketExtArray8(&buffer[offset], bufLen - offset, &serverHello->sessionTicket, &offset); break; case HS_EX_TYPE_SERVER_NAME: ParseHsExtArrayForList(&buffer[offset], bufLen - offset, &serverHello->serverName, &offset); break; case HS_EX_TYPE_APP_LAYER_PROTOCOLS: ParseHsExtArrayForList(&buffer[offset], bufLen - offset, &serverHello->alpn, &offset); break; case HS_EX_TYPE_SUPPORTED_VERSIONS: ParseHsExtUint16(&buffer[offset], bufLen - offset, &serverHello->supportedVersion, &offset); break; case HS_EX_TYPE_KEY_SHARE: ParseHsExtServerKeyShare(&buffer[offset], bufLen - offset, &serverHello->keyShare, &offset); break; case HS_EX_TYPE_PRE_SHARED_KEY: ParseHsExtUint16(&buffer[offset], bufLen - offset, &serverHello->pskSelectedIdentity, &offset); break; case HS_EX_TYPE_COOKIE: ParseHsExtArray8(&buffer[offset], bufLen - offset, &serverHello->tls13Cookie, &offset); break; case HS_EX_TYPE_ENCRYPT_THEN_MAC: ParseHsExtArray8(&buffer[offset], bufLen - offset, &serverHello->encryptThenMac, &offset); break; default: /* Unrecognized extension, return error */ *parseLen += offset; return HITLS_PARSE_UNSUPPORTED_EXTENSION; } } *parseLen += offset; return HITLS_SUCCESS; } static void CleanServerHelloMsg(FRAME_ServerHelloMsg *serverHello) { BSL_SAL_FREE(serverHello->randomValue.data); BSL_SAL_FREE(serverHello->sessionId.data); BSL_SAL_FREE(serverHello->pointFormats.exData.data); BSL_SAL_FREE(serverHello->extendedMasterSecret.exData.data); BSL_SAL_FREE(serverHello->secRenego.exData.data); BSL_SAL_FREE(serverHello->sessionTicket.exData.data); BSL_SAL_FREE(serverHello->serverName.exData.data); BSL_SAL_FREE(serverHello->alpn.exData.data); BSL_SAL_FREE(serverHello->keyShare.data.keyExchange.data); BSL_SAL_FREE(serverHello->tls13Cookie.exData.data); return; } static int32_t ParseCertificateMsg( FRAME_Type *type, const uint8_t *buffer, uint32_t bufLen, FRAME_CertificateMsg *certificate, uint32_t *parseLen) { uint32_t offset = 0; if (type->versionType == HITLS_VERSION_TLS13) { ParseFieldInteger8(&buffer[0], bufLen, &certificate->certificateReqCtxSize, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &certificate->certificateReqCtx, certificate->certificateReqCtxSize.data, &offset); } ParseFieldInteger24(&buffer[offset], bufLen - offset, &certificate->certsLen, &offset); if (certificate->certsLen.data == 0) { *parseLen += offset; return HITLS_SUCCESS; } FrameCertItem *certItem = NULL; while (offset < bufLen) { uint32_t tmpOffset = offset; FrameCertItem *item = BSL_SAL_Calloc(1u, sizeof(FrameCertItem)); if (item == NULL) { return HITLS_MEMALLOC_FAIL; } item->state = INITIAL_FIELD; ParseFieldInteger24(&buffer[offset], bufLen - offset, &item->certLen, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &item->cert, item->certLen.data, &offset); if (type->versionType == HITLS_VERSION_TLS13) { ParseFieldInteger16(&buffer[offset], bufLen - offset, &item->extensionLen, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &item->extension, item->extensionLen.data, &offset); } if (certificate->certItem == NULL) { certificate->certItem = item; } else { certItem->next = item; } certItem = item; if (tmpOffset == offset) { break; } } *parseLen += offset; return HITLS_SUCCESS; } static void CleanCertificateMsg(FRAME_CertificateMsg *certificate) { BSL_SAL_FREE(certificate->certificateReqCtx.data); FrameCertItem *certItem = certificate->certItem; while (certItem != NULL) { FrameCertItem *temp = certItem->next; BSL_SAL_FREE(certItem->cert.data); BSL_SAL_FREE(certItem->extension.data); BSL_SAL_FREE(certItem); certItem = temp; } certificate->certItem = NULL; return; } static int32_t ParseServerKxEcdhMsg(FRAME_Type *frameType, const uint8_t *buffer, uint32_t bufLen, FRAME_ServerEcdh *ecdh, uint32_t *parseLen) { uint32_t offset = 0; ParseFieldInteger8(&buffer[0], bufLen, &ecdh->curveType, &offset); if (ecdh->curveType.data != HITLS_EC_CURVE_TYPE_NAMED_CURVE) { return HITLS_PARSE_UNSUPPORT_KX_ALG; } ParseFieldInteger16(&buffer[offset], bufLen - offset, &ecdh->namedcurve, &offset); ParseFieldInteger8(&buffer[offset], bufLen - offset, &ecdh->pubKeySize, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &ecdh->pubKey, ecdh->pubKeySize.data, &offset); if (((!IS_DTLS_VERSION(frameType->versionType)) && (frameType->versionType >= HITLS_VERSION_TLS12)) || ((IS_DTLS_VERSION(frameType->versionType)) && (frameType->versionType <= HITLS_VERSION_DTLS12))) { ParseFieldInteger16(&buffer[offset], bufLen - offset, &ecdh->signAlgorithm, &offset); } ParseFieldInteger16(&buffer[offset], bufLen - offset, &ecdh->signSize, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &ecdh->signData, ecdh->signSize.data, &offset); *parseLen += offset; return HITLS_SUCCESS; } static int32_t ParseServerKxDhMsg(FRAME_Type *frameType, const uint8_t *buffer, uint32_t bufLen, FRAME_ServerDh *dh, uint32_t *parseLen) { uint32_t offset = 0; ParseFieldInteger16(&buffer[0], bufLen, &dh->plen, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &dh->p, dh->plen.data, &offset); ParseFieldInteger16(&buffer[offset], bufLen - offset, &dh->glen, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &dh->g, dh->glen.data, &offset); ParseFieldInteger16(&buffer[offset], bufLen - offset, &dh->pubKeyLen, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &dh->pubKey, dh->pubKeyLen.data, &offset); if (((!IS_DTLS_VERSION(frameType->versionType)) && (frameType->versionType >= HITLS_VERSION_TLS12)) || ((IS_DTLS_VERSION(frameType->versionType)) && (frameType->versionType <= HITLS_VERSION_DTLS12))) { ParseFieldInteger16(&buffer[offset], bufLen - offset, &dh->signAlgorithm, &offset); } ParseFieldInteger16(&buffer[offset], bufLen - offset, &dh->signSize, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &dh->signData, dh->signSize.data, &offset); *parseLen += offset; return HITLS_SUCCESS; } static int32_t ParseServerKxEccMsg(const uint8_t *buffer, uint32_t bufLen, FRAME_ServerEcdh *ecdh, uint32_t *parseLen) { uint32_t offset = 0; ParseFieldInteger16(&buffer[offset], bufLen - offset, &ecdh->signSize, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &ecdh->signData, ecdh->signSize.data, &offset); *parseLen += offset; return HITLS_SUCCESS; } static int32_t ParseServerKxMsg(FRAME_Type *frameType, const uint8_t *buffer, uint32_t bufLen, FRAME_ServerKeyExchangeMsg *serverKx, uint32_t *parseLen) { switch (frameType->keyExType) { case HITLS_KEY_EXCH_ECDHE: return ParseServerKxEcdhMsg(frameType, buffer, bufLen, &serverKx->keyEx.ecdh, parseLen); case HITLS_KEY_EXCH_DHE: return ParseServerKxDhMsg(frameType, buffer, bufLen, &serverKx->keyEx.dh, parseLen); case HITLS_KEY_EXCH_ECC: return ParseServerKxEccMsg(buffer, bufLen, &serverKx->keyEx.ecdh, parseLen); default: break; } return HITLS_PARSE_UNSUPPORT_KX_ALG; } static void CleanServerKxMsg(HITLS_KeyExchAlgo kexType, FRAME_ServerKeyExchangeMsg *serverKx) { FRAME_ServerEcdh *ecdh = &serverKx->keyEx.ecdh; FRAME_ServerDh *dh = &serverKx->keyEx.dh; switch (kexType) { case HITLS_KEY_EXCH_ECDHE: BSL_SAL_FREE(ecdh->pubKey.data); BSL_SAL_FREE(ecdh->signData.data); break; case HITLS_KEY_EXCH_DHE: BSL_SAL_FREE(dh->p.data); BSL_SAL_FREE(dh->g.data); BSL_SAL_FREE(dh->pubKey.data); BSL_SAL_FREE(dh->signData.data); break; default: break; } return; } static int32_t ParseCertReqMsgExBody(uint16_t extMsgType, const uint8_t *buffer, uint32_t bufLen, FRAME_CertificateRequestMsg *certReq, uint32_t *parseLen) { uint32_t offset = 0; switch (extMsgType) { case HS_EX_TYPE_SIGNATURE_ALGORITHMS: ParseFieldInteger16(&buffer[offset], bufLen - offset, &certReq->signatureAlgorithmsSize, &offset); ParseFieldArray16(&buffer[offset], bufLen - offset, &certReq->signatureAlgorithms, certReq->signatureAlgorithmsSize.data, &offset); break; default: break; } *parseLen += offset; return HITLS_SUCCESS; } static int32_t ParseCertReqMsg( FRAME_Type *type, const uint8_t *buffer, uint32_t bufLen, FRAME_CertificateRequestMsg *certReq, uint32_t *parseLen) { uint32_t offset = 0; certReq->state = INITIAL_FIELD; if (type->versionType != HITLS_VERSION_TLS13) { ParseFieldInteger8(&buffer[0], bufLen, &certReq->certTypesSize, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &certReq->certTypes, certReq->certTypesSize.data, &offset); ParseFieldInteger16(&buffer[offset], bufLen - offset, &certReq->signatureAlgorithmsSize, &offset); ParseFieldArray16(&buffer[offset], bufLen - offset, &certReq->signatureAlgorithms, certReq->signatureAlgorithmsSize.data, &offset); ParseFieldInteger16(&buffer[offset], bufLen - offset, &certReq->distinguishedNamesSize, &offset); if (certReq->distinguishedNamesSize.data != 0u) { ParseFieldArray8(&buffer[offset], bufLen - offset, &certReq->distinguishedNames, certReq->distinguishedNamesSize.data, &offset); } } else { ParseFieldInteger8(&buffer[0], bufLen, &certReq->certificateReqCtxSize, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &certReq->certificateReqCtx, certReq->certificateReqCtxSize.data, &offset); ParseFieldInteger16(&buffer[offset], bufLen - offset, &certReq->exMsgLen, &offset); while (offset < bufLen) { uint32_t tmpOffset = offset; FRAME_Integer extMsgType ; FRAME_Integer extMsgLen ; ParseFieldInteger16(&buffer[offset], bufLen - offset, &extMsgType, &offset); ParseFieldInteger16(&buffer[offset], bufLen - offset, &extMsgLen, &offset); ParseCertReqMsgExBody(extMsgType.data, &buffer[offset], bufLen - offset, certReq, &offset); if (offset == tmpOffset) { break; } } } *parseLen += offset; return HITLS_SUCCESS; } static void CleanCertReqMsg(FRAME_CertificateRequestMsg *certReq) { BSL_SAL_FREE(certReq->certTypes.data); BSL_SAL_FREE(certReq->signatureAlgorithms.data); BSL_SAL_FREE(certReq->distinguishedNames.data); BSL_SAL_FREE(certReq->certificateReqCtx.data); return; } static int32_t ParseServerHelloDoneMsg(uint32_t bufLen) { if (bufLen != 0) { return HITLS_PARSE_INVALID_MSG_LEN; } return HITLS_SUCCESS; } static void CleanServerHelloDoneMsg(FRAME_ServerHelloDoneMsg *serverHelloDone) { /* The ServerHelloDone packet is an empty packet. If there is any constructed data, release it. */ BSL_SAL_FREE(serverHelloDone->extra.data); return; } static int32_t ParseClientKxMsg(FRAME_Type *frameType, const uint8_t *buffer, uint32_t bufLen, FRAME_ClientKeyExchangeMsg *clientKx, uint32_t *parseLen) { uint32_t offset = 0; switch (frameType->keyExType) { case HITLS_KEY_EXCH_ECDHE: /* Compatible with OpenSSL. Three bytes are added to the client key exchange. */ #ifdef HITLS_TLS_PROTO_TLCP11 if (frameType->versionType == HITLS_VERSION_TLCP_DTLCP11) { // Curve type + Curve ID + Public key length uint8_t minLen = sizeof(uint8_t) + sizeof(uint16_t) + sizeof(uint8_t); if (bufLen < minLen) { return HITLS_PARSE_INVALID_MSG_LEN; } // Ignore the first three bytes. offset += sizeof(uint8_t) + sizeof(uint16_t); } #endif ParseFieldInteger8(&buffer[offset], bufLen - offset, &clientKx->pubKeySize, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &clientKx->pubKey, clientKx->pubKeySize.data, &offset); break; case HITLS_KEY_EXCH_DHE: case HITLS_KEY_EXCH_RSA: ParseFieldInteger16(&buffer[offset], bufLen - offset, &clientKx->pubKeySize, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &clientKx->pubKey, clientKx->pubKeySize.data, &offset); break; default: return HITLS_PARSE_UNSUPPORT_KX_ALG; } *parseLen += offset; return HITLS_SUCCESS; } static void CleanClientKxMsg(FRAME_ClientKeyExchangeMsg *clientKx) { BSL_SAL_FREE(clientKx->pubKey.data); return; } static int32_t ParseCertVerifyMsg(FRAME_Type *frameType, const uint8_t *buffer, uint32_t bufLen, FRAME_CertificateVerifyMsg *certVerify, uint32_t *parseLen) { uint32_t offset = 0; if (((!IS_DTLS_VERSION(frameType->versionType)) && (frameType->versionType >= HITLS_VERSION_TLS12)) || ((IS_DTLS_VERSION(frameType->versionType)) && (frameType->versionType <= HITLS_VERSION_DTLS12))) { ParseFieldInteger16(&buffer[0], bufLen, &certVerify->signHashAlg, &offset); } ParseFieldInteger16(&buffer[offset], bufLen - offset, &certVerify->signSize, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &certVerify->sign, certVerify->signSize.data, &offset); *parseLen += offset; return HITLS_SUCCESS; } static void CleanCertVerifyMsg(FRAME_CertificateVerifyMsg *certVerify) { BSL_SAL_FREE(certVerify->sign.data); return; } static int32_t ParseFinishedMsg(const uint8_t *buffer, uint32_t bufLen, FRAME_FinishedMsg *finished, uint32_t *parseLen) { uint32_t offset = 0; ParseFieldArray8(buffer, bufLen, &finished->verifyData, bufLen, &offset); *parseLen += offset; return HITLS_SUCCESS; } static void CleanFinishedMsg(FRAME_FinishedMsg *finished) { BSL_SAL_FREE(finished->verifyData.data); return; } static int32_t ParseNewSessionTicket(FRAME_Type *frameType, const uint8_t *buffer, uint32_t bufLen, FRAME_NewSessionTicketMsg *sessionTicket, uint32_t *parseLen) { uint32_t offset = 0; ParseFieldInteger32(&buffer[0], bufLen, &sessionTicket->ticketLifetime, &offset); if (frameType->versionType != HITLS_VERSION_TLS13) { ParseFieldInteger16(&buffer[offset], bufLen - offset, &sessionTicket->ticketSize, &offset); ParseFieldArray8( &buffer[offset], bufLen - offset, &sessionTicket->ticket, sessionTicket->ticketSize.data, &offset); } else { ParseFieldInteger32(&buffer[offset], bufLen - offset, &sessionTicket->ticketAgeAdd, &offset); ParseFieldInteger8(&buffer[offset], bufLen - offset, &sessionTicket->ticketNonceSize, &offset); ParseFieldArray8(&buffer[offset], bufLen - offset, &sessionTicket->ticketNonce, sessionTicket->ticketNonceSize.data, &offset); ParseFieldInteger16(&buffer[offset], bufLen - offset, &sessionTicket->ticketSize, &offset); ParseFieldArray8( &buffer[offset], bufLen - offset, &sessionTicket->ticket, sessionTicket->ticketSize.data, &offset); ParseFieldInteger16(&buffer[offset], bufLen - offset, &sessionTicket->extensionLen, &offset); while (offset < bufLen) { FRAME_Integer tmpField = {0}; uint32_t tmpOffset = offset; ParseFieldInteger16(&buffer[tmpOffset], bufLen - tmpOffset, &tmpField, &tmpOffset); switch (tmpField.data) { default: /* The extensions in the tls 1.3 new session ticket cannot be parsed currently. Skip this step. */ ParseFieldInteger16(&buffer[tmpOffset], bufLen - tmpOffset, &tmpField, &tmpOffset); tmpOffset += tmpField.data; offset = tmpOffset; break; } } } *parseLen += offset; return HITLS_SUCCESS; } static void CleanNewSessionTicket(FRAME_NewSessionTicketMsg *sessionTicket) { BSL_SAL_FREE(sessionTicket->ticket.data); BSL_SAL_FREE(sessionTicket->ticketNonce.data); return; } static int32_t ParseHsMsg(FRAME_Type *frameType, const uint8_t *buffer, uint32_t bufLen, FRAME_HsMsg *hsMsg, uint32_t *parseLen) { uint32_t offset = 0; ParseFieldInteger8(&buffer[0], bufLen, &hsMsg->type, &offset); ParseFieldInteger24(&buffer[offset], bufLen - offset, &hsMsg->length, &offset); if (IS_TRANSTYPE_DATAGRAM(frameType->transportType)) { ParseFieldInteger16(&buffer[offset], bufLen - offset, &hsMsg->sequence, &offset); ParseFieldInteger24(&buffer[offset], bufLen - offset, &hsMsg->fragmentOffset, &offset); ParseFieldInteger24(&buffer[offset], bufLen - offset, &hsMsg->fragmentLength, &offset); } *parseLen += offset; /* To ensure that the memory can be normally released after users modify hsMsg->type.data, * assign a value to frameType. */ frameType->handshakeType = hsMsg->type.data; switch (hsMsg->type.data) { case CLIENT_HELLO: return ParseClientHelloMsg(frameType, &buffer[offset], bufLen - offset, &hsMsg->body.clientHello, parseLen); case SERVER_HELLO: return ParseServerHelloMsg(&buffer[offset], bufLen - offset, &hsMsg->body.serverHello, parseLen); case CERTIFICATE: return ParseCertificateMsg(frameType, &buffer[offset], bufLen - offset, &hsMsg->body.certificate, parseLen); case SERVER_KEY_EXCHANGE: return ParseServerKxMsg(frameType, &buffer[offset], bufLen - offset, &hsMsg->body.serverKeyExchange, parseLen); case CERTIFICATE_REQUEST: return ParseCertReqMsg(frameType, &buffer[offset], bufLen - offset, &hsMsg->body.certificateReq, parseLen); case CLIENT_KEY_EXCHANGE: return ParseClientKxMsg(frameType, &buffer[offset], bufLen - offset, &hsMsg->body.clientKeyExchange, parseLen); case CERTIFICATE_VERIFY: return ParseCertVerifyMsg(frameType, &buffer[offset], bufLen - offset, &hsMsg->body.certificateVerify, parseLen); case FINISHED: return ParseFinishedMsg(&buffer[offset], bufLen - offset, &hsMsg->body.finished, parseLen); case SERVER_HELLO_DONE: return ParseServerHelloDoneMsg(bufLen - offset); case NEW_SESSION_TICKET: return ParseNewSessionTicket(frameType, &buffer[offset], bufLen - offset, &hsMsg->body.newSessionTicket, parseLen); default: break; } return HITLS_PARSE_UNSUPPORT_HANDSHAKE_MSG; } static int32_t ParseCcsMsg(const uint8_t *buffer, uint32_t bufLen, FRAME_CcsMsg *ccsMsg, uint32_t *parseLen) { /* The length of the CCS message is 1 byte. */ if (bufLen != 1u) { return HITLS_PARSE_INVALID_MSG_LEN; } uint32_t offset = 0; ParseFieldInteger8(buffer, bufLen, &ccsMsg->ccsType, &offset); *parseLen += offset; return HITLS_SUCCESS; } static void CleanCcsMsg(FRAME_CcsMsg *ccsMsg) { /* This field is used to construct abnormal packets. Data is not written during parsing. However, * users may apply for memory. Therefore, this field needs to be released. */ BSL_SAL_FREE(ccsMsg->extra.data); return; } static int32_t ParseAlertMsg(const uint8_t *buffer, uint32_t bufLen, FRAME_AlertMsg *alertMsg, uint32_t *parseLen) { /* The length of the alert message is 2 bytes. */ if (bufLen != 2u) { return HITLS_PARSE_INVALID_MSG_LEN; } uint32_t offset = 0; ParseFieldInteger8(&buffer[0], bufLen, &alertMsg->alertLevel, &offset); ParseFieldInteger8(&buffer[offset], bufLen - offset, &alertMsg->alertDescription, &offset); *parseLen += offset; return HITLS_SUCCESS; } static void CleanAlertMsg(FRAME_AlertMsg *alertMsg) { /* This field is used to construct abnormal packets. Data is not written during parsing. * However, users may apply for memory. Therefore, this field needs to be released. */ BSL_SAL_FREE(alertMsg->extra.data); return; } static int32_t ParseAppMsg(const uint8_t *buffer, uint32_t bufLen, FRAME_AppMsg *appMsg, uint32_t *parseLen) { if (bufLen == 0u) { return HITLS_PARSE_INVALID_MSG_LEN; } uint32_t offset = 0; ParseFieldArray8(buffer, bufLen, &appMsg->appData, bufLen, &offset); *parseLen += offset; return HITLS_SUCCESS; } static void CleanAppMsg(FRAME_AppMsg *appMsg) { BSL_SAL_FREE(appMsg->appData.data); return; } int32_t FRAME_ParseMsgHeader( FRAME_Type *frameType, const uint8_t *buffer, uint32_t bufLen, FRAME_Msg *msg, uint32_t *parseLen) { if ((frameType == NULL) || (buffer == NULL) || (msg == NULL) || (parseLen == NULL)) { return HITLS_INTERNAL_EXCEPTION; } uint32_t offset = 0; ParseFieldInteger8(&buffer[0], bufLen, &msg->recType, &offset); ParseFieldInteger16(&buffer[offset], bufLen - offset, &msg->recVersion, &offset); if (IS_TRANSTYPE_DATAGRAM(frameType->transportType)) { ParseFieldInteger16(&buffer[offset], bufLen - offset, &msg->epoch, &offset); ParseFieldInteger48(&buffer[offset], bufLen - offset, &msg->sequence, &offset); } ParseFieldInteger16(&buffer[offset], bufLen - offset, &msg->length, &offset); if ((msg->length.data + offset) > bufLen) { return HITLS_PARSE_INVALID_MSG_LEN; } *parseLen = offset; return HITLS_SUCCESS; } int32_t FRAME_ParseTLSRecordHeader(const uint8_t *buffer, uint32_t bufferLen, FRAME_Msg *msg, uint32_t *parsedLen) { if ((buffer == NULL) || (msg == NULL) || (parsedLen == NULL)) { return HITLS_INTERNAL_EXCEPTION; } uint32_t offset = 0; // Parse the 0th byte of the buffer. The parsing result is stored in msg->recType, offset = 1. ParseFieldInteger8(buffer, bufferLen, &msg->recType, &offset); // Parse the first and second bytes of the buffer. The parsing result is stored in msg->recVersion, offset = 3. ParseFieldInteger16(buffer + offset, bufferLen - offset, &msg->recVersion, &offset); // Parse the third to fourth bytes of the buffer. The parsing result is stored in msg->length, and offset = 5. ParseFieldInteger16(buffer + offset, bufferLen - offset, &msg->length, &offset); // msg->length.data indicates the length of the parsed record body. // In this case, the value of offset is the header length. if ((msg->length.data + offset) > bufferLen) { // The length of the entire message cannot be greater than bufLen. return HITLS_PARSE_INVALID_MSG_LEN; } *parsedLen = offset; return HITLS_SUCCESS; } // Parse the body of a non-handshake record. int32_t FRAME_ParseTLSNonHsRecordBody(const uint8_t *buffer, uint32_t bufferLen, FRAME_Msg *msg, uint32_t *parseLen) { if ((buffer == NULL) || (msg == NULL) || (parseLen == NULL)) { return HITLS_INTERNAL_EXCEPTION; } switch (msg->recType.data) { case REC_TYPE_CHANGE_CIPHER_SPEC: return ParseCcsMsg(buffer, bufferLen, &msg->body.ccsMsg, parseLen); case REC_TYPE_ALERT: return ParseAlertMsg(buffer, bufferLen, &msg->body.alertMsg, parseLen); case REC_TYPE_APP: return ParseAppMsg(buffer, bufferLen, &msg->body.appMsg, parseLen); default: break; } return HITLS_INTERNAL_EXCEPTION; } int32_t FRAME_ParseMsgBody( FRAME_Type *frameType, const uint8_t *buffer, uint32_t bufLen, FRAME_Msg *msg, uint32_t *parseLen) { if ((frameType == NULL) || (buffer == NULL) || (msg == NULL) || (parseLen == NULL)) { return HITLS_INTERNAL_EXCEPTION; } /* To ensure that the memory can be normally released after users modify msg->recType.data, * assign a value to frameType. */ frameType->recordType = msg->recType.data; switch (msg->recType.data) { case REC_TYPE_HANDSHAKE: return ParseHsMsg(frameType, buffer, bufLen, &msg->body.hsMsg, parseLen); case REC_TYPE_CHANGE_CIPHER_SPEC: return ParseCcsMsg(buffer, bufLen, &msg->body.ccsMsg, parseLen); case REC_TYPE_ALERT: return ParseAlertMsg(buffer, bufLen, &msg->body.alertMsg, parseLen); case REC_TYPE_APP: return ParseAppMsg(buffer, bufLen, &msg->body.appMsg, parseLen); default: break; } return HITLS_INTERNAL_EXCEPTION; } int32_t FRAME_ParseMsg(FRAME_Type *frameType, const uint8_t *buffer, uint32_t bufLen, FRAME_Msg *msg, uint32_t *parseLen) { int32_t ret; ret = FRAME_ParseMsgHeader(frameType, buffer, bufLen, msg, parseLen); if (ret != HITLS_SUCCESS) { return ret; } return FRAME_ParseMsgBody(frameType, &buffer[*parseLen], msg->length.data, msg, parseLen); } int32_t FRAME_ParseTLSNonHsRecord(const uint8_t *buffer, uint32_t bufLen, FRAME_Msg *msg, uint32_t *parseLen) { int32_t ret; uint32_t headerLen; ret = FRAME_ParseTLSRecordHeader(buffer, bufLen, msg, parseLen); if (ret != HITLS_SUCCESS) { return ret; } headerLen = *parseLen; return FRAME_ParseTLSNonHsRecordBody(buffer + headerLen, msg->length.data, msg, parseLen); } int32_t FRAME_ParseHsRecord( FRAME_Type *frameType, const uint8_t *buffer, uint32_t bufferLen, FRAME_Msg *msg, uint32_t *parseLen) { int32_t ret; uint32_t headerLen; ret = FRAME_ParseMsgHeader(frameType, buffer, bufferLen, msg, parseLen); if (ret != HITLS_SUCCESS) { return ret; } headerLen = *parseLen; /* To ensure that the memory can be normally released after users modify msg->recType.data, * assign a value to frameType. */ frameType->recordType = msg->recType.data; if (msg->recType.data == REC_TYPE_HANDSHAKE) { return ParseHsMsg(frameType, buffer + headerLen, msg->length.data, &msg->body.hsMsg, parseLen); } return HITLS_PARSE_UNSUPPORT_HANDSHAKE_MSG; } static void CleanParsedHsMsg(HS_MsgType handshakeType, HITLS_KeyExchAlgo kexType, FRAME_HsMsg *hsMsg) { switch (handshakeType) { case CLIENT_HELLO: return CleanClientHelloMsg(&hsMsg->body.clientHello); case SERVER_HELLO: return CleanServerHelloMsg(&hsMsg->body.serverHello); case CERTIFICATE: return CleanCertificateMsg(&hsMsg->body.certificate); case SERVER_KEY_EXCHANGE: return CleanServerKxMsg(kexType, &hsMsg->body.serverKeyExchange); case CERTIFICATE_REQUEST: return CleanCertReqMsg(&hsMsg->body.certificateReq); case CLIENT_KEY_EXCHANGE: return CleanClientKxMsg(&hsMsg->body.clientKeyExchange); case CERTIFICATE_VERIFY: return CleanCertVerifyMsg(&hsMsg->body.certificateVerify); case FINISHED: return CleanFinishedMsg(&hsMsg->body.finished); case SERVER_HELLO_DONE: return CleanServerHelloDoneMsg(&hsMsg->body.serverHelloDone); case NEW_SESSION_TICKET: return CleanNewSessionTicket(&hsMsg->body.newSessionTicket); default: break; } return; } static void CleanHsMsg(FRAME_Type *frameType, FRAME_HsMsg *hsMsg) { return CleanParsedHsMsg(frameType->handshakeType, frameType->keyExType, hsMsg); } void FRAME_CleanMsg(FRAME_Type *frameType, FRAME_Msg *msg) { if ((frameType == NULL) || (msg == NULL)) { return; } switch (frameType->recordType) { case REC_TYPE_HANDSHAKE: CleanHsMsg(frameType, &msg->body.hsMsg); break; case REC_TYPE_CHANGE_CIPHER_SPEC: CleanCcsMsg(&msg->body.ccsMsg); break; case REC_TYPE_ALERT: CleanAlertMsg(&msg->body.alertMsg); break; case REC_TYPE_APP: CleanAppMsg(&msg->body.appMsg); break; default: break; } memset_s(msg, sizeof(FRAME_Msg), 0, sizeof(FRAME_Msg)); return; } void FRAME_CleanNonHsRecord(REC_Type recType, FRAME_Msg *msg) { if (msg == NULL) { return; } switch (recType) { case REC_TYPE_CHANGE_CIPHER_SPEC: CleanCcsMsg(&msg->body.ccsMsg); break; case REC_TYPE_ALERT: CleanAlertMsg(&msg->body.alertMsg); break; case REC_TYPE_APP: CleanAppMsg(&msg->body.appMsg); break; default: break; } memset_s(msg, sizeof(FRAME_Msg), 0, sizeof(FRAME_Msg)); }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/msg/src/frame_parse_msg.c
C
unknown
51,939
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "securec.h" #include "bsl_bytes.h" #include "bsl_sal.h" #include "hitls_error.h" #include "hitls.h" #include "tls.h" #include "hs_ctx.h" #include "pack_common.h" #include "pack.h" #include "frame_msg.h" #include "pack_frame_msg.h" #define RECORD_BUF_LEN (18 * 1024) #define TEST_CERT_LEN_TAG_SIZE 3 TLS_Ctx *NewFrameTlsCtx(void) { TLS_Ctx *tlsCtx = (TLS_Ctx *)BSL_SAL_Calloc(1u, sizeof(HITLS_Ctx)); if (tlsCtx == NULL) { return NULL; } tlsCtx->hsCtx = (HS_Ctx *)BSL_SAL_Calloc(1u, sizeof(HS_Ctx)); if (tlsCtx->hsCtx == NULL) { BSL_SAL_FREE(tlsCtx); return NULL; } tlsCtx->hsCtx->clientRandom = tlsCtx->negotiatedInfo.clientRandom; tlsCtx->hsCtx->serverRandom = tlsCtx->negotiatedInfo.serverRandom; return tlsCtx; } int32_t GenClientHelloMandatoryCtx(TLS_Ctx *tlsCtx, FRAME_Msg *msg) { ClientHelloMsg *clientHello = &msg->body.handshakeMsg.body.clientHello; TLS_Config *tlsConfig = &tlsCtx->config.tlsConfig; tlsConfig->maxVersion = clientHello->version; int32_t ret = memcpy_s(tlsCtx->hsCtx->clientRandom, HS_RANDOM_SIZE, clientHello->randomValue, HS_RANDOM_SIZE); if (ret != EOK) { return HITLS_MEMCPY_FAIL; } if (clientHello->sessionIdSize > 0) { #if defined(HITLS_TLS_FEATURE_SESSION) || defined(HITLS_TLS_PROTO_TLS13) tlsCtx->hsCtx->sessionId = (uint8_t *)BSL_SAL_Dump(clientHello->sessionId, clientHello->sessionIdSize); if (tlsCtx->hsCtx->sessionId == NULL) { return HITLS_MEMALLOC_FAIL; } tlsCtx->hsCtx->sessionIdSize = clientHello->sessionIdSize; #endif } #ifdef HITLS_TLS_PROTO_DTLS12 if (IS_SUPPORT_DATAGRAM(tlsConfig->originVersionMask) && clientHello->cookieLen > 0) { tlsCtx->negotiatedInfo.cookieSize = clientHello->cookieLen; tlsCtx->negotiatedInfo.cookie = (uint8_t *)BSL_SAL_Dump(clientHello->cookie, clientHello->cookieLen); if (tlsCtx->negotiatedInfo.cookie == NULL) { return HITLS_MEMALLOC_FAIL; } } #endif tlsConfig->cipherSuitesSize = clientHello->cipherSuitesSize; uint32_t suitsLen = clientHello->cipherSuitesSize * sizeof(uint16_t); tlsConfig->cipherSuites = (uint16_t *)BSL_SAL_Dump(clientHello->cipherSuites, suitsLen); if (tlsConfig->cipherSuites == NULL) { return HITLS_MEMALLOC_FAIL; } return HITLS_SUCCESS; } int32_t GenClientHelloExtensionCtx(TLS_Ctx *tlsCtx, FRAME_Msg *msg) { ClientHelloMsg *clientHello = &msg->body.handshakeMsg.body.clientHello; TLS_Config *tlsConfig = &tlsCtx->config.tlsConfig; tlsConfig->isSupportExtendMasterSecret = clientHello->extension.flag.haveExtendedMasterSecret; tlsConfig->signAlgorithmsSize = clientHello->extension.content.signatureAlgorithmsSize; if (tlsConfig->signAlgorithmsSize > 0) { uint32_t signAlgorithmsLen = tlsConfig->signAlgorithmsSize * sizeof(uint16_t); tlsConfig->signAlgorithms = (uint16_t *)BSL_SAL_Dump(clientHello->extension.content.signatureAlgorithms, signAlgorithmsLen); if (tlsConfig->signAlgorithms == NULL) { return HITLS_MEMALLOC_FAIL; } } tlsConfig->groupsSize = clientHello->extension.content.supportedGroupsSize; if (tlsConfig->groupsSize > 0) { uint32_t groupsLen = tlsConfig->groupsSize * sizeof(uint16_t); tlsConfig->groups = (uint16_t *)BSL_SAL_Dump(clientHello->extension.content.supportedGroups, groupsLen); if (tlsConfig->groups == NULL) { return HITLS_MEMALLOC_FAIL; } } tlsConfig->pointFormatsSize = clientHello->extension.content.pointFormatsSize; if (tlsConfig->pointFormatsSize > 0) { uint32_t pointFormatsLen = tlsConfig->pointFormatsSize * sizeof(uint8_t); tlsConfig->pointFormats = (uint8_t *)BSL_SAL_Dump(clientHello->extension.content.pointFormats, pointFormatsLen); if (tlsConfig->pointFormats == NULL) { return HITLS_MEMALLOC_FAIL; } } return HITLS_SUCCESS; } int32_t PackClientHelloMsg(FRAME_Msg *msg) { TLS_Ctx *tlsCtx = NewFrameTlsCtx(); if (tlsCtx == NULL) { return HITLS_MEMCPY_FAIL; } int32_t ret = GenClientHelloMandatoryCtx(tlsCtx, msg); if (ret != HITLS_SUCCESS) { goto EXIT; } // extended information ret = GenClientHelloExtensionCtx(tlsCtx, msg); if (ret != HITLS_SUCCESS) { goto EXIT; } ret = HS_PackMsg(tlsCtx, CLIENT_HELLO); if (memcpy_s(&msg->buffer[msg->len], REC_MAX_PLAIN_LENGTH, tlsCtx->hsCtx->msgBuf, tlsCtx->hsCtx->msgLen) != EOK) { return HITLS_MEMCPY_FAIL; } msg->len += tlsCtx->hsCtx->msgLen; EXIT: HITLS_Free(tlsCtx); return ret; } int32_t PackServerHelloMsg(FRAME_Msg *msg) { TLS_Ctx *tlsCtx = NewFrameTlsCtx(); if (tlsCtx == NULL) { return HITLS_MEMCPY_FAIL; } ServerHelloMsg *serverHello = &msg->body.handshakeMsg.body.serverHello; tlsCtx->negotiatedInfo.version = serverHello->version; int32_t ret = 0; ret = memcpy_s(tlsCtx->hsCtx->serverRandom, HS_RANDOM_SIZE, serverHello->randomValue, HS_RANDOM_SIZE); if (ret != EOK) { goto EXIT; } if (serverHello->sessionIdSize > 0) { // SessionId #if defined(HITLS_TLS_FEATURE_SESSION) || defined(HITLS_TLS_PROTO_TLS13) tlsCtx->hsCtx->sessionId = (uint8_t *)BSL_SAL_Dump(serverHello->sessionId, serverHello->sessionIdSize); if (tlsCtx->hsCtx->sessionId == NULL) { ret = HITLS_MEMALLOC_FAIL; goto EXIT; } tlsCtx->hsCtx->sessionIdSize = serverHello->sessionIdSize; #endif } tlsCtx->negotiatedInfo.cipherSuiteInfo.cipherSuite = serverHello->cipherSuite; tlsCtx->negotiatedInfo.isExtendedMasterSecret = serverHello->haveExtendedMasterSecret; ret = HS_PackMsg(tlsCtx, SERVER_HELLO); if (memcpy_s(&msg->buffer[msg->len], REC_MAX_PLAIN_LENGTH, tlsCtx->hsCtx->msgBuf, tlsCtx->hsCtx->msgLen) != EOK) { return HITLS_MEMCPY_FAIL; } msg->len += tlsCtx->hsCtx->msgLen; EXIT: HITLS_Free(tlsCtx); return ret; } int32_t PackCertificateMsg(FRAME_Msg *msg) { CertificateMsg *certificate = &msg->body.handshakeMsg.body.certificate; uint32_t allCertsLen = 0; // Total length of all certificates uint32_t offset = msg->len + DTLS_HS_MSG_HEADER_SIZE; // Reserved packet header // Indicates the offset of the total length of the certificate chain. uint32_t certsLenOffset = offset; offset += TEST_CERT_LEN_TAG_SIZE; // Total length of the reserved certificate chain CERT_Item *cur = certificate->cert; while (cur != NULL) { BSL_Uint24ToByte(cur->dataSize, &msg->buffer[offset]); offset += TEST_CERT_LEN_TAG_SIZE; int32_t ret = memcpy_s(&msg->buffer[offset], RECORD_BUF_LEN - offset, cur->data, cur->dataSize); if (ret != EOK) { return HITLS_MEMCPY_FAIL; } offset += cur->dataSize; allCertsLen += TEST_CERT_LEN_TAG_SIZE + cur->dataSize; cur = cur->next; } // Indicates the total length of the certificate chain. BSL_Uint24ToByte(allCertsLen, &msg->buffer[certsLenOffset]); /* Assemble the packet header. */ const uint32_t sequence = 1; const uint32_t bodyLen = TEST_CERT_LEN_TAG_SIZE + allCertsLen; PackDtlsMsgHeader(CERTIFICATE, sequence, bodyLen, &msg->buffer[msg->len]); msg->len += DTLS_HS_MSG_HEADER_SIZE + bodyLen; return HITLS_SUCCESS; } int32_t PackServerKxMsg(FRAME_Msg *msg) { ServerKeyExchangeMsg *serverKx = &msg->body.handshakeMsg.body.serverKeyExchange; uint32_t offset = msg->len + DTLS_HS_MSG_HEADER_SIZE; // Reserved packet header /* Curve Type and Curve ID */ msg->buffer[offset] = (uint8_t)(serverKx->keyEx.ecdh.ecPara.type); offset += sizeof(uint8_t); BSL_Uint16ToByte((uint16_t)(serverKx->keyEx.ecdh.ecPara.param.namedcurve), &msg->buffer[offset]); offset += sizeof(uint16_t); /* Public key length and public key content */ msg->buffer[offset] = (uint8_t)serverKx->keyEx.ecdh.pubKeySize; offset += sizeof(uint8_t); int32_t ret = memcpy_s(&msg->buffer[offset], RECORD_BUF_LEN - offset, serverKx->keyEx.ecdh.pubKey, serverKx->keyEx.ecdh.pubKeySize); if (ret != EOK) { return HITLS_MEMCPY_FAIL; } offset += serverKx->keyEx.ecdh.pubKeySize; /* signature algorithm */ BSL_Uint16ToByte(serverKx->keyEx.ecdh.signAlgorithm, &msg->buffer[offset]); offset += sizeof(uint16_t); /* Signature Length */ BSL_Uint16ToByte(serverKx->keyEx.ecdh.signSize, &msg->buffer[offset]); offset += sizeof(uint16_t); ret = memcpy_s(&msg->buffer[offset], RECORD_BUF_LEN - offset, serverKx->keyEx.ecdh.signData, serverKx->keyEx.ecdh.signSize); if (ret != EOK) { return HITLS_MEMCPY_FAIL; } offset += serverKx->keyEx.ecdh.signSize; /* Assemble the packet header. */ const uint32_t sequence = msg->body.handshakeMsg.sequence; const uint32_t bodyLen = sizeof(uint8_t) + sizeof(uint16_t) + sizeof(uint8_t) + serverKx->keyEx.ecdh.pubKeySize + sizeof(uint16_t) + sizeof(uint16_t) + serverKx->keyEx.ecdh.signSize; PackDtlsMsgHeader(SERVER_KEY_EXCHANGE, sequence, bodyLen, &msg->buffer[msg->len]); msg->len += DTLS_HS_MSG_HEADER_SIZE + bodyLen; return HITLS_SUCCESS; } int32_t PackServerHelloDoneMsg(FRAME_Msg *msg) { /* Assemble the packet header. */ const uint32_t sequence = msg->body.handshakeMsg.sequence; const uint32_t bodyLen = 0; PackDtlsMsgHeader(SERVER_HELLO_DONE, sequence, bodyLen, &msg->buffer[msg->len]); msg->len += DTLS_HS_MSG_HEADER_SIZE + bodyLen; return HITLS_SUCCESS; } int32_t PackClientKxMsg(FRAME_Msg *msg) { ClientKeyExchangeMsg *clientKx = &msg->body.handshakeMsg.body.clientKeyExchange; uint32_t offset = msg->len + DTLS_HS_MSG_HEADER_SIZE; // Reserved packet header msg->buffer[offset] = (uint8_t)clientKx->dataSize; offset += sizeof(uint8_t); int32_t ret = memcpy_s(&msg->buffer[offset], RECORD_BUF_LEN - offset, clientKx->data, clientKx->dataSize); if (ret != EOK) { return HITLS_MEMCPY_FAIL; } /* Assemble the packet header. */ const uint32_t sequence = msg->body.handshakeMsg.sequence; const uint32_t bodyLen = clientKx->dataSize + sizeof(uint8_t); PackDtlsMsgHeader(CLIENT_KEY_EXCHANGE, sequence, bodyLen, &msg->buffer[msg->len]); msg->len += DTLS_HS_MSG_HEADER_SIZE + bodyLen; return HITLS_SUCCESS; } int32_t PackFinishMsg(FRAME_Msg *msg) { TLS_Ctx *tlsCtx = NewFrameTlsCtx(); if (tlsCtx == NULL) { return HITLS_MEMCPY_FAIL; } FinishedMsg *finished = &msg->body.handshakeMsg.body.finished; int32_t ret = 0; tlsCtx->hsCtx->verifyCtx = (VerifyCtx*)BSL_SAL_Calloc(1u, sizeof(VerifyCtx)); if (tlsCtx->hsCtx->verifyCtx == NULL) { ret = HITLS_MEMALLOC_FAIL; goto EXIT; } tlsCtx->hsCtx->verifyCtx->verifyDataSize = finished->verifyDataSize; ret = memcpy_s(tlsCtx->hsCtx->verifyCtx->verifyData, MAX_SIGN_SIZE, finished->verifyData, finished->verifyDataSize); if (ret != EOK) { goto EXIT; } ret = HS_PackMsg(tlsCtx, FINISHED); if (memcpy_s(&msg->buffer[msg->len], REC_MAX_PLAIN_LENGTH, tlsCtx->hsCtx->msgBuf, tlsCtx->hsCtx->msgLen) != EOK) { return HITLS_MEMCPY_FAIL; } msg->len += tlsCtx->hsCtx->msgLen; EXIT: HITLS_Free(tlsCtx); return ret; } int32_t PackHandShakeMsg(FRAME_Msg *msg) { HS_MsgType type = msg->body.handshakeMsg.type; uint32_t ret = HITLS_SUCCESS; switch (type) { case CLIENT_HELLO: ret = PackClientHelloMsg(msg); break; case SERVER_HELLO: ret = PackServerHelloMsg(msg); break; case CERTIFICATE: ret = PackCertificateMsg(msg); break; case SERVER_KEY_EXCHANGE: ret = PackServerKxMsg(msg); break; case SERVER_HELLO_DONE: ret = PackServerHelloDoneMsg(msg); break; case CLIENT_KEY_EXCHANGE: ret = PackClientKxMsg(msg); break; case FINISHED: ret = PackFinishMsg(msg); break; default: ret = HITLS_PACK_UNSUPPORT_HANDSHAKE_MSG; } return ret; } int32_t PackCCSMsg(FRAME_Msg *msg) { FRAME_CcsMsg *ccsMsg = &msg->body.ccsMsg; uint32_t offset = msg->len; msg->buffer[offset] = ccsMsg->type; msg->len += sizeof(uint8_t); return HITLS_SUCCESS; } int32_t PackAlertMsg(FRAME_Msg *msg) { FRAME_AlertMsg *alertMsg = &msg->body.alertMsg; uint32_t offset = msg->len; msg->buffer[offset] = alertMsg->level; offset += sizeof(uint8_t); msg->buffer[offset] = alertMsg->description; msg->len += sizeof(uint8_t) + sizeof(uint8_t); return HITLS_SUCCESS; } int32_t PackAppData(FRAME_Msg *msg) { FRAME_AppMsg *appMsg = &msg->body.appMsg; uint32_t offset = msg->len; BSL_Uint32ToByte(appMsg->len, &msg->buffer[offset]); offset += sizeof(uint32_t); int32_t ret = memcpy_s(&msg->buffer[offset], RECORD_BUF_LEN - offset, appMsg->buffer, appMsg->len); if (ret != EOK) { return HITLS_MEMCPY_FAIL; } msg->len += sizeof(uint32_t) + appMsg->len; return HITLS_SUCCESS; } // Pack header int32_t PackRecordHeader(FRAME_Msg *msg) { uint32_t offset = 0; msg->buffer[offset] = msg->type; offset += sizeof(uint8_t); BSL_Uint16ToByte(msg->version, &msg->buffer[offset]); offset += sizeof(uint16_t); #ifdef HITLS_TLS_PROTO_DTLS12 if (IS_TRANSTYPE_DATAGRAM(msg->transportType)) { BSL_Uint64ToByte(msg->epochSeq, &msg->buffer[offset]); offset += sizeof(uint64_t); } #endif BSL_Uint16ToByte(msg->bodyLen, &msg->buffer[offset]); offset += sizeof(uint16_t); msg->len = offset; return HITLS_SUCCESS; } int32_t PackFrameMsg(FRAME_Msg *msg) { // Apply for an 18 KB buffer for storing the current message. msg->buffer = (uint8_t *)BSL_SAL_Calloc(1u, RECORD_BUF_LEN); if (msg->buffer == NULL) { return HITLS_MEMALLOC_FAIL; } msg->len = RECORD_BUF_LEN; // The length must be the same as the length of the applied 18 KB buffer. // pack Header PackRecordHeader(msg); // pack Body uint32_t ret = HITLS_SUCCESS; switch (msg->type) { case REC_TYPE_HANDSHAKE: ret = PackHandShakeMsg(msg); break; case REC_TYPE_CHANGE_CIPHER_SPEC: ret = PackCCSMsg(msg); break; case REC_TYPE_ALERT: ret = PackAlertMsg(msg); break; case REC_TYPE_APP: ret = PackAppData(msg); break; default: break; } return ret; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/msg/src/pack_frame_msg.c
C
unknown
15,421
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "securec.h" #include "bsl_bytes.h" #include "bsl_sal.h" #include "hitls_error.h" #include "tls.h" #include "conn_init.h" #include "hs_ctx.h" #include "parse.h" #include "conn_init.h" #include "frame_tls.h" #include "frame_msg.h" #include "parser_frame_msg.h" void SendAlertStake(const TLS_Ctx *ctx, ALERT_Level level, ALERT_Description description) { (void)ctx; (void)level; (void)description; return; } int32_t ParserRecordHeader(FRAME_Msg *frameMsg, const uint8_t *buffer, uint32_t len, uint32_t *parserLen) { (void)len; uint32_t bufOffset = 0; frameMsg->type = buffer[bufOffset]; bufOffset += sizeof(uint8_t); frameMsg->version = BSL_ByteToUint16(&buffer[bufOffset]); bufOffset += sizeof(uint16_t); #ifdef HITLS_TLS_PROTO_DTLS12 if (IS_TRANSTYPE_DATAGRAM(frameMsg->transportType)) { frameMsg->epochSeq = BSL_ByteToUint64(&buffer[bufOffset]); bufOffset += sizeof(uint64_t); } #endif frameMsg->bodyLen = BSL_ByteToUint16(&buffer[bufOffset]); bufOffset += sizeof(uint16_t); *parserLen = bufOffset; return HITLS_SUCCESS; } int32_t ParserHandShakeMsg(const FRAME_LinkObj *linkObj, FRAME_Msg *frameMsg, const uint8_t *buffer, uint32_t len, uint32_t *parserLen) { int32_t ret; HS_MsgInfo hsMsgInfo = {0}; HITLS_Ctx *sslCtx = FRAME_GetTlsCtx(linkObj); SendAlertCallback tmpAlertCallback = sslCtx->method.sendAlert; sslCtx->method.sendAlert = SendAlertStake; CONN_Init(sslCtx); ret = HS_ParseMsgHeader(sslCtx, buffer, len, &hsMsgInfo); if (ret != HITLS_SUCCESS) { sslCtx->method.sendAlert = tmpAlertCallback; return ret; } hsMsgInfo.rawMsg = buffer; ret = HS_ParseMsg(sslCtx, &hsMsgInfo, &frameMsg->body.handshakeMsg); if (ret != HITLS_SUCCESS) { sslCtx->method.sendAlert = tmpAlertCallback; return ret; } sslCtx->method.sendAlert = tmpAlertCallback; *parserLen += hsMsgInfo.length; return HITLS_SUCCESS; } int32_t ParserCCSMsg(FRAME_Msg *frameMsg, const uint8_t *buffer, uint32_t len, uint32_t *parserLen) { (void)len; frameMsg->body.ccsMsg.type = buffer[0]; *parserLen += sizeof(uint8_t); return HITLS_SUCCESS; } int32_t ParserAlertMsg(FRAME_Msg *frameMsg, const uint8_t *buffer, uint32_t len, uint32_t *parserLen) { (void)len; uint32_t bufOffset = 0; frameMsg->body.alertMsg.level = buffer[bufOffset]; bufOffset += sizeof(uint8_t); frameMsg->body.alertMsg.description = buffer[bufOffset]; bufOffset += sizeof(uint8_t); *parserLen += bufOffset; return HITLS_SUCCESS; } int32_t ParserAppMsg(FRAME_Msg *frameMsg, const uint8_t *buffer, uint32_t len, uint32_t *parserLen) { (void)len; uint32_t bufOffset = 0; uint32_t userDataLen = BSL_ByteToUint32(&buffer[bufOffset]); frameMsg->body.appMsg.len = userDataLen; bufOffset += sizeof(uint32_t); BSL_SAL_FREE(frameMsg->body.appMsg.buffer); frameMsg->body.appMsg.buffer = BSL_SAL_Dump(&buffer[bufOffset], userDataLen); if (frameMsg->body.appMsg.buffer == NULL) { return HITLS_MEMALLOC_FAIL; } bufOffset += userDataLen; *parserLen += bufOffset; return HITLS_SUCCESS; } int32_t ParserRecordBody(const FRAME_LinkObj *linkObj, FRAME_Msg *frameMsg, const uint8_t *buffer, uint32_t len, uint32_t *parserLen) { switch (frameMsg->type) { case REC_TYPE_HANDSHAKE: return ParserHandShakeMsg(linkObj, frameMsg, buffer, len, parserLen); case REC_TYPE_CHANGE_CIPHER_SPEC: return ParserCCSMsg(frameMsg, buffer, len, parserLen); case REC_TYPE_ALERT: return ParserAlertMsg(frameMsg, buffer, len, parserLen); case REC_TYPE_APP: return ParserAppMsg(frameMsg, buffer, len, parserLen); default: break; } return HITLS_SUCCESS; } int32_t ParserTotalRecord(const FRAME_LinkObj *linkObj, FRAME_Msg *frameMsg, const uint8_t *buffer, uint32_t len, uint32_t *parserLen) { int32_t ret = ParserRecordHeader(frameMsg, buffer, len, parserLen); if (ret != HITLS_SUCCESS) { return ret; } return ParserRecordBody(linkObj, frameMsg, &buffer[*parserLen], len - *parserLen, parserLen); } void CleanRecordBody(FRAME_Msg *frameMsg) { if (frameMsg->type == REC_TYPE_HANDSHAKE) { HS_CleanMsg(&frameMsg->body.handshakeMsg); } else if (frameMsg->type == REC_TYPE_APP) { BSL_SAL_FREE(frameMsg->body.appMsg.buffer); } BSL_SAL_FREE(frameMsg->buffer); }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/msg/src/parser_frame_msg.c
C
unknown
5,078
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HANDLE_CMD_H #define HANDLE_CMD_H #include <stdint.h> #include "hlt_type.h" #include "channel_res.h" #ifdef __cplusplus extern "C" { #endif #define MAX_CMD_ID_LEN (15) #define MAX_CMD_FUNCID_LEN (64) #define MAX_CMD_PARAS_NUM (100) typedef struct { uint8_t parasNum; char id[MAX_CMD_ID_LEN]; char funcId[MAX_CMD_FUNCID_LEN]; char paras[MAX_CMD_PARAS_NUM][CONTROL_CHANNEL_MAX_MSG_LEN]; char result[CONTROL_CHANNEL_MAX_MSG_LEN]; } CmdData; /** * @brief Expected result value */ int ExpectResult(CmdData *expectCmdData); /** * @brief Waiting for the result of the peer end */ int WaitResultFromPeer(CmdData *expectCmdData); /** * @brief Resolve instructions from a string */ int ParseCmdFromStr(char *str, CmdData *cmdData); /** * @brief Parse the instruction from the buffer. */ int ParseCmdFromBuf(ControlChannelBuf *dataBuf, CmdData *cmdData); /** * @brief Execute the corresponding command. */ int ExecuteCmd(CmdData *cmdData); /** * @brief Obtain the CTX configuration content from the character string parsing. */ int ParseCtxConfigFromString(char (*string)[CONTROL_CHANNEL_MAX_MSG_LEN], HLT_Ctx_Config *ctxConfig); #ifdef __cplusplus } #endif #endif // HANDLE_CMD_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/process/include/handle_cmd.h
C
unknown
1,759
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef PROCESS_H #define PROCESS_H #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include "hlt_type.h" #ifdef __cplusplus extern "C" { #endif #define DOMAIN_PATH_LEN (128) #define TLS_RES_MAX_NUM (64) typedef struct ProcessSt { TLS_TYPE tlsType; // Identifies whether the HiTLS interface is used. char srcDomainPath[DOMAIN_PATH_LEN]; char peerDomainPath[DOMAIN_PATH_LEN]; // This field is used only by remote processes. int controlChannelFd; // This field is used only by the local process. int remoteFlag; // Indicates whether the process is a remote process. The value 1 indicates a remote process. int connFd; // FD used by the TLS link int connType; // Enumerated value of HILT_TransportType, which is the communication protocol type used by the // TLS link. int connPort; struct sockaddr_in sockAddr; void* tlsResArray[TLS_RES_MAX_NUM]; // Stores ctx SSL resources. int tlsResNum; // Number of created TLS resources void* hltTlsResArray[TLS_RES_MAX_NUM]; // Stores the HLT_Tls_Res resource. This resource is used only // by the local process. int hltTlsResNum; // Number of created HLT_Tls_Res resources. } Process; /** * @brief Initializes the global table used to represent command IDs. */ void InitCmdIndex(void); /** * @brief Initializing Process Resources */ int InitProcess(void); /** * @brief Obtaining Process Resources */ Process *GetProcess(void); /** * @brief Obtain the process from the linked list. */ Process *GetProcessFromList(void); /** * @brief Release the linked list of the storage process. */ void FreeProcessResList(void); /** * @brief Release process resources. */ void FreeProcess(void); #ifdef __cplusplus } #endif #endif // PROCESS_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/process/include/process.h
C
unknown
2,364
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <stdbool.h> #include <semaphore.h> #include "hlt_type.h" #include "securec.h" #include "logger.h" #include "rpc_func.h" #include "channel_res.h" #include "handle_cmd.h" #define SUCCESS 0 #define ERROR (-1) #define ASSERT_RETURN(condition, log) \ do { \ if (!(condition)) { \ LOG_ERROR(log); \ return ERROR; \ } \ } while (0) int ExpectResult(CmdData *expectCmdData) { int ret, id; char *endPtr = NULL; CmdData cmdData; ControlChannelRes *channelRes; channelRes = GetControlChannelRes(); OsLock(channelRes->rcvBufferLock); id = (int)strtol(expectCmdData->id, &endPtr, 0) % MAX_RCV_BUFFER_NUM; // Check whether the corresponding buffer contains content. if (strlen(channelRes->rcvBuffer[id]) == 0) { OsUnLock(channelRes->rcvBufferLock); return ERROR; } // Parsing the CMD ret = ParseCmdFromStr(channelRes->rcvBuffer[id], &cmdData); if (ret != SUCCESS) { LOG_ERROR("ParseCmdFromStr ERROR"); OsUnLock(channelRes->rcvBufferLock); return ERROR; } if ((strncmp(expectCmdData->id, cmdData.id, strlen(cmdData.id)) == 0) && (strncmp(expectCmdData->funcId, cmdData.funcId, strlen(cmdData.funcId)) == 0)) { ret = memcpy_s(expectCmdData->paras, sizeof(expectCmdData->paras), cmdData.paras, sizeof(cmdData.paras)); if (ret != EOK) { LOG_ERROR("memcpy_s ERROR"); OsUnLock(channelRes->rcvBufferLock); return ERROR; } (void)memset_s(channelRes->rcvBuffer[id], CONTROL_CHANNEL_MAX_MSG_LEN, 0, CONTROL_CHANNEL_MAX_MSG_LEN); OsUnLock(channelRes->rcvBufferLock); return SUCCESS; } OsUnLock(channelRes->rcvBufferLock); LOG_ERROR("strncmp ERROR [expectCmdData->id=%s, cmdData.id = %s, expectCmdData->funcId = %s, cmdData.funcId = %s]", expectCmdData->id, cmdData.id, expectCmdData->funcId, cmdData.funcId); return ERROR; } int WaitResultFromPeer(CmdData *expectCmdData) { int ret; int timeout = TIME_OUT_SEC; if (getenv("SSL_TIMEOUT") != NULL) { timeout = atoi(getenv("SSL_TIMEOUT")); } timeout *= 2; time_t start = time(NULL); do { ret = ExpectResult(expectCmdData); usleep(1000); // Waiting for 1000 subtleties } while ((ret != SUCCESS) && (time(NULL) - start < timeout)); ASSERT_RETURN(ret == SUCCESS, "ExpectResult Error"); return SUCCESS; } int ParseCmdFromStr(char *str, CmdData *cmdData) { int ret, count, strBufLen; char *token = NULL; char *rest = NULL; char *strBuf = NULL; (void)memset_s(cmdData, sizeof(CmdData), 0, sizeof(CmdData)); strBufLen = strlen(str) + 1; strBuf = (char*)malloc(strBufLen); ASSERT_RETURN(strBuf != NULL, "Malloc Error"); (void)memset_s(strBuf, strBufLen, 0, strBufLen); ret = memcpy_s(strBuf, strBufLen, str, strlen(str)); if (ret != EOK) { LOG_ERROR("memcpy_s Error"); goto ERR; } /* The command message structure is as follows: ID | FUNC | PARAS1 | PARAS2 |...... Fields are separated by vertical bars (|). */ // Get ID token = strtok_s(strBuf, "|", &rest); ret = strcpy_s(cmdData->id, sizeof(cmdData->id), token); // Get Id if (ret != EOK) { LOG_ERROR("strcpy_s Error"); goto ERR; } // Get FUNC. token = strtok_s(NULL, "|", &rest); ret = strcpy_s(cmdData->funcId, sizeof(cmdData->funcId), token); // Get FunId if (ret != EOK) { LOG_ERROR("strcpy_s Error"); goto ERR; } // Obtaining Parameters token = strtok_s(NULL, "|", &rest); count = 0; for (; token != NULL; token = strtok_s(NULL, "|", &rest)) { // Maximum length of argument is CONTROL_CHANNEL_MAX_MSG_LEN ret = strcpy_s(cmdData->paras[count], sizeof(cmdData->paras[0]), token); int offset = 0; while (rest[offset] == '|') { count++; offset++; } count++; if (ret != EOK) { break; } } if (ret != EOK) { LOG_ERROR("strcpy_s error"); goto ERR; } cmdData->parasNum = count; free(strBuf); return SUCCESS; ERR: free(strBuf); return ERROR; } int ParseCmdFromBuf(ControlChannelBuf *dataBuf, CmdData *cmdData) { return ParseCmdFromStr(dataBuf->data, cmdData); } int ExecuteCmd(CmdData *cmdData) { int ret; RpcFunList *rcpFuncList = GetRpcFuncList(); int funcNum = GetRpcFuncNum(); ret = ERROR; for (int i = 0; i < funcNum; i++) { if (strncmp(rcpFuncList[i].funcId, cmdData->funcId, strlen(cmdData->funcId)) == 0) { ret = rcpFuncList[i].hfunc(cmdData); return ret; } } LOG_ERROR("Not Find FuncId"); (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, ERROR); ASSERT_RETURN(ret > 0, "sprintf_s Error"); return ret; } int ParseCtxConfigFromString(char (*string)[CONTROL_CHANNEL_MAX_MSG_LEN], HLT_Ctx_Config *ctxConfig) { int ret; /* The message structure is as follows: minVersion | maxVersion |cipherSuites |CA |...... Fields are separated by vertical bars (|). */ int index = 1; // minimum version number // The first parameter indicates the minimum version number. ctxConfig->minVersion = (int)strtol(string[index++], NULL, 10); LOG_DEBUG("Remote Process Set Ctx minVersion is %u", ctxConfig->minVersion); // Maximum version number // The second parameter indicates the maximum version number. ctxConfig->maxVersion = (int)strtol(string[index++], NULL, 10); LOG_DEBUG("Remote Process Set Ctx maxVersion is %u", ctxConfig->maxVersion); // Obtaining the Algorithm Suite // The third parameter indicates the algorithm suite. ret = strcpy_s(ctxConfig->cipherSuites, sizeof(ctxConfig->cipherSuites), string[index++]); ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx cipherSuites is %s", ctxConfig->cipherSuites); // The fourth parameter indicates the algorithm suite. ret = strcpy_s(ctxConfig->tls13CipherSuites, sizeof(ctxConfig->tls13CipherSuites), string[index++]); ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx tls13cipherSuites is %s", ctxConfig->tls13CipherSuites); // ECC Point Format Configuration for Asymmetric Algorithms // The fifth parameter indicates the dot format. ret = strcpy_s(ctxConfig->pointFormats, sizeof(ctxConfig->pointFormats), string[index++]); ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx pointFormats is %s", ctxConfig->pointFormats); // Obtaining a Group // The sixth parameter indicates a group. ret = strcpy_s(ctxConfig->groups, sizeof(ctxConfig->groups), string[index++]); ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx groups is %s", ctxConfig->groups); // Obtaining a Signature // The seventh parameter indicates the signature. ret = strcpy_s(ctxConfig->signAlgorithms, sizeof(ctxConfig->signAlgorithms), string[index++]); ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx signAlgorithms is %s", ctxConfig->signAlgorithms); // Whether to support renegotiation // The eighth parameter indicates whether renegotiation is supported. ctxConfig->isSupportRenegotiation = (((int)strtol(string[index++], NULL, 10)) > 0) ? true : false; LOG_DEBUG("Remote Process Set Ctx isSupportRenegotiation is %d", ctxConfig->isSupportRenegotiation); // Indicates whether to verify the client. // The tenth parameter indicates whether to verify the client. ctxConfig->isSupportClientVerify = (((int)strtol(string[index++], NULL, 10)) > 0) ? true : false; LOG_DEBUG("Remote Process Set Ctx isSupportClientVerify is %d", ctxConfig->isSupportClientVerify); // Indicates whether the client can send an empty certificate chain. // The eleventh parameter indicates whether the client can send an empty certificate chain. ctxConfig->isSupportNoClientCert = (((int)strtol(string[index++], NULL, 10)) > 0) ? true : false; LOG_DEBUG("Remote Process Set Ctx isSupportNoClientCert is %d", ctxConfig->isSupportNoClientCert); // Indicates whether extended master keys are supported. // The twelfth parameter indicates whether the extended master key is supported. ctxConfig->isSupportExtendMasterSecret = (((int)strtol(string[index++], NULL, 10)) > 0) ? true : false; LOG_DEBUG("Remote Process Set Ctx isSupportExtendMasterSecret is %d", ctxConfig->isSupportExtendMasterSecret); // device certificate // The thirteenth parameter indicates the location of the device certificate. ret = strcpy_s(ctxConfig->eeCert, sizeof(ctxConfig->eeCert), string[index++]); ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx EE is %s", ctxConfig->eeCert); // private key // The fourteenth parameter indicates the location of the private key. ret = strcpy_s(ctxConfig->privKey, sizeof(ctxConfig->privKey), string[index++]); ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx privKey is %s", ctxConfig->privKey); // private key password // The fifteenth parameter indicates the password of the private key. ret = strcpy_s(ctxConfig->password, sizeof(ctxConfig->password), string[index++]); ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx password is %s", ctxConfig->password); // CA certificate // The 16th parameter indicates the CA certificate. ret = strcpy_s(ctxConfig->caCert, sizeof(ctxConfig->caCert), string[index++]); ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx caCert is %s", ctxConfig->caCert); // Chain certificate // The 17th parameter indicates the certificate chain. ret = strcpy_s(ctxConfig->chainCert, sizeof(ctxConfig->chainCert), string[index++]); ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx chainCert is %s", ctxConfig->chainCert); // signature certificate LOG_DEBUG("Remote Process Set Ctx signCert is %s", string[index]); // The eighteenth parameter indicates the position of the signature certificate. ret = strcpy_s(ctxConfig->signCert, sizeof(ctxConfig->signCert), string[index++]); ASSERT_RETURN(ret == EOK, "strcpy_s Error"); // private key for signature LOG_DEBUG("Remote Process Set Ctx signPrivKey is %s", string[index]); // The 19th parameter indicates the location of the signature private key. ret = strcpy_s(ctxConfig->signPrivKey, sizeof(ctxConfig->signPrivKey), string[index++]); ASSERT_RETURN(ret == EOK, "strcpy_s Error"); // psk ret = strcpy_s(ctxConfig->psk, sizeof(ctxConfig->psk), string[index++]); // 21st parameter psk ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx psk is %s", ctxConfig->psk); // Indicates whether to support session tickets. // Indicates whether to enable the sessionTicket function. The value is a decimal number. ctxConfig->isSupportSessionTicket = (int)strtol(string[index++], NULL, 10); LOG_DEBUG("Remote Process Set Ctx isSupportSessionTicket is %d", ctxConfig->isSupportSessionTicket); // Setting the Session Storage Mode // The 23rd parameter is used to set the session storage mode. The value is a decimal number. ctxConfig->setSessionCache = (int)strtol(string[index++], NULL, 10); LOG_DEBUG("Remote Process Set Ctx SessionCache is %d", ctxConfig->setSessionCache); // Setting the ticket key cb // 24th parameter ticket key cb ret = strcpy_s(ctxConfig->ticketKeyCb, sizeof(ctxConfig->ticketKeyCb), string[index++]); ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx ticketKeyCb is %s", ctxConfig->ticketKeyCb); // Indicates whether isFlightTransmitEnable is supported. The 25th parameter indicates whether to send handshake // messages by flight. The value is converted into a decimal number. ctxConfig->isFlightTransmitEnable = (((int)strtol(string[index++], NULL, 10)) > 0) ? true : false; LOG_DEBUG("Remote Process Set Ctx isFlightTransmitEnable is %d", ctxConfig->isFlightTransmitEnable); // Setting the server name ret = strcpy_s(ctxConfig->serverName, sizeof(ctxConfig->serverName), string[index++]); // Parameter 26 ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx ServerName is %s", ctxConfig->serverName); // Setting the server name cb // 27th parameter server name cb ret = strcpy_s(ctxConfig->sniDealCb, sizeof(ctxConfig->sniDealCb), string[index++]); ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx ServerNameCb is %s", ctxConfig->sniDealCb); // Setting the server name arg // 28th parameter server name arg cb ret = strcpy_s(ctxConfig->sniArg, sizeof(ctxConfig->sniArg), string[index++]); ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx ServerNameArg is %s", ctxConfig->sniArg); // Setting the ALPN ret = strcpy_s(ctxConfig->alpnList, sizeof(ctxConfig->alpnList), string[index++]); // 29th parameter ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx alpnList is %s", ctxConfig->alpnList); // Setting the ALPN cb ret = strcpy_s(ctxConfig->alpnSelectCb, sizeof(ctxConfig->alpnSelectCb), string[index++]); // 30th parameter ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx alpnSelectCb is %s", ctxConfig->alpnSelectCb); // Setting the ALPN data ret = strcpy_s(ctxConfig->alpnUserData, sizeof(ctxConfig->alpnUserData), string[index++]); // 31th parameter ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx alpnUserData is %s", ctxConfig->alpnUserData); // Sets the security level. The parameter indicates that the security strength of the key meets the security level // requirements and is converted into a decimal number. ctxConfig->securitylevel = (int)strtol(string[index++], NULL, 10); LOG_DEBUG("Remote Process Set Ctx SecurityLevel is %d", ctxConfig->securitylevel); // Indicates whether the DH key length follows the certificate. The parameter indicates whether the DH key length // follows the certificate, which is converted into a decimal number. ctxConfig->isSupportDhAuto = (int)strtol(string[index++], NULL, 10); LOG_DEBUG("Remote Process Set Ctx issupportDhauto is %d", ctxConfig->isSupportDhAuto); // Sets the TLS1.3 key exchange mode. The parameter indicates the TLS1.3 key exchange mode, // which is converted into a decimal number. ctxConfig->keyExchMode = (int)strtol(string[index++], NULL, 10); LOG_DEBUG("Remote Process Set Ctx keyExchMode is %u", ctxConfig->keyExchMode); // The parameter indicates the SupportType callback type, which converts characters into decimal numbers. ctxConfig->SupportType = (int)strtol(string[index++], NULL, 10); LOG_DEBUG("Remote Process Set Ctx SupportType is %d", ctxConfig->SupportType); ctxConfig->isSupportPostHandshakeAuth = (((int)strtol(string[index++], NULL, 10)) > 0) ? true : false; ctxConfig->readAhead = (int)strtol(string[index++], NULL, 10); LOG_DEBUG("Remote Process Set Ctx readAhead is %u", ctxConfig->readAhead); // Sets whether to verify the keyusage in the certificate. The keyusage is converted into a decimal number. ctxConfig->needCheckKeyUsage = (((int)strtol(string[index++], NULL, 10)) > 0) ? true : false; LOG_DEBUG("Remote Process Set Ctx needCheckKeyUsage is %d", ctxConfig->needCheckKeyUsage); // Set whether to continue the handshake when the verification of peer certificate fails ctxConfig->isSupportVerifyNone = (((int)strtol(string[index++], NULL, 10)) > 0) ? true : false; LOG_DEBUG("Remote Process Set Ctx isSupportVerifyNone is %d", ctxConfig->isSupportVerifyNone); // Whether allow a renegotiation initiated by the client ctxConfig->allowClientRenegotiate = (((int)strtol(string[index++], NULL, 10)) > 0) ? true : false; LOG_DEBUG("Remote Process Set Ctx allowClientRenegotiate is %d", ctxConfig->allowClientRenegotiate); // Set the empty record number. ctxConfig->emptyRecordsNum = (int)strtol(string[index++], NULL, 10); LOG_DEBUG("Remote Process Set Ctx emptyRecordsNum is %u", ctxConfig->emptyRecordsNum); // Whether allow legacy renegotiation ctxConfig->allowLegacyRenegotiate = (((int)strtol(string[index++], NULL, 10)) > 0) ? true : false; LOG_DEBUG("Remote Process Set Ctx allowLegacyRenegotiate is %d", ctxConfig->allowLegacyRenegotiate); // Indicates whether encrypt then mac are supported. ctxConfig->isEncryptThenMac = (((int)strtol(string[index++], NULL, 10)) > 0) ? true : false; LOG_DEBUG("Remote Process Set Ctx isEncryptThenMac is %d", ctxConfig->isEncryptThenMac); // set the features supported by modesupport, The value is a decimal number. ctxConfig->modeSupport = (int)strtol(string[index++], NULL, 10); LOG_DEBUG("Remote Process Set Ctx modeSupport is %d", ctxConfig->modeSupport); ctxConfig->isMiddleBoxCompat = (int)strtol(string[index++], NULL, 10); LOG_DEBUG("Remote Process Set Ctx MiddleBoxCompat is %d", ctxConfig->isMiddleBoxCompat); // set the attrName ret = strcpy_s(ctxConfig->attrName, sizeof(ctxConfig->attrName), string[index++]); ASSERT_RETURN(ret == EOK, "strcpy_s Error"); LOG_DEBUG("Remote Process Set Ctx attrName is %s", ctxConfig->attrName); // Setting the info cb ctxConfig->infoCb = NULL; // The pointer cannot be transferred. Set this parameter to null. return SUCCESS; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/process/src/handle_cmd.c
C
unknown
18,808
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <unistd.h> #include <sys/time.h> #include <sys/syscall.h> #include <libgen.h> #include "lock.h" #include "hlt.h" #include "logger.h" #include "tls_res.h" #include "channel_res.h" #include "control_channel.h" #include "rpc_func.h" #include "hitls.h" #include "hitls_config.h" #include "process.h" #define SUCCESS 0 #define ERROR (-1) #define CMD_MAX_LEN (512) #define DOMAIN_PATH_LEN (128) #define START_PROCESS_CMD "./process %d ./%s_%d ./%s %d > ./%s_%d.log &" #define ASSERT_RETURN(condition, log) \ do { \ if (!(condition)) { \ LOG_ERROR(log); \ return ERROR; \ } \ } while (0) typedef struct ProcessRes { Process *process; struct ProcessRes *next; } ProcessRes; typedef struct ProcessList { ProcessRes *processRes; uint8_t num; } ProcessList; static ProcessList g_processList; static Process *g_process = NULL; static int g_processIndex = 0; // Initialization process linked list, which is used only in the Local Process process and is used to save the Remote // Process. int InitProcessList(void) { g_processList.processRes = (ProcessRes*)malloc(sizeof(ProcessRes)); ASSERT_RETURN(g_processList.processRes != NULL, "Malloc ProcessRes Error"); memset_s(g_processList.processRes, sizeof(ProcessRes), 0, sizeof(ProcessRes)); g_processList.num = 0; return SUCCESS; } // Inserts a process to a linked list. Currently, only remote processes are stored. int InsertProcessToList(Process *tmpProcess) { ProcessRes *frontProcessRes = g_processList.processRes; ProcessRes *nextProcessRes = NULL; ProcessRes *tmpProcessRes; ASSERT_RETURN(tmpProcess != NULL, "TmpProcess is NULL"); // Find the last process resource. The obtained frontProcessRes is the last process resource. nextProcessRes = frontProcessRes->next; while (nextProcessRes != NULL) { frontProcessRes = nextProcessRes; nextProcessRes = frontProcessRes->next; } // Applying for Process Resources tmpProcessRes = (ProcessRes*)malloc(sizeof(ProcessRes)); ASSERT_RETURN(tmpProcessRes != NULL, "Malloc ProcessRes Error"); tmpProcessRes->process = tmpProcess; tmpProcessRes->next = NULL; frontProcessRes->next = tmpProcessRes; g_processList.num++; return SUCCESS; } Process *GetProcessFromList(void) { ProcessRes *headProcessRes = g_processList.processRes; ProcessRes *firstProcessRes, *nextProcessRes; Process* resultProcess; if (g_processList.num == 0) { return NULL; } // Find the last element firstProcessRes = headProcessRes->next; nextProcessRes = firstProcessRes; while ((nextProcessRes != NULL) && (nextProcessRes->next != NULL)) { firstProcessRes = nextProcessRes; nextProcessRes = firstProcessRes->next; } resultProcess = firstProcessRes->process; firstProcessRes->next = NULL; g_processList.num--; return resultProcess; } void FreeProcessResList(void) { ProcessRes *frontProcessRes = g_processList.processRes; ProcessRes *nextProcessRes = NULL; ProcessRes *tmpProcessRes = NULL; nextProcessRes = frontProcessRes->next; while (nextProcessRes != NULL) { tmpProcessRes = nextProcessRes->next; free(nextProcessRes); nextProcessRes = tmpProcessRes; } free(g_processList.processRes); memset_s(&g_processList, sizeof(g_processList), 0, sizeof(g_processList)); return; } int InitProcess(void) { g_process= (Process*)malloc(sizeof(Process)); ASSERT_RETURN(g_process != NULL, "Malloc ProcessRes Error"); (void)memset_s(g_process, sizeof(Process), 0, sizeof(Process)); return SUCCESS; } Process *GetProcess(void) { return g_process; } void FreeProcess(void) { if (g_process != NULL) { free(g_process); g_process = NULL; } return; } void MonitorControlChannel(void) { fd_set fdSet; char *endPtr = NULL; int ret, fdMax, index; ControlChannelBuf dataBuf; ControlChannelRes *channelInfo; channelInfo = GetControlChannelRes(); int32_t fd = channelInfo->sockFd; fdMax = fd + 1; struct timeval stTimeOut = {0}; while (!channelInfo->isExit) { stTimeOut.tv_sec = 1; stTimeOut.tv_usec = 0; FD_ZERO(&fdSet); FD_SET(fd, &fdSet); ret = select(fdMax, &fdSet, NULL, NULL, &stTimeOut); if (ret <= 0) { LOG_ERROR("Select Error"); continue; } if (FD_ISSET(fd, &fdSet)) { ret = ControlChannelRead(fd, &dataBuf); if (ret != SUCCESS) { LOG_ERROR("ControlChannelRead Error"); continue; } CmdData cmdData = {0}; ret = ParseCmdFromStr(dataBuf.data, &cmdData); index = (int)strtol(cmdData.id, &endPtr, 0) % MAX_RCV_BUFFER_NUM; ret = PushResultToChannelIdBuffer(channelInfo, dataBuf.data, index); if (ret != SUCCESS) { LOG_ERROR("PushResultToChannelRcvBuffer Error"); return; } LOG_DEBUG("Local Process Rcv is %s", dataBuf.data); } else { LOG_ERROR("FD_ISSET Error"); } } } HLT_Process *InitSrcProcess(TLS_TYPE tlsType, char *srcDomainPath) { int ret, srcPathLen; ControlChannelRes *channelInfo; char srcControlDomainPath[DOMAIN_PATH_LEN] = {0}; HLT_Process *process; // Check whether the call is the first time. process = GetProcess(); if (process != NULL) { LOG_ERROR("Repeat Init LocalProcess Is Not Support"); return NULL; } // The printf output buffer is not set. setbuf(stdout, NULL); // Initializes the command statistics global variable, which is required only by the local process. InitCmdIndex(); srcPathLen = strlen(srcDomainPath); if (srcPathLen == 0) { LOG_ERROR("srcDomainPath is NULL"); return NULL; } ret = sprintf_s(srcControlDomainPath, DOMAIN_PATH_LEN, "%s.%u.sock", basename(srcDomainPath), getpid()); ret = InitProcess(); if (ret != SUCCESS) { LOG_ERROR("InitProcess Error"); return NULL; } process = GetProcess(); if (HLT_LibraryInit(tlsType) != SUCCESS) { LOG_ERROR("HLT_TlsRegCallback ERROR is %d", ret); goto ERR; } // Initialize the process resource linked list, which is used to store remote process resources. ret = InitProcessList(); if (ret != SUCCESS) { LOG_ERROR("InitProcessList ERROR"); goto ERR; } // Initializes the CTX SSL resource linked list. ret = InitTlsResList(); if (ret != SUCCESS) { LOG_ERROR("InitTlsResList ERROR"); goto ERR; } // Initialize the control link. ret = InitControlChannelRes(srcControlDomainPath, strlen(srcControlDomainPath), NULL, 0); if (ret != SUCCESS) { LOG_ERROR("InitControlChannelRes ERROR"); goto ERR; } channelInfo = GetControlChannelRes(); // Create control link UDP domain socket ret = ControlChannelInit(channelInfo); if (ret != SUCCESS) { LOG_ERROR("ControlChannelInit ERROR"); goto ERR; } // Start a thread to listen to the control link. The link is used to receive the results returned by other processes pthread_t tId; channelInfo->isExit = false; if (pthread_create(&tId, NULL, (void*)MonitorControlChannel, NULL) != 0) { LOG_ERROR("Create MonitorControlChannel Thread Error ..."); goto ERR; } channelInfo->tid = tId; // Populate Process Information process->tlsType = tlsType; process->controlChannelFd = channelInfo->sockFd; process->remoteFlag = 0; process->tlsResNum = 0; process->hltTlsResNum = 0; process->connType = NONE_TYPE; process->connFd = 0; ret = memcpy_s(process->srcDomainPath, DOMAIN_PATH_LEN, srcControlDomainPath, strlen(srcControlDomainPath)); if (ret != EOK) { LOG_ERROR("memcpy_s process->srcDomainPath ERROR"); goto ERR; } LOG_DEBUG("Init Local Process Successful"); return (HLT_Process*)process; ERR: free(process); return NULL; } HLT_Process *InitPeerProcess(TLS_TYPE tlsType, HILT_TransportType connType, int port, bool isBlock) { // peerDomainPath address, which is the IP address of the monitoring process. // Creating a Process int ret, peerPathLen, tryNum; char startCmd[CMD_MAX_LEN] = {0}; HLT_Process *localProcess; HLT_Process *process = NULL; localProcess = GetProcess(); if (localProcess == NULL) { LOG_ERROR("Must Call HLT_InitLocalProcess First"); return NULL; } peerPathLen = strlen(localProcess->srcDomainPath); if (peerPathLen == 0) { LOG_ERROR("peerDomainPath is NULL"); return NULL; } process = (HLT_Process*)malloc(sizeof(HLT_Process)); if (process == NULL) { LOG_ERROR("Malloc Process is NULL"); return NULL; } (void)memset_s(process, sizeof(HLT_Process), 0, sizeof(HLT_Process)); pid_t localpid = getpid(); ret = sprintf_s(startCmd, CMD_MAX_LEN, START_PROCESS_CMD, tlsType, localProcess->srcDomainPath, g_processIndex, localProcess->srcDomainPath, localpid, localProcess->srcDomainPath, g_processIndex); if (ret == 0) { LOG_ERROR("sprintf_s Error"); free(process); return NULL; } LOG_DEBUG("Exect Cmd is %s", startCmd); ret = system(startCmd); if (ret == ERROR) { LOG_ERROR("System Error"); free(process); return NULL; } // After the remote process is started successfully, the remote process is stored in the linked list. InsertProcessToList(process); // The message is received, indicating that the peer end is in the receiveable state. CmdData expectCmdData = {0}; (void)sprintf_s(expectCmdData.id, sizeof(expectCmdData.id), "0"); (void)sprintf_s(expectCmdData.funcId, sizeof(expectCmdData.funcId), "HEART"); tryNum = 0; do { ret = WaitResultFromPeer(&expectCmdData); tryNum++; } while ((ret == ERROR) && (tryNum < 2)); // Retry once if (ret == ERROR) { LOG_ERROR("WaitResultFromPeer Error"); goto ERR; } // Populate Process Information process->connType = NONE_TYPE; process->connFd = 0; process->tlsType = tlsType; process->remoteFlag = 1; ret = sprintf_s(process->srcDomainPath, DOMAIN_PATH_LEN, "%s_%d", localProcess->srcDomainPath, g_processIndex); if (ret <= 0) { LOG_ERROR("sprintf_s Error"); goto ERR; } // Creating a Data Link if (connType != NONE_TYPE) { DataChannelParam channelParam; HLT_FD sockFd = {0}; channelParam.port = port; channelParam.type = connType; channelParam.isBlock = isBlock; // The SCTP link is set to non-block. Otherwise, the SCTP link may be suspended. sockFd = HLT_CreateDataChannel(process, localProcess, channelParam); localProcess->connType = connType; localProcess->connFd = sockFd.peerFd; localProcess->sockAddr = sockFd.sockAddr; process->connType = connType; process->connFd = sockFd.srcFd; process->connPort = sockFd.connPort; if ((sockFd.srcFd <= 0) || (sockFd.peerFd <= 0)) { LOG_ERROR("Create CHANNEL ERROR"); goto ERR; } } g_processIndex++; return (HLT_Process*)process; ERR: // You do not need to release the process. If you can go to this point, // the process is successfully created and inserted into the table. // The process resource is released in the HLT_FreeAllProcess function. // If the remote process is released in advance, the remote process may be successfully started but cannot be exited g_processIndex++; return NULL; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/process/src/process.c
C
unknown
12,643
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CHANNEL_RES_H #define CHANNEL_RES_H #include <stdio.h> #include <stdint.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <stdbool.h> #include <fcntl.h> #include "lock.h" #ifdef __cplusplus extern "C" { #endif #define CONTROL_CHANNEL_MAX_MSG_LEN (20 * 1024) #define DOMAIN_PATH_LEN (128) #define MAX_SEND_BUFFER_NUM (100) #define MAX_RCV_BUFFER_NUM (100) typedef struct { uint8_t *data; uint32_t dataLen; } DataBuf; typedef struct { char data[CONTROL_CHANNEL_MAX_MSG_LEN]; uint32_t dataLen; } ControlChannelBuf; typedef struct { char srcDomainPath[DOMAIN_PATH_LEN]; char peerDomainPath[DOMAIN_PATH_LEN]; struct sockaddr_un srcAddr; struct sockaddr_un peerAddr; int32_t sockFd; char sendBuffer[MAX_SEND_BUFFER_NUM][CONTROL_CHANNEL_MAX_MSG_LEN]; char rcvBuffer[MAX_RCV_BUFFER_NUM][CONTROL_CHANNEL_MAX_MSG_LEN]; uint8_t sendBufferNum; Lock *sendBufferLock; uint8_t rcvBufferNum; Lock *rcvBufferLock; pthread_t tid; bool isExit; } ControlChannelRes; /** * @brief Control Link Resource Initialization */ int InitControlChannelRes(char *srcDomainPath, int srcDomainPathLen, char *peerDomainPath, int peerDomainPathLen); /** * @brief Release control link resources. */ void FreeControlChannelRes(void); /** * @brief Obtaining Control Link Resources */ ControlChannelRes* GetControlChannelRes(void); /** * @brief Writes data to the control link */ int PushResultToChannelSendBuffer(ControlChannelRes *channelInfo, char *result); /** * @brief Read data from the control link */ int PushResultToChannelRcvBuffer(ControlChannelRes *channelInfo, char *result); /** * @brief Writes data to the control link by ID */ int PushResultToChannelIdBuffer(ControlChannelRes *channelInfo, char *result, int id); #ifdef __cplusplus } #endif #endif // CHANNEL_RES_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/resource/include/channel_res.h
C
unknown
2,431
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef TLS_RES_H #define TLS_RES_H #include <stdint.h> #include "lock.h" #ifdef __cplusplus extern "C" { #endif typedef struct Res { void *tlsRes; // Indicates the CTX or SSL resource. int ctxId; // This field is used only in sslList, indicating the ctx from which the SSL is generated. struct Res *next; uint8_t id; // Indicates the sequence number of a resource, that is, the number of times that the resource // is created. The value starts from 0. } Res; typedef struct { Res *res; uint8_t num; Lock *resListLock; } ResList; /** * @brief Initializing the TLS Resource Linked List */ int InitTlsResList(void); /** * @brief Releasing the TLS Resource Linked List */ void FreeTlsResList(void); /** * @brief Releases CTX and SSL resources in the linked list based on CTX resources. */ int FreeResFromSsl(const void *ctx); /** * @brief Insert CTX resources into the linked list. */ int InsertCtxToList(void *ctx); /** * @brief Insert SSL resources into the linked list. */ int InsertSslToList(void* ctx, void *ssl); /** * @brief Obtains the CTX linked list from the linked list. */ ResList* GetCtxList(void); /** * @brief Obtains the SSL linked list from the linked list. */ ResList* GetSslList(void); /** * @brief Obtain the CTX from the CTX linked list based on the ID. */ int GetCtxIdFromSsl(const void* tls); /** * @brief Obtains the TLS RES in the linked list. */ Res* GetResFromTlsResList(ResList *resList, const void* tlsRes); /** * @brief Obtains TLS RES from the linked list based on the ID. */ void* GetTlsResFromId(ResList *resList, int id); #ifdef __cplusplus } #endif #endif // TLS_RES_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/resource/include/tls_res.h
C
unknown
2,216
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <sys/time.h> #include "logger.h" #include "securec.h" #include "lock.h" #include "channel_res.h" #define SUCCESS 0 #define ERROR (-1) static ControlChannelRes g_channelRes; static int SetControlChannelRes(ControlChannelRes *channelInfo, char *srcDomainPath, char *peerDomainPath) { int ret; // Translate the source address. ret = memset_s(&(channelInfo->srcAddr), sizeof(struct sockaddr_un), 0, sizeof(struct sockaddr_un)); if (ret != EOK) { LOG_ERROR("memset_s Error\n"); return ERROR; } ret = memcpy_s(channelInfo->srcDomainPath, DOMAIN_PATH_LEN, srcDomainPath, strlen(srcDomainPath)); if (ret != EOK) { LOG_ERROR("memcpy_s Error\n"); return ERROR; } channelInfo->srcAddr.sun_family = AF_UNIX; ret = strcpy_s(channelInfo->srcAddr.sun_path, strlen(srcDomainPath) + 1, srcDomainPath); if (ret != EOK) { LOG_ERROR("strcpy_s Error"); return ERROR; } ret = memset_s(channelInfo->peerDomainPath, sizeof(channelInfo->peerDomainPath), 0, sizeof(channelInfo->peerDomainPath)); if (ret != EOK) { LOG_ERROR("memset_s Error\n"); return ERROR; } if (peerDomainPath != NULL) { ret = memcpy_s(channelInfo->peerDomainPath, DOMAIN_PATH_LEN, peerDomainPath, strlen(peerDomainPath)); if (ret != EOK) { LOG_ERROR("memcpy_s Error\n"); return ERROR; } channelInfo->peerAddr.sun_family = AF_UNIX; ret = strcpy_s(channelInfo->peerAddr.sun_path, strlen(peerDomainPath) + 1, peerDomainPath); if (ret != EOK) { LOG_ERROR("strcpy_s Error"); return ERROR; } } return SUCCESS; } int InitControlChannelRes(char *srcDomainPath, int srcDomainPathLen, char *peerDomainPath, int peerDomainPathLen) { int ret; if ((srcDomainPathLen <= 0) && (peerDomainPathLen <= 0)) { LOG_ERROR("srcDomainPathLen or peerDomainPathLen is 0"); return ERROR; } ret = memset_s(&g_channelRes, sizeof(ControlChannelRes), 0, sizeof(ControlChannelRes)); if (ret != EOK) { return ERROR; } // Initializing the Send Buffer Lock g_channelRes.sendBufferLock = OsLockNew(); if (g_channelRes.sendBufferLock == NULL) { LOG_ERROR("OsLockNew Error"); return ERROR; } // Initialize the receive buffer lock. g_channelRes.rcvBufferLock = OsLockNew(); if (g_channelRes.rcvBufferLock == NULL) { LOG_ERROR("OsLockNew Error"); return ERROR; } // Initializes the communication address used for UDP Domain Socket communication. return SetControlChannelRes(&g_channelRes, srcDomainPath, peerDomainPath); } ControlChannelRes *GetControlChannelRes(void) { return &g_channelRes; } int PushResultToChannelSendBuffer(ControlChannelRes *channelInfo, char *result) { int ret; OsLock(channelInfo->sendBufferLock); if (channelInfo->sendBufferNum == MAX_SEND_BUFFER_NUM) { LOG_ERROR("Channel Send Buffer Is Full, Please Try Again"); OsUnLock(channelInfo->sendBufferLock); return 1; // The value 1 indicates that the current buffer is full and needs to be retried. } (void)memset_s(channelInfo->sendBuffer + channelInfo->sendBufferNum, CONTROL_CHANNEL_MAX_MSG_LEN, 0, CONTROL_CHANNEL_MAX_MSG_LEN); ret = memcpy_s(channelInfo->sendBuffer + channelInfo->sendBufferNum, CONTROL_CHANNEL_MAX_MSG_LEN, result, strlen(result)); if (ret != EOK) { LOG_ERROR("memcpy_s Error"); OsUnLock(channelInfo->sendBufferLock); return ERROR; } channelInfo->sendBufferNum++; channelInfo->sendBufferNum %= MAX_SEND_BUFFER_NUM; OsUnLock(channelInfo->sendBufferLock); return SUCCESS; } int PushResultToChannelRcvBuffer(ControlChannelRes *channelInfo, char *result) { int ret; OsLock(channelInfo->rcvBufferLock); if (channelInfo->rcvBufferNum == MAX_RCV_BUFFER_NUM) { LOG_ERROR("Channel Send Buffer Is Full, Please Try Again"); OsUnLock(channelInfo->rcvBufferLock); return 1; // The value 1 indicates that the current buffer is full and needs to be retried. } (void)memset_s(channelInfo->rcvBuffer + channelInfo->rcvBufferNum, CONTROL_CHANNEL_MAX_MSG_LEN, 0, CONTROL_CHANNEL_MAX_MSG_LEN); ret = memcpy_s(channelInfo->rcvBuffer + channelInfo->rcvBufferNum, CONTROL_CHANNEL_MAX_MSG_LEN, result, strlen(result)); if (ret != EOK) { LOG_ERROR("memcpy_s Error"); OsUnLock(channelInfo->rcvBufferLock); return ERROR; } channelInfo->rcvBufferNum++; channelInfo->rcvBufferNum %= MAX_RCV_BUFFER_NUM; OsUnLock(channelInfo->rcvBufferLock); return SUCCESS; } int PushResultToChannelIdBuffer(ControlChannelRes *channelInfo, char *result, int id) { int ret; OsLock(channelInfo->rcvBufferLock); (void)memset_s(channelInfo->rcvBuffer + (id % MAX_RCV_BUFFER_NUM), CONTROL_CHANNEL_MAX_MSG_LEN, 0, CONTROL_CHANNEL_MAX_MSG_LEN); ret = memcpy_s(channelInfo->rcvBuffer + (id % MAX_RCV_BUFFER_NUM), CONTROL_CHANNEL_MAX_MSG_LEN, result, strlen(result)); if (ret != EOK) { LOG_ERROR("memcpy_s Error"); OsUnLock(channelInfo->rcvBufferLock); return ERROR; } OsUnLock(channelInfo->rcvBufferLock); return SUCCESS; } void FreeControlChannelRes(void) { if (g_channelRes.tid != 0) { g_channelRes.isExit = true; pthread_join(g_channelRes.tid, NULL); } OsLockDestroy(g_channelRes.sendBufferLock); OsLockDestroy(g_channelRes.rcvBufferLock); memset_s(&g_channelRes, sizeof(g_channelRes), 0, sizeof(g_channelRes)); return; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/resource/src/channel_res.c
C
unknown
6,327
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <stdint.h> #include "securec.h" #include "lock.h" #include "logger.h" #include "hitls_func.h" #include "process.h" #include "tls_res.h" #define SUCCESS 0 #define ERROR (-1) ResList g_ctxList; ResList g_sslList; int InitTlsResList(void) { // Initializes the CTX resource management linked list. (void)memset_s(&g_ctxList, sizeof(ResList), 0, sizeof(ResList)); g_ctxList.resListLock = OsLockNew(); if (g_ctxList.resListLock == NULL) { LOG_ERROR("OsLockNew Error"); return ERROR; } // Indicates the head element in the linked list, which does not store any resource. g_ctxList.res = (Res *)malloc(sizeof(Res)); if (g_ctxList.res == NULL) { OsLockDestroy(g_ctxList.resListLock); return ERROR; } (void)memset_s(g_ctxList.res, sizeof(Res), 0, sizeof(Res)); g_ctxList.num = 0; // Initializing the SSL Resource Management Linked List (void)memset_s(&g_sslList, sizeof(ResList), 0, sizeof(ResList)); g_sslList.resListLock = OsLockNew(); if (g_sslList.resListLock == NULL) { LOG_ERROR("OsLockNew Error"); free(g_ctxList.res); OsLockDestroy(g_ctxList.resListLock); g_ctxList.resListLock = NULL; return ERROR; } // Indicates the head element in the linked list, which does not store any resource. g_sslList.res = (Res *)malloc(sizeof(Res)); if (g_sslList.res == NULL) { free(g_ctxList.res); OsLockDestroy(g_ctxList.resListLock); OsLockDestroy(g_sslList.resListLock); return ERROR; } (void)memset_s(g_sslList.res, sizeof(Res), 0, sizeof(Res)); g_sslList.num = 0; return SUCCESS; } int InsertResToList(ResList *resList, Res tempRes) { int id; Res *curRes = NULL; Res *res = (Res*)malloc(sizeof(Res)); if (res == NULL) { return ERROR; } memset_s(res, sizeof(Res), 0, sizeof(Res)); // Insert in the lock OsLock(resList->resListLock); id = resList->num; res->ctxId = tempRes.ctxId; res->tlsRes = tempRes.tlsRes; res->next = NULL; res->id = id; // In the linked list, the first element is NULL by default and is used as the start element. curRes = resList->res->next; // When the first element is empty if (curRes == NULL) { resList->res->next = res; resList->num++; OsUnLock(resList->resListLock); return id; } // Find the tail element while (curRes->next != NULL) { curRes = curRes->next; } curRes->next = res; resList->num++; OsUnLock(resList->resListLock); return id; } int InsertCtxToList(void *tlsRes) { ResList *resList = GetCtxList(); Res ctxRes = {0}; ctxRes.tlsRes = tlsRes; ctxRes.ctxId = -1; // This field is used only in the SSL linked list. return InsertResToList(resList, ctxRes); } static int GetTlsIdFromResList(ResList *resList, const void *tls) { Res *tlsRes = GetResFromTlsResList(resList, tls); if (tlsRes == NULL) { LOG_ERROR("GetResFromTlsResList ERROR"); return ERROR; } // Indicates the serial number of a resource. return tlsRes->id; } int InsertSslToList(void *ctx, void *ssl) { int ctxId; Res sslRes = {0}; ResList *ctxList = GetCtxList(); ResList *sslList = GetSslList(); ctxId = GetTlsIdFromResList(ctxList, ctx); if (ctxId == ERROR) { LOG_ERROR("GetTlsIdFromResList Error"); return ERROR; } sslRes.tlsRes = ssl; sslRes.ctxId = ctxId; // This field is used only in the SSL linked list and indicates the CTX that is created. return InsertResToList(sslList, sslRes); } ResList *GetCtxList(void) { return &g_ctxList; } ResList *GetSslList(void) { return &g_sslList; } Res *GetResFromTlsResList(ResList *resList, const void *tlsRes) { Res *tmpRes = NULL; OsLock(resList->resListLock); // In the linked list, the first element is NULL by default and is used as the start element. tmpRes = resList->res->next; while (tmpRes != NULL) { if (tmpRes->tlsRes == tlsRes) { OsUnLock(resList->resListLock); return tmpRes; } tmpRes = tmpRes->next; } OsUnLock(resList->resListLock); return NULL; } static Res *GetResFromId(ResList *resList, int id) { Res *tmpRes = NULL; OsLock(resList->resListLock); // In the linked list, the first element is NULL by default and is used as the start element. tmpRes = resList->res->next; while (tmpRes != NULL) { if (tmpRes->id == id) { OsUnLock(resList->resListLock); return tmpRes; } tmpRes = tmpRes->next; } OsUnLock(resList->resListLock); return NULL; } void *GetTlsResFromId(ResList *resList, int id) { Res *res = GetResFromId(resList, id); if (res == NULL) { LOG_ERROR("GetResFromId error"); return NULL; } return res->tlsRes; } int GetCtxIdFromSsl(const void *tls) { ResList *sslList = GetSslList(); Res *tmpRes = GetResFromTlsResList(sslList, tls); if (tmpRes == NULL) { LOG_ERROR("GetResFromTlsResList ERROR"); return ERROR; } // CTX ID corresponding to SSL return tmpRes->ctxId; } static void *GetLastResFromList(ResList *resList) { Res *headRes = resList->res; Res *frontRes = NULL; Res *nextRes = NULL; if (resList->num == 0) { return NULL; } frontRes = headRes->next; nextRes = frontRes; // Find the last element while ((nextRes != NULL) && (nextRes->tlsRes != NULL)) { frontRes = nextRes; nextRes = frontRes->next; } resList->num--; return frontRes; } void FreeResList(ResList *resList) { Res *curRes = NULL; Res *tmpRes = NULL; OsLock(resList->resListLock); curRes = resList->res->next; while (curRes != NULL) { tmpRes = curRes->next; free(curRes); curRes = tmpRes; } OsUnLock(resList->resListLock); free(resList->res); OsLockDestroy(resList->resListLock); } void FreeCtx(TLS_TYPE tlsType, Res *ctxRes) { switch (tlsType) { case HITLS: HitlsFreeCtx(ctxRes->tlsRes); break; default: /* Unknown type */ return; } ctxRes->tlsRes = NULL; return; } void FreeSsl(TLS_TYPE tlsType, Res *sslRes) { switch (tlsType) { case HITLS: HitlsFreeSsl(sslRes->tlsRes); break; default: /* Unknown type */ return; } sslRes->tlsRes = NULL; return; } void FreeTlsResList(void) { Process *process = GetProcess(); TLS_TYPE type = process->tlsType; // Clearing CTX Resources ResList *ctxList = GetCtxList(); void *resCtx = GetLastResFromList(ctxList); while (resCtx != NULL) { FreeCtx(type, resCtx); resCtx = GetLastResFromList(ctxList); } FreeResList(ctxList); // Clearing SSL Resources ResList *sslList = GetSslList(); void *sslRes = GetLastResFromList(sslList); while (sslRes != NULL) { FreeSsl(type, sslRes); sslRes = GetLastResFromList(sslList); } FreeResList(sslList); return; } int FreeResFromSsl(const void *ctx) { Process *process = GetProcess(); TLS_TYPE type = process->tlsType; ResList *sslList = GetSslList(); Res *preRes = NULL; Res *curRes = NULL; Res *nextRes = NULL; OsLock(sslList->resListLock); preRes = sslList->res; curRes = sslList->res->next; while (curRes != NULL) { if (curRes->tlsRes == ctx) { nextRes = curRes->next; FreeSsl(type, curRes); FreeCtx(type, curRes); free(curRes); preRes->next = nextRes; sslList->num--; OsUnLock(sslList->resListLock); return SUCCESS; } preRes = curRes; curRes = curRes->next; } OsUnLock(sslList->resListLock); return ERROR; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/resource/src/tls_res.c
C
unknown
8,569
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef COMMON_FUNC_H #define COMMON_FUNC_H #include <stdatomic.h> #include "hlt_type.h" #ifdef __cplusplus extern "C" { #endif typedef enum { EE_CERT, PRIVE_KEY, CA_CERT, CHAIN_CERT } CERT_TYPE; typedef struct { atomic_int mallocCnt; atomic_int freeCnt; atomic_int mallocSize; atomic_int freeSize; atomic_int maxMemSize; } MemCnt; /** * @brief Load a certificate from a file. */ int LoadCertFromFile(void *ctx, char *pCert, CERT_TYPE certType); /** * @brief Memory application that contains the count */ void *CountMalloc(uint32_t len); /** * @brief Memory release that contains the count */ void CountFree(void *addr); /** * @brief Clear the memory count. */ void ClearMemCntData(void); /** * @brief Obtain the memory count. */ MemCnt *GetMemCntData(void); int32_t ExampleSetPsk(char *psk); uint32_t ExampleClientCb(HITLS_Ctx *ctx, const uint8_t *hint, uint8_t *identity, uint32_t maxIdentityLen, uint8_t *psk, uint32_t maxPskLen); uint32_t ExampleServerCb(HITLS_Ctx *ctx, const uint8_t *identity, uint8_t *psk, uint32_t maxPskLen); int32_t ExampleTicketKeySuccessCb(uint8_t *keyName, uint32_t keyNameSize, void *cipher, uint8_t isEncrypt); int32_t ExampleTicketKeyRenewCb(uint8_t *keyName, uint32_t keyNameSize, void *cipher, uint8_t isEncrypt); void *GetTicketKeyCb(char *str); void *GetExtensionCb(const char *str); void *GetExampleData(const char *str); #ifdef __cplusplus } #endif #endif // COMMON_FUNC_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/rpc/include/common_func.h
C
unknown
2,011
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_FUNC_H #define HITLS_FUNC_H #include "hitls_config.h" #include "bsl_uio.h" #include "hlt_type.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Hitls initialization */ int HitlsInit(void); /** * @brief HiTLS Create connection management resources. */ void* HitlsNewCtx(TLS_VERSION tlsVersion); HITLS_Config *HitlsProviderNewCtx(char *providerPath, char (*providerNames)[MAX_PROVIDER_NAME_LEN], int *providerLibFmts, int providerCnt, char *attrName, TLS_VERSION tlsVersion); /** * @brief HiTLS Releases connection management resources. */ void HitlsFreeCtx(void *ctx); /** * @brief HiTLS Setting connection information */ int HitlsSetCtx(HITLS_Config *config, HLT_Ctx_Config *ctxConfig); /** * @brief HiTLS Creating an SSL resource */ void* HitlsNewSsl(void *ctx); /** * @brief HiTLS Releases SSL resources. */ void HitlsFreeSsl(void *ssl); /** * @brief HiTLS Set TLS information. */ int HitlsSetSsl(void *ssl, HLT_Ssl_Config *sslConfig); /** * @brief HiTLS waits for a TLS connection. */ void *HitlsAccept(void *ssl); /** * @brief The HiTLS initiates a TLS connection. */ int HitlsConnect(void *ssl); /** * @brief HiTLS writes data through the TLS connection. */ int HitlsWrite(void *ssl, uint8_t *data, uint32_t dataLen); /** * @brief HiTLS reads data through the TLS connection. */ int HitlsRead(void *ssl, uint8_t *data, uint32_t bufSize, uint32_t *readLen); /** * @brief HiTLS Disables the TLS connection. */ int HitlsClose(void *ssl); /** * @brief HiTLS supports renegotiation through TLS connection. */ int HitlsRenegotiate(void *ssl); int HitlsSetMtu(void *ssl, uint16_t mtu); int HitlsSetSession(void *ssl, void *session); int HitlsSessionReused(void *ssl); void *HitlsGet1Session(void *ssl); int HitlsSessionHasTicket(void *session); int HitlsSessionIsResumable(void *session); void HitlsFreeSession(void *session); int HitlsGetErrorCode(void *ssl); /** * @brief Obtaining method based on the connection type */ BSL_UIO_Method *GetDefaultMethod(BSL_UIO_TransportType type); #ifdef __cplusplus } #endif #endif // HITLS_FUNC_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/rpc/include/hitls_func.h
C
unknown
2,622
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef RPC_FUNC_H #define RPC_FUNC_H #include <pthread.h> #include "handle_cmd.h" #ifdef __cplusplus extern "C" { #endif typedef struct { char *funcId; int (*hfunc)(CmdData *cmdData); } RpcFunList; /** * @brief Obtain the list of registered functions. */ RpcFunList* GetRpcFuncList(void); /** * @brief Obtain the number of registered functions. */ int GetRpcFuncNum(void); /** * @brief Invoke the RPC to create CTX resources. */ int RpcTlsNewCtx(CmdData*); /** * @brief Invoke the RPC to create CTX resources with provider. */ int RpcProviderTlsNewCtx(CmdData *cmdData); /** * @brief Invoke the RPC to set the CTX information. */ int RpcTlsSetCtx(CmdData*); /** * @brief Invoke the RPC to create an SSL resource. */ int RpcTlsNewSsl(CmdData*); /** * @brief Invoke the RPC to set the SSL information. */ int RpcTlsSetSsl(CmdData*); /** * @brief The RPC invokes the TLS connection to be listened on. */ int RpcTlsListen(CmdData *cmdData); /** * @brief Invoke the RPC to wait for the TLS connection. */ int RpcTlsAccept(CmdData*); /** * @brief Invoke the RPC interface for TLS connection. */ int RpcTlsConnect(CmdData*); /** * @brief Invoke the RPC to read data through TLS. */ int RpcTlsRead(CmdData *cmdData); /** * @brief Invoke the RPC to write data through TLS. */ int RpcTlsWrite(CmdData *cmdData); /** * @brief Invoke the RPC interface to enable renegotiation. */ int RpcTlsRenegotiate(CmdData *cmdData); /** * @brief The RPC call is used to enable the pha. */ int RpcTlsVerifyClientPostHandshake(CmdData *cmdData); /** * @brief The RPC exits the process */ int RpcProcessExit(CmdData*); /** * @brief RPC bound port */ int RunDataChannelBind(void *param); /** * @brief RPC listening data connection */ int RpcDataChannelAccept(CmdData*); /** * @brief The RPC data initiates a connection. */ int RpcDataChannelConnect(CmdData *cmdData); /** * @brief RPC listens on a certain type of data connection. */ int RunDataChannelAccept(void *param); /** * @brief RPC bound port */ int RpcDataChannelBind(CmdData *cmdData); /** * @brief RPC registration hook */ int RpcTlsRegCallback(CmdData *cmdData); /** * @brief RPC Obtain the SSL connection status. */ int RpcTlsGetStatus(CmdData *cmdData); /** * @brief RPC Obtain the flag of the alert message. */ int RpcTlsGetAlertFlag(CmdData *cmdData); /** * @brief RPC Obtain the level of the alert message. */ int RpcTlsGetAlertLevel(CmdData *cmdData); /** * @brief RPC Obtain the description of the alert message. */ int RpcTlsGetAlertDescription(CmdData *cmdData); /** * @brief RPC Disable the TLS connection. */ int RpcTlsClose(CmdData *cmdData); /** * @brief RPC Release the CTX and SSL contexts. */ int RpcFreeResFormSsl(CmdData *cmdData); int RpcCloseFd(CmdData *cmdData); int RpcTlsSetMtu(CmdData *cmdData); int RpcTlsGetErrorCode(CmdData *cmdData); #ifdef __cplusplus } #endif #endif // RPC_FUNC_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/rpc/include/rpc_func.h
C
unknown
3,438
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdlib.h> #include <malloc.h> #include <stdatomic.h> #include "securec.h" #include "hitls_crypt_type.h" #include "hitls_session.h" #include "logger.h" #include "bsl_sal.h" #include "hitls_error.h" #include "hitls_sni.h" #include "sni.h" #include "hitls_alpn.h" #include "hitls_type.h" #include "common_func.h" #define SUCCESS 0 #define ERROR (-1) #define MAX_CERT_PATH_LENGTH (128) #define SINGLE_CERT_LEN (120) #define KEY_NAME_SIZE 16 #define IV_SIZE 16 #define KEY_SIZE 32 #define RENEGOTIATE_FAIL 1 static uint8_t g_keyName[KEY_NAME_SIZE] = { 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A }; static uint8_t g_key[KEY_SIZE] = { 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A }; static uint8_t g_iv[IV_SIZE] = { 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A, 0x1A }; typedef struct { char *name; void *cb; } ExampleCb; typedef struct { char *name; void *(*data)(void); } ExampleData; #define ASSERT_RETURN(condition, log) \ do { \ if (!(condition)) { \ LOG_ERROR(log); \ return ERROR; \ } \ } while (0) static char g_localIdentity[PSK_MAX_LEN] = "Client_identity"; static char g_localPsk[PSK_MAX_LEN] = "1A1A1A1A1A"; int32_t ExampleSetPsk(char *psk) { if (psk == NULL) { LOG_DEBUG("input error."); return -1; } (void)memset_s(g_localPsk, PSK_MAX_LEN, 0, PSK_MAX_LEN); if (strcpy_s(g_localPsk, PSK_MAX_LEN, psk) != EOK) { LOG_DEBUG("ExampleSetPsk failed."); return -1; } return 0; } int32_t ExampleHexStr2BufHelper(const uint8_t *input, uint32_t inLen, uint8_t *out, uint32_t outLen, uint32_t *usedLen) { (void)inLen; (void)outLen; char indexH[2] = {0}; char indexL[2] = {0}; const uint8_t *curr = NULL; uint8_t *outIndex = NULL; int32_t high, low; if ((input == NULL) || (out == NULL) || (usedLen == NULL)) { return -1; } for (curr = input, outIndex = out; *curr;) { indexH[0] = *curr++; indexL[0] = *curr++; if (indexL[0] == '\0') { return -1; } high = (int32_t)strtol(indexH, NULL, 16); // Converting char to Hexadecimal numbers low = (int32_t)strtol(indexL, NULL, 16); // Converting char to Hexadecimal numbers if (high < 0 || low < 0) { return -1; } *outIndex++ = (uint8_t)((high << 4) | low); // The upper four bits of the are shifted to the left } *usedLen = outIndex - out; return 0; } uint32_t ExampleClientCb(HITLS_Ctx *ctx, const uint8_t *hint, uint8_t *identity, uint32_t maxIdentityLen, uint8_t *psk, uint32_t maxPskLen) { (void)ctx; (void)hint; int32_t ret; uint8_t pskTrans[PSK_MAX_LEN] = {0}; uint32_t pskTransUsedLen = 0u; ret = ExampleHexStr2BufHelper((uint8_t *)g_localPsk, sizeof(g_localPsk), pskTrans, PSK_MAX_LEN, &pskTransUsedLen); if (ret != 0) { return 0; } /* strlen(g_localIdentity) + 1 copy terminator */ if (memcpy_s(identity, maxIdentityLen, g_localIdentity, strlen(g_localIdentity) + 1) != EOK) { return 0; } if (memcpy_s(psk, maxPskLen, pskTrans, pskTransUsedLen) != EOK) { return 0; } return pskTransUsedLen; } uint32_t ExampleServerCb(HITLS_Ctx *ctx, const uint8_t *identity, uint8_t *psk, uint32_t maxPskLen) { (void)ctx; if (identity == NULL || strcmp((const char *)identity, g_localIdentity) != 0) { return 0; } int32_t ret; uint8_t pskTrans[PSK_MAX_LEN] = {0}; uint32_t pskTransUsedLen = 0u; ret = ExampleHexStr2BufHelper((uint8_t *)g_localPsk, sizeof(g_localPsk), pskTrans, PSK_MAX_LEN, &pskTransUsedLen); if (ret != 0) { return 0; } if (memcpy_s(psk, maxPskLen, pskTrans, pskTransUsedLen) != EOK) { return 0; } return pskTransUsedLen; } static void SetCipherInfo(void *cipher) { HITLS_CipherParameters *cipherPara = cipher; cipherPara->type = HITLS_CBC_CIPHER; cipherPara->algo = HITLS_CIPHER_AES_256_CBC; cipherPara->key = g_key; cipherPara->keyLen = sizeof(g_key); cipherPara->hmacKey = g_key; cipherPara->hmacKeyLen = sizeof(g_key); cipherPara->iv = g_iv; cipherPara->ivLen = sizeof(g_iv); return; } int32_t ExampleTicketKeySuccessCb(uint8_t *keyName, uint32_t keyNameSize, void *cipher, uint8_t isEncrypt) { if (isEncrypt) { if (memcpy_s(keyName, keyNameSize, g_keyName, KEY_NAME_SIZE) != EOK) { return HITLS_TICKET_KEY_RET_FAIL; } SetCipherInfo(cipher); return HITLS_TICKET_KEY_RET_SUCCESS; } if (memcmp(keyName, g_keyName, KEY_NAME_SIZE) != 0) { return HITLS_TICKET_KEY_RET_FAIL; } SetCipherInfo(cipher); return HITLS_TICKET_KEY_RET_SUCCESS; } int32_t ExampleTicketKeyRenewCb(uint8_t *keyName, uint32_t keyNameSize, void *cipher, uint8_t isEncrypt) { if (isEncrypt) { if (memcpy_s(keyName, keyNameSize, g_keyName, KEY_NAME_SIZE) != EOK) { return HITLS_TICKET_KEY_RET_FAIL; } SetCipherInfo(cipher); return HITLS_TICKET_KEY_RET_SUCCESS_RENEW; } if (memcmp(keyName, g_keyName, KEY_NAME_SIZE) != 0) { return HITLS_TICKET_KEY_RET_FAIL; } SetCipherInfo(cipher); return HITLS_TICKET_KEY_RET_SUCCESS_RENEW; } int32_t ExampleTicketKeyAlertCb(uint8_t *keyName, uint32_t keyNameSize, HITLS_CipherParameters *cipher, uint8_t isEncrypt) { if (isEncrypt) { (void)memcpy_s(keyName, keyNameSize, g_keyName, KEY_NAME_SIZE); SetCipherInfo(cipher); return HITLS_TICKET_KEY_RET_SUCCESS_RENEW; } else { return HITLS_TICKET_KEY_RET_NEED_ALERT; } } int32_t ExampleTicketKeyFailCb(uint8_t *keyName, uint32_t keyNameSize, HITLS_CipherParameters *cipher, uint8_t isEncrypt) { if (isEncrypt) { (void)memcpy_s(keyName, keyNameSize, g_keyName, KEY_NAME_SIZE); SetCipherInfo(cipher); return HITLS_TICKET_KEY_RET_SUCCESS_RENEW; } SetCipherInfo(cipher); return HITLS_TICKET_KEY_RET_FAIL; } int32_t ExampleServerNameCb(HITLS_Ctx *ctx, int *alert, void *arg) { (void)ctx; (void)arg; *alert = HITLS_ACCEPT_SNI_ERR_OK; return HITLS_ACCEPT_SNI_ERR_OK; } int32_t ExampleServerNameCbNOACK(HITLS_Ctx *ctx, int *alert, void *arg) { (void)ctx; (void)alert; (void)arg; return HITLS_ACCEPT_SNI_ERR_NOACK; } int32_t ExampleServerNameCbALERT(HITLS_Ctx *ctx, int *alert, void *arg) { (void)ctx; (void)alert; (void)arg; return HITLS_ACCEPT_SNI_ERR_ALERT_FATAL; } SNI_Arg *g_sniArg; void *ExampleServerNameArg(void) { return g_sniArg; } static char *g_alpnhttp = "http"; int32_t ExampleAlpnParseProtocolList1(uint8_t *out, uint8_t *outLen, uint8_t *in, uint8_t inLen) { if (out == NULL || outLen == NULL || in == NULL) { return HITLS_NULL_INPUT; } if (inLen == 0) { return HITLS_CONFIG_INVALID_LENGTH; } uint8_t i = 0u; uint8_t commaNum = 0u; uint8_t startPos = 0u; for (i = 0u; i <= inLen; ++i) { if (i == inLen || in[i] == ',') { if (i == startPos) { ++startPos; ++commaNum; continue; } out[startPos - commaNum] = (uint8_t)(i - startPos); startPos = i + 1; } else { out[i + 1 - commaNum] = in[i]; } } *outLen = inLen + 1 - commaNum; return HITLS_SUCCESS; } int32_t ExampleAlpnCb(HITLS_Ctx *ctx, char **selectedProto, uint8_t *selectedProtoSize, char *clientAlpnList, uint32_t clientAlpnListSize, void *userData) { (void)ctx; (void)userData; if (clientAlpnListSize >= 5 && memcmp(clientAlpnList + 1, "http", 4) == 0) { *selectedProto = clientAlpnList + 1; *selectedProtoSize = 4; return HITLS_ALPN_ERR_OK; } else if (clientAlpnListSize >= 4 && memcmp(clientAlpnList + 1, "ftp", 3) == 0) { *selectedProto = g_alpnhttp; *selectedProtoSize = 4; return HITLS_ALPN_ERR_OK; } else if (clientAlpnListSize >= 4 && memcmp(clientAlpnList + 1, "mml", 3) == 0) { *selectedProto = g_alpnhttp; *selectedProtoSize = 4; return HITLS_ALPN_ERR_ALERT_FATAL; } else if (clientAlpnListSize >= 4 && memcmp(clientAlpnList + 1, "www", 3) == 0) { *selectedProto = g_alpnhttp; *selectedProtoSize = 4; return HITLS_ALPN_ERR_OK; } else { return HITLS_ALPN_ERR_NOACK; } } int32_t AlpnCbWARN1(HITLS_Ctx *ctx, uint8_t **selectedProto, uint8_t *selectedProtoSize, uint8_t *clientAlpnList, uint32_t clientAlpnListSize, void *userData) { (void)ctx; (void)selectedProto; (void)selectedProtoSize; (void)clientAlpnList; (void)clientAlpnListSize; (void)userData; return HITLS_ALPN_ERR_ALERT_WARNING; } int32_t AlpnCbALERT1(HITLS_Ctx *ctx, uint8_t **selectedProto, uint8_t *selectedProtoSize, uint8_t *clientAlpnList, uint32_t clientAlpnListSize, void *userData) { (void)ctx; (void)selectedProto; (void)selectedProtoSize; (void)clientAlpnList; (void)clientAlpnListSize; (void)userData; return HITLS_ALPN_ERR_ALERT_FATAL; } void *ExampleAlpnData(void) { // Return the alpnData address. return "audata"; } void *GetTicketKeyCb(char *str) { const ExampleCb cbList[] = { {"ExampleTicketKeySuccessCb", ExampleTicketKeySuccessCb}, {"ExampleTicketKeyRenewCb", ExampleTicketKeyRenewCb}, {"ExampleTicketKeyAlertCb", ExampleTicketKeyAlertCb}, {"ExampleTicketKeyFailCb", ExampleTicketKeyFailCb}, }; int len = sizeof(cbList) / sizeof(cbList[0]); for (int i = 0; i < len; i++) { if (strcmp(str, cbList[i].name) == 0) { return cbList[i].cb; } } return NULL; } static void ExampleKeyLogCb(HITLS_Ctx *ctx, const char *out) { (void)ctx; // Unused parameter char *fileName = "FileKeyLog.txt"; char *fileEndStr = "\n"; FILE *fp = fopen(fileName, "a+"); if (fp == NULL) { return; } fwrite(out, sizeof(char), strlen(out), fp); fwrite((char*)fileEndStr, sizeof(char), strlen(fileEndStr), fp); fclose(fp); } void *GetExtensionCb(const char *str) { const ExampleCb cbList[] = { {"ExampleSNICb", ExampleServerNameCb}, {"ExampleAlpnCb", ExampleAlpnCb}, {"ExampleAlpnWarnCb", AlpnCbWARN1}, {"ExampleAlpAlertCb", AlpnCbALERT1}, {"ExampleSNICbnoack", ExampleServerNameCbNOACK}, {"ExampleSNICbAlert", ExampleServerNameCbALERT}, {"ExampleKeyLogCb", ExampleKeyLogCb}, }; int len = sizeof(cbList) / sizeof(cbList[0]); for (int i = 0; i < len; i++) { if (strcmp(str, cbList[i].name) == 0) { return cbList[i].cb; } } return NULL; } void *GetExampleData(const char *str) { const ExampleData cbList[] = { {"ExampleSNIArg", ExampleServerNameArg}, {"ExampleAlpnData", ExampleAlpnData}, }; int len = sizeof(cbList) / sizeof(cbList[0]); for (int i = 0; i < len; i++) { if (strcmp(str, cbList[i].name) == 0) { return cbList[i].data(); } } return NULL; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/rpc/src/common_func.c
C
unknown
12,103
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <arpa/inet.h> #include "uio_base.h" #include "bsl_sal.h" #include "sal_net.h" #include "hitls.h" #include "hitls_cert_type.h" #include "hitls_config.h" #include "hitls_error.h" #include "hitls_psk.h" #include "hitls_session.h" #include "hitls_debug.h" #include "hitls_sni.h" #include "hitls_alpn.h" #include "hitls_security.h" #include "hitls_crypt_init.h" #include "tls.h" #include "hlt_type.h" #include "logger.h" #include "tls_res.h" #include "cert_callback.h" #include "sctp_channel.h" #include "tcp_channel.h" #include "udp_channel.h" #include "common_func.h" #include "crypt_eal_rand.h" #include "crypt_algid.h" #include "channel_res.h" #include "crypt_eal_provider.h" #define SUCCESS 0 #define ERROR (-1) #define FUNC_TIME_OUT_SEC 120 #define ASSERT_RETURN(condition, log) \ do { \ if (!(condition)) { \ LOG_ERROR(log); \ return ERROR; \ } \ } while (0) typedef struct { char *name; uint16_t configValue; } HitlsConfig; typedef enum { CIPHER, GROUPS, SIGNATURE, POINTFORMAT, } HitlsConfigType; static const HitlsConfig g_cipherSuiteList[] = { {"HITLS_RSA_WITH_AES_128_CBC_SHA", HITLS_RSA_WITH_AES_128_CBC_SHA}, {"HITLS_DHE_DSS_WITH_AES_128_CBC_SHA", HITLS_DHE_DSS_WITH_AES_128_CBC_SHA}, {"HITLS_DHE_RSA_WITH_AES_128_CBC_SHA", HITLS_DHE_RSA_WITH_AES_128_CBC_SHA}, {"HITLS_RSA_WITH_AES_256_CBC_SHA", HITLS_RSA_WITH_AES_256_CBC_SHA}, {"HITLS_DHE_DSS_WITH_AES_256_CBC_SHA", HITLS_DHE_DSS_WITH_AES_256_CBC_SHA}, {"HITLS_DHE_RSA_WITH_AES_256_CBC_SHA", HITLS_DHE_RSA_WITH_AES_256_CBC_SHA}, {"HITLS_RSA_WITH_AES_128_CBC_SHA256", HITLS_RSA_WITH_AES_128_CBC_SHA256}, {"HITLS_RSA_WITH_AES_256_CBC_SHA256", HITLS_RSA_WITH_AES_256_CBC_SHA256}, {"HITLS_DHE_DSS_WITH_AES_128_CBC_SHA256", HITLS_DHE_DSS_WITH_AES_128_CBC_SHA256}, {"HITLS_DHE_RSA_WITH_AES_128_CBC_SHA256", HITLS_DHE_RSA_WITH_AES_128_CBC_SHA256}, {"HITLS_DHE_DSS_WITH_AES_256_CBC_SHA256", HITLS_DHE_DSS_WITH_AES_256_CBC_SHA256}, {"HITLS_DHE_RSA_WITH_AES_256_CBC_SHA256", HITLS_DHE_RSA_WITH_AES_256_CBC_SHA256}, {"HITLS_RSA_WITH_AES_128_GCM_SHA256", HITLS_RSA_WITH_AES_128_GCM_SHA256}, {"HITLS_RSA_WITH_AES_256_GCM_SHA384", HITLS_RSA_WITH_AES_256_GCM_SHA384}, {"HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256", HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256}, {"HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384", HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384}, {"HITLS_DHE_DSS_WITH_AES_128_GCM_SHA256", HITLS_DHE_DSS_WITH_AES_128_GCM_SHA256}, {"HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384", HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384}, {"HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA}, {"HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA}, {"HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA}, {"HITLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", HITLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}, {"HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256}, {"HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384}, {"HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256}, {"HITLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", HITLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384}, {"HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, {"HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384}, {"HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}, {"HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384}, {"HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256}, {"HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256}, {"HITLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256", HITLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256}, {"HITLS_AES_128_GCM_SHA256", HITLS_AES_128_GCM_SHA256}, {"HITLS_AES_256_GCM_SHA384", HITLS_AES_256_GCM_SHA384}, {"HITLS_CHACHA20_POLY1305_SHA256", HITLS_CHACHA20_POLY1305_SHA256}, {"HITLS_AES_128_CCM_SHA256", HITLS_AES_128_CCM_SHA256}, {"HITLS_AES_128_CCM_8_SHA256", HITLS_AES_128_CCM_8_SHA256}, {"HITLS_ECDHE_ECDSA_WITH_AES_128_CCM", HITLS_ECDHE_ECDSA_WITH_AES_128_CCM}, {"HITLS_ECDHE_ECDSA_WITH_AES_256_CCM", HITLS_ECDHE_ECDSA_WITH_AES_256_CCM}, {"HITLS_DHE_RSA_WITH_AES_128_CCM", HITLS_DHE_RSA_WITH_AES_128_CCM}, {"HITLS_DHE_RSA_WITH_AES_256_CCM", HITLS_DHE_RSA_WITH_AES_256_CCM}, {"HITLS_RSA_WITH_AES_256_CCM", HITLS_RSA_WITH_AES_256_CCM}, {"HITLS_RSA_WITH_AES_256_CCM_8", HITLS_RSA_WITH_AES_256_CCM_8}, {"HITLS_RSA_WITH_AES_128_CCM", HITLS_RSA_WITH_AES_128_CCM}, {"HITLS_RSA_WITH_AES_128_CCM_8", HITLS_RSA_WITH_AES_128_CCM_8}, /* psk cipher suite */ {"HITLS_PSK_WITH_AES_128_CBC_SHA", HITLS_PSK_WITH_AES_128_CBC_SHA}, {"HITLS_PSK_WITH_AES_256_CBC_SHA", HITLS_PSK_WITH_AES_256_CBC_SHA}, {"HITLS_DHE_PSK_WITH_AES_128_CBC_SHA", HITLS_DHE_PSK_WITH_AES_128_CBC_SHA}, {"HITLS_DHE_PSK_WITH_AES_256_CBC_SHA", HITLS_DHE_PSK_WITH_AES_256_CBC_SHA}, {"HITLS_RSA_PSK_WITH_AES_128_CBC_SHA", HITLS_RSA_PSK_WITH_AES_128_CBC_SHA}, {"HITLS_RSA_PSK_WITH_AES_256_CBC_SHA", HITLS_RSA_PSK_WITH_AES_256_CBC_SHA}, {"HITLS_PSK_WITH_AES_128_GCM_SHA256", HITLS_PSK_WITH_AES_128_GCM_SHA256}, {"HITLS_PSK_WITH_AES_256_GCM_SHA384", HITLS_PSK_WITH_AES_256_GCM_SHA384}, {"HITLS_DHE_PSK_WITH_AES_128_GCM_SHA256", HITLS_DHE_PSK_WITH_AES_128_GCM_SHA256}, {"HITLS_DHE_PSK_WITH_AES_256_GCM_SHA384", HITLS_DHE_PSK_WITH_AES_256_GCM_SHA384}, {"HITLS_RSA_PSK_WITH_AES_128_GCM_SHA256", HITLS_RSA_PSK_WITH_AES_128_GCM_SHA256}, {"HITLS_RSA_PSK_WITH_AES_256_GCM_SHA384", HITLS_RSA_PSK_WITH_AES_256_GCM_SHA384}, {"HITLS_PSK_WITH_AES_128_CBC_SHA256", HITLS_PSK_WITH_AES_128_CBC_SHA256}, {"HITLS_PSK_WITH_AES_256_CBC_SHA384", HITLS_PSK_WITH_AES_256_CBC_SHA384}, {"HITLS_DHE_PSK_WITH_AES_128_CBC_SHA256", HITLS_DHE_PSK_WITH_AES_128_CBC_SHA256}, {"HITLS_DHE_PSK_WITH_AES_256_CBC_SHA384", HITLS_DHE_PSK_WITH_AES_256_CBC_SHA384}, {"HITLS_RSA_PSK_WITH_AES_128_CBC_SHA256", HITLS_RSA_PSK_WITH_AES_128_CBC_SHA256}, {"HITLS_RSA_PSK_WITH_AES_256_CBC_SHA384", HITLS_RSA_PSK_WITH_AES_256_CBC_SHA384}, {"HITLS_ECDHE_PSK_WITH_AES_128_CBC_SHA", HITLS_ECDHE_PSK_WITH_AES_128_CBC_SHA}, {"HITLS_ECDHE_PSK_WITH_AES_256_CBC_SHA", HITLS_ECDHE_PSK_WITH_AES_256_CBC_SHA}, {"HITLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256", HITLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256}, {"HITLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384", HITLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384}, {"HITLS_PSK_WITH_CHACHA20_POLY1305_SHA256", HITLS_PSK_WITH_CHACHA20_POLY1305_SHA256}, {"HITLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256", HITLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256}, {"HITLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256", HITLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256}, {"HITLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256", HITLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256}, {"HITLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256", HITLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256}, {"HITLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384", HITLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384}, {"HITLS_DHE_PSK_WITH_AES_128_CCM", HITLS_DHE_PSK_WITH_AES_128_CCM}, {"HITLS_DHE_PSK_WITH_AES_256_CCM", HITLS_DHE_PSK_WITH_AES_256_CCM}, {"HITLS_PSK_WITH_AES_256_CCM", HITLS_PSK_WITH_AES_256_CCM}, {"HITLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256", HITLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256}, /* Anonymous ciphersuite */ {"HITLS_DH_ANON_WITH_AES_256_CBC_SHA", HITLS_DH_ANON_WITH_AES_256_CBC_SHA}, {"HITLS_DH_ANON_WITH_AES_128_CBC_SHA", HITLS_DH_ANON_WITH_AES_128_CBC_SHA}, {"HITLS_DH_ANON_WITH_AES_128_CBC_SHA256", HITLS_DH_ANON_WITH_AES_128_CBC_SHA256}, {"HITLS_DH_ANON_WITH_AES_256_CBC_SHA256", HITLS_DH_ANON_WITH_AES_256_CBC_SHA256}, {"HITLS_DH_ANON_WITH_AES_128_GCM_SHA256", HITLS_DH_ANON_WITH_AES_128_GCM_SHA256}, {"HITLS_DH_ANON_WITH_AES_256_GCM_SHA384", HITLS_DH_ANON_WITH_AES_256_GCM_SHA384}, {"HITLS_ECDH_ANON_WITH_AES_128_CBC_SHA", HITLS_ECDH_ANON_WITH_AES_128_CBC_SHA}, {"HITLS_ECDH_ANON_WITH_AES_256_CBC_SHA", HITLS_ECDH_ANON_WITH_AES_256_CBC_SHA}, {"HITLS_ECDHE_SM4_CBC_SM3", HITLS_ECDHE_SM4_CBC_SM3}, {"HITLS_ECC_SM4_CBC_SM3", HITLS_ECC_SM4_CBC_SM3}, {"HITLS_ECDHE_SM4_GCM_SM3", HITLS_ECDHE_SM4_GCM_SM3}, {"HITLS_ECC_SM4_GCM_SM3", HITLS_ECC_SM4_GCM_SM3}, /* error ciphersuite */ {"HITLS_INVALID_CIPHER_TC01", 0xFFFF}, {"HITLS_INVALID_CIPHER_TC02", 0xFFFE}, }; static const HitlsConfig g_groupList[] = { {"HITLS_EC_GROUP_BRAINPOOLP256R1", HITLS_EC_GROUP_BRAINPOOLP256R1}, {"HITLS_EC_GROUP_BRAINPOOLP384R1", HITLS_EC_GROUP_BRAINPOOLP384R1}, {"HITLS_EC_GROUP_BRAINPOOLP512R1", HITLS_EC_GROUP_BRAINPOOLP512R1}, {"HITLS_EC_GROUP_SECP256R1", HITLS_EC_GROUP_SECP256R1}, {"HITLS_EC_GROUP_SECP384R1", HITLS_EC_GROUP_SECP384R1}, {"HITLS_EC_GROUP_SECP521R1", HITLS_EC_GROUP_SECP521R1}, {"HITLS_EC_GROUP_CURVE25519", HITLS_EC_GROUP_CURVE25519}, {"HITLS_EC_GROUP_SM2", HITLS_EC_GROUP_SM2}, {"HITLS_INVALID_GROUP_TC01", 0xFF}, {"HITLS_INVALID_GROUP_TC02", 0xFE}, {"HITLS_FF_DHE_2048", HITLS_FF_DHE_2048}, {"HITLS_FF_DHE_3072", HITLS_FF_DHE_3072}, {"HITLS_FF_DHE_4096", HITLS_FF_DHE_4096}, {"HITLS_FF_DHE_6144", HITLS_FF_DHE_6144}, {"HITLS_FF_DHE_8192", HITLS_FF_DHE_8192}, {"SecP256r1MLKEM768", 4587}, // for new kem group {"X25519MLKEM768", 4588}, // for new kem group {"SecP384r1MLKEM1024", 4589}, // for new kem group {"test_new_group", 477}, // for new group {"test_new_group_kem", 478}, // NEW_KEM_ALGID {"test_new_group_with_new_key_type", 479}, // NEW_PKEY_ALGID }; static const HitlsConfig g_signatureList[] = { {"CERT_SIG_SCHEME_RSA_PKCS1_SHA1", CERT_SIG_SCHEME_RSA_PKCS1_SHA1}, {"CERT_SIG_SCHEME_ECDSA_SHA1", CERT_SIG_SCHEME_ECDSA_SHA1}, {"CERT_SIG_SCHEME_ECDSA_SHA224", CERT_SIG_SCHEME_ECDSA_SHA224}, {"CERT_SIG_SCHEME_RSA_PKCS1_SHA224", CERT_SIG_SCHEME_RSA_PKCS1_SHA224}, {"CERT_SIG_SCHEME_RSA_PKCS1_SHA256", CERT_SIG_SCHEME_RSA_PKCS1_SHA256}, {"CERT_SIG_SCHEME_RSA_PKCS1_SHA384", CERT_SIG_SCHEME_RSA_PKCS1_SHA384}, {"CERT_SIG_SCHEME_RSA_PKCS1_SHA512", CERT_SIG_SCHEME_RSA_PKCS1_SHA512}, {"CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256", CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}, {"CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384", CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384}, {"CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512", CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512}, {"CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256", CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256}, {"CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA384", CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA384}, {"CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA512", CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA512}, {"CERT_SIG_SCHEME_ED25519", CERT_SIG_SCHEME_ED25519}, {"CERT_SIG_SCHEME_ED448", CERT_SIG_SCHEME_ED448}, {"CERT_SIG_SCHEME_DSA_SHA1", CERT_SIG_SCHEME_DSA_SHA1}, {"CERT_SIG_SCHEME_DSA_SHA224", CERT_SIG_SCHEME_DSA_SHA224}, {"CERT_SIG_SCHEME_DSA_SHA256", CERT_SIG_SCHEME_DSA_SHA256}, {"CERT_SIG_SCHEME_DSA_SHA384", CERT_SIG_SCHEME_DSA_SHA384}, {"CERT_SIG_SCHEME_DSA_SHA512", CERT_SIG_SCHEME_DSA_SHA512}, {"CERT_SIG_SCHEME_SM2_SM3", CERT_SIG_SCHEME_SM2_SM3}, {"CERT_SIG_SCHEME_RSA_PSS_PSS_SHA256", CERT_SIG_SCHEME_RSA_PSS_PSS_SHA256}, {"CERT_SIG_SCHEME_RSA_PSS_PSS_SHA384", CERT_SIG_SCHEME_RSA_PSS_PSS_SHA384}, {"CERT_SIG_SCHEME_RSA_PSS_PSS_SHA512", CERT_SIG_SCHEME_RSA_PSS_PSS_SHA512}, {"HITLS_INVALID_SIG_TC01", 0xFFFF}, {"HITLS_INVALID_SIG_TC02", 0xFFFE}, {"test_new_sign_alg_name", 23333}, {"test_new_sign_alg_name_with_new_key_type", 24444}, }; static const HitlsConfig g_eccFormatList[] = { {"HITLS_POINT_FORMAT_UNCOMPRESSED", HITLS_POINT_FORMAT_UNCOMPRESSED}, {"HITLS_INVALID_FORMAT_TC01", 0xFF}, {"HITLS_INVALID_FORMAT_TC02", 0xFE}, }; #ifdef HITLS_TLS_MAINTAIN_KEYLOG static void KetLogPrint(HITLS_Ctx *ctx, const char *out) { (void)ctx; char *fileName = "FileKeyLog.txt"; char *fileEndStr = "\n"; char *p = getenv("HITLSKEYLOGFILE"); if (p == NULL) { return; } FILE *fp = fopen(fileName, "a+"); if (fp == NULL) { return; } fwrite(out, sizeof(char), strlen(out), fp); fwrite((char *)fileEndStr, sizeof(char), strlen(fileEndStr), fp); fclose(fp); } #endif int HitlsInit(void) { int ret; ret = RegMemCallback(MEM_CALLBACK_DEFAULT); ret |= RegCertCallback(CERT_CALLBACK_DEFAULT); #ifdef HITLS_TLS_FEATURE_PROVIDER CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_SHA256, "provider=default", NULL, 0, NULL); #else CRYPT_EAL_RandInit(CRYPT_RAND_SHA256, NULL, NULL, NULL, 0); HITLS_CryptMethodInit(); #endif return ret; } #ifdef HITLS_TLS_FEATURE_PROVIDER static HITLS_Lib_Ctx *InitProviderLibCtx(char *providerPath, char (*providerNames)[MAX_PROVIDER_NAME_LEN], int *providerLibFmts, int providerCnt) { int ret; HITLS_Lib_Ctx *libCtx = CRYPT_EAL_LibCtxNew(); if (libCtx == NULL) { LOG_ERROR("CRYPT_EAL_LibCtxNew Error"); return NULL; } if (providerPath != NULL && strlen(providerPath) > 0) { ret = CRYPT_EAL_ProviderSetLoadPath(libCtx, providerPath); if (ret != EOK) { CRYPT_EAL_LibCtxFree(libCtx); LOG_ERROR("CRYPT_EAL_ProviderSetLoadPath Error"); return NULL; } } for (int i = 0; i < providerCnt; i++) { ret = CRYPT_EAL_ProviderLoad(libCtx, (BSL_SAL_LibFmtCmd)providerLibFmts[i], providerNames[i], NULL, NULL); if (ret != EOK) { CRYPT_EAL_LibCtxFree(libCtx); LOG_ERROR("CRYPT_EAL_ProviderLoad Error"); return NULL; } char attrName[512] = {0}; memcpy_s(attrName, sizeof(attrName), "provider?", strlen("provider?")); memcpy_s(attrName + strlen("provider?"), sizeof(attrName) - strlen("provider?"), providerNames[i], strlen(providerNames[i])); CRYPT_EAL_ProviderRandInitCtx(libCtx, CRYPT_RAND_SHA256, attrName, NULL, 0, NULL); } return libCtx; } HITLS_Config *HitlsProviderNewCtx(char *providerPath, char (*providerNames)[MAX_PROVIDER_NAME_LEN], int *providerLibFmts, int providerCnt, char *attrName, TLS_VERSION tlsVersion) { char *tmpAttrName = NULL; if (attrName != NULL && strlen(attrName) > 0) { tmpAttrName = attrName; } HITLS_Config *hitlsConfig = NULL; HITLS_Lib_Ctx *libCtx = NULL; if (providerCnt > 0) { libCtx = InitProviderLibCtx(providerPath, providerNames, providerLibFmts, providerCnt); if (libCtx == NULL) { LOG_ERROR("InitProviderLibCtx Error"); return NULL; } } switch (tlsVersion) { case DTLS1_2: LOG_DEBUG("HiTLS New DTLS1_2 Ctx"); hitlsConfig = HITLS_CFG_ProviderNewDTLS12Config(libCtx, tmpAttrName); break; case TLS1_2: LOG_DEBUG("HiTLS New TLS1_2 Ctx"); hitlsConfig = HITLS_CFG_ProviderNewTLS12Config(libCtx, tmpAttrName); break; case TLS1_3: LOG_DEBUG("HiTLS New TLS1_3 Ctx"); hitlsConfig = HITLS_CFG_ProviderNewTLS13Config(libCtx, tmpAttrName); break; case TLS_ALL: LOG_DEBUG("HiTLS New TLS_ALL Ctx"); hitlsConfig = HITLS_CFG_ProviderNewTLSConfig(libCtx, tmpAttrName); break; #ifdef HITLS_TLS_PROTO_TLCP11 case TLCP1_1: LOG_DEBUG("HiTLS New TLCP1_1 Ctx"); hitlsConfig = HITLS_CFG_ProviderNewTLCPConfig(libCtx, tmpAttrName); break; #endif #ifdef HITLS_TLS_PROTO_DTLCP11 case DTLCP1_1: LOG_DEBUG("HiTLS New DTLCP1_1 Ctx"); hitlsConfig = HITLS_CFG_ProviderNewDTLCPConfig(libCtx, tmpAttrName); break; #endif default: /* Unknown protocol type */ break; } if (hitlsConfig == NULL) { CRYPT_EAL_LibCtxFree(libCtx); LOG_ERROR("HITLS Not Support This TlsVersion's ID %d", tlsVersion); } #ifdef HITLS_TLS_FEATURE_SECURITY // Setting the security level HITLS_CFG_SetSecurityLevel(hitlsConfig, HITLS_SECURITY_LEVEL_ZERO); #endif /* HITLS_TLS_FEATURE_SECURITY */ return hitlsConfig; } #endif HITLS_Config *HitlsNewCtx(TLS_VERSION tlsVersion) { HITLS_Config *hitlsConfig = NULL; switch (tlsVersion) { #ifdef HITLS_TLS_PROTO_DTLS12 case DTLS1_2: LOG_DEBUG("HiTLS New DTLS1_2 Ctx"); hitlsConfig = HITLS_CFG_NewDTLS12Config(); break; #endif #ifdef HITLS_TLS_PROTO_TLS12 case TLS1_2: LOG_DEBUG("HiTLS New TLS1_2 Ctx"); hitlsConfig = HITLS_CFG_NewTLS12Config(); break; #endif #ifdef HITLS_TLS_PROTO_TLS13 case TLS1_3: LOG_DEBUG("HiTLS New TLS1_3 Ctx"); hitlsConfig = HITLS_CFG_NewTLS13Config(); break; #endif #ifdef HITLS_TLS_PROTO_ALL case TLS_ALL: LOG_DEBUG("HiTLS New TLS_ALL Ctx"); hitlsConfig = HITLS_CFG_NewTLSConfig(); break; #endif #ifdef HITLS_TLS_PROTO_TLCP11 case TLCP1_1: LOG_DEBUG("HiTLS New TLCP1_1 Ctx"); hitlsConfig = HITLS_CFG_NewTLCPConfig(); break; #endif #ifdef HITLS_TLS_PROTO_DTLCP11 case DTLCP1_1: LOG_DEBUG("HiTLS New DTLCP1_1 Ctx"); hitlsConfig = HITLS_CFG_NewDTLCPConfig(); break; #endif default: /* Unknown protocol type */ break; } if (hitlsConfig == NULL) { LOG_ERROR("HITLS Not Support This TlsVersion's ID %d", tlsVersion); } #ifdef HITLS_TLS_FEATURE_SECURITY // Setting the security level HITLS_CFG_SetSecurityLevel(hitlsConfig, HITLS_SECURITY_LEVEL_ZERO); #endif /* HITLS_TLS_FEATURE_SECURITY */ return hitlsConfig; } void HitlsFreeCtx(void *ctx) { if (ctx == NULL) { return; } HITLS_CFG_FreeConfig(ctx); } static int32_t GetConfigVauleFromStr(const HitlsConfig *hitlsConfigList, uint32_t configSize, const char *cipherName) { for (uint32_t i = 0; i < configSize; i++) { if (strcmp(cipherName, hitlsConfigList[i].name) != 0) { continue; } return hitlsConfigList[i].configValue; } return ERROR; // The cipher suite does not exist. } static int8_t HitlsSetConfig(const HitlsConfig *hitlsConfigList, int configListSize, void *ctx, char *name, HitlsConfigType type) { int ret = 0; char configArray[MAX_CIPHERSUITES_LEN] = {0}; // A maximum of 512 characters are supported. char *token, *rest; int32_t configValue; uint16_t configValueArray[20] = {0}; // Currently, a maximum of 20 cipher suites are supported. uint32_t configSize = 0; ret = memcpy_s(configArray, sizeof(configArray), name, strlen(name)); ASSERT_RETURN(ret == EOK, "Memcpy Error"); configSize = 0; token = strtok_s(configArray, ":", &rest); do { // Currently, a maximum of 20 cipher suites are supported. ASSERT_RETURN(configSize < 20, "Max Support Set 20 Config"); configValue = GetConfigVauleFromStr(hitlsConfigList, configListSize, token); ASSERT_RETURN(configValue != ERROR, "GetConfigVauleFromStr Error"); configValueArray[configSize] = (uint16_t)configValue; token = strtok_s(NULL, ":", &rest); configSize++; } while (token != NULL); switch (type) { case CIPHER: ret = HITLS_CFG_SetCipherSuites(ctx, configValueArray, configSize); break; case GROUPS: ret = HITLS_CFG_SetGroups(ctx, configValueArray, configSize); break; case SIGNATURE: ret = HITLS_CFG_SetSignature(ctx, configValueArray, configSize); break; case POINTFORMAT: { uint8_t pointformatArray[20] = {0}; for (uint32_t i = 0; i < configSize; i++) { pointformatArray[i] = configValueArray[i]; } ret = HITLS_CFG_SetEcPointFormats(ctx, pointformatArray, configSize); break; } default: ret = ERROR; } ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetXXX Error"); return SUCCESS; } int HitlsSetCtx(HITLS_Config *outCfg, HLT_Ctx_Config *inCtxCfg) { int ret = 0; #ifdef HITLS_TLS_FEATURE_SESSION if (inCtxCfg->setSessionCache >= 0) { LOG_DEBUG("HiTLS Set SessionCache is %d", inCtxCfg->setSessionCache); HITLS_CFG_SetSessionCacheMode(outCfg, inCtxCfg->setSessionCache); } #endif #ifdef HITLS_TLS_PROTO_ALL // Set the protocol version. if ((inCtxCfg->minVersion != 0) && (inCtxCfg->maxVersion != 0)) { LOG_DEBUG("HiTLS Set minVersion is %u maxVersion is %u", inCtxCfg->minVersion, inCtxCfg->maxVersion); ret = HITLS_CFG_SetVersion(outCfg, inCtxCfg->minVersion, inCtxCfg->maxVersion); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetVersion Error ERROR"); } #endif if (inCtxCfg->SupportType == SERVER_CFG_SET_TRUE) { HITLS_CFG_SetCipherServerPreference(outCfg, true); } if (inCtxCfg->SupportType == SERVER_CFG_SET_FALSE) { HITLS_CFG_SetCipherServerPreference(outCfg, false); } #ifdef HITLS_TLS_FEATURE_RENEGOTIATION // Setting Renegotiation LOG_DEBUG("HiTLS Set Support Renegotiation is %d", inCtxCfg->isSupportRenegotiation); ret = HITLS_CFG_SetRenegotiationSupport(outCfg, inCtxCfg->isSupportRenegotiation); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetRenegotiationSupport ERROR"); // Whether allow a renegotiation initiated by the client LOG_DEBUG("HiTLS Set allow Client Renegotiate is %d", inCtxCfg->allowClientRenegotiate); ret = HITLS_CFG_SetClientRenegotiateSupport(outCfg, inCtxCfg->allowClientRenegotiate); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetClientRenegotiateSupport ERROR"); #endif #ifdef HITLS_TLS_FEATURE_CERT_MODE // Whether to enable dual-ended verification LOG_DEBUG("HiTLS Set Support Client Verify is %d", inCtxCfg->isSupportClientVerify); ret = HITLS_CFG_SetClientVerifySupport(outCfg, inCtxCfg->isSupportClientVerify); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetClientVerifySupport ERROR"); LOG_DEBUG("HiTLS Set readAhead is %d", inCtxCfg->readAhead); ret = HITLS_CFG_SetReadAhead(outCfg, inCtxCfg->readAhead); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetReadAhead ERROR"); // Indicates whether to allow empty certificate list on the client. LOG_DEBUG("HiTLS Set Support Not Client Cert is %d", inCtxCfg->isSupportNoClientCert); ret = HITLS_CFG_SetNoClientCertSupport(outCfg, inCtxCfg->isSupportNoClientCert); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetNoClientCertSupport ERROR"); #endif #ifdef HITLS_TLS_FEATURE_PHA // Whether to enable pha LOG_DEBUG("HiTLS Set Support pha is %d", inCtxCfg->isSupportPostHandshakeAuth); ret = HITLS_CFG_SetPostHandshakeAuthSupport(outCfg, inCtxCfg->isSupportPostHandshakeAuth); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetPostHandshakeAuth ERROR"); #endif // Indicates whether extended master keys are supported. LOG_DEBUG("HiTLS Set Support Extend Master Secret is %d", inCtxCfg->isSupportExtendMasterSecret); ret = HITLS_CFG_SetExtenedMasterSecretSupport(outCfg, inCtxCfg->isSupportExtendMasterSecret); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetExtenedMasterSecretSupport ERROR"); #ifdef HITLS_TLS_CONFIG_KEY_USAGE // Support CloseCheckKeyUsage LOG_DEBUG("HiTLS Set CloseCheckKeyUsage is false"); ret = HITLS_CFG_SetCheckKeyUsage(outCfg, inCtxCfg->needCheckKeyUsage); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetCheckKeyUsage ERROR"); #endif #ifdef HITLS_TLS_FEATURE_SESSION_TICKET // Indicates whether to support sessionTicket. LOG_DEBUG("HiTLS Set Support SessionTicket is %d", inCtxCfg->isSupportSessionTicket); ret = HITLS_CFG_SetSessionTicketSupport(outCfg, inCtxCfg->isSupportSessionTicket); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetSessionTicketSupport ERROR"); #endif #ifdef HITLS_TLS_SUITE_CIPHER_CBC // Whether encrypt-then-mac is supported LOG_DEBUG("HiTLS Set Support EncryptThenMac is %d", inCtxCfg->isEncryptThenMac); ret = HITLS_CFG_SetEncryptThenMac(outCfg, (uint32_t)inCtxCfg->isEncryptThenMac); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetEncryptThenMac ERROR"); #endif // ECC Point Format Configuration for Asymmetric Algorithms if (strncmp("NULL", inCtxCfg->pointFormats, strlen(inCtxCfg->pointFormats)) != 0) { LOG_DEBUG("HiTLS Set PoinFormats is %s", inCtxCfg->pointFormats); int configListSize = sizeof(g_eccFormatList) / sizeof(g_eccFormatList[0]); ret = HitlsSetConfig(g_eccFormatList, configListSize, outCfg, inCtxCfg->pointFormats, POINTFORMAT); ASSERT_RETURN(ret == SUCCESS, "ECC Format ERROR"); } // Loading cipher suites if (strncmp("NULL", inCtxCfg->cipherSuites, strlen(inCtxCfg->cipherSuites)) != 0) { LOG_DEBUG("HiTLS Set CipherSuites is %s", inCtxCfg->cipherSuites); int configListSize = sizeof(g_cipherSuiteList) / sizeof(g_cipherSuiteList[0]); ret = HitlsSetConfig(g_cipherSuiteList, configListSize, outCfg, inCtxCfg->cipherSuites, CIPHER); ASSERT_RETURN(ret == SUCCESS, "Hitls Set Cipher ERROR"); } // set groups if (strncmp("NULL", inCtxCfg->groups, strlen(inCtxCfg->groups)) != 0) { LOG_DEBUG("HiTLS Set Groups is %s", inCtxCfg->groups); int configListSize = sizeof(g_groupList) / sizeof(g_groupList[0]); ret = HitlsSetConfig(g_groupList, configListSize, outCfg, inCtxCfg->groups, GROUPS); ASSERT_RETURN(ret == SUCCESS, "Hitls Set Group ERROR"); } // signature algorithm if (strncmp("NULL", inCtxCfg->signAlgorithms, strlen(inCtxCfg->signAlgorithms)) != 0) { LOG_DEBUG("HiTLS Set SignAlgorithms is %s", inCtxCfg->signAlgorithms); int configListSize = sizeof(g_signatureList) / sizeof(g_signatureList[0]); ret = HitlsSetConfig(g_signatureList, configListSize, outCfg, inCtxCfg->signAlgorithms, SIGNATURE); ASSERT_RETURN(ret == SUCCESS, "Hitls Set Signature ERROR"); } #ifdef HITLS_TLS_FEATURE_SNI // sni if (strncmp("NULL", inCtxCfg->serverName, strlen(inCtxCfg->serverName)) != 0) { LOG_DEBUG("HiTLS Set ServerName is %s", inCtxCfg->serverName); ret = HITLS_CFG_SetServerName(outCfg, (uint8_t *)inCtxCfg->serverName, strlen(inCtxCfg->serverName)); ASSERT_RETURN(ret == SUCCESS, "Hitls Set ServerName ERROR"); } // Register the server_name function callback. if (strncmp("NULL", inCtxCfg->sniDealCb, strlen(inCtxCfg->sniDealCb)) != 0) { LOG_DEBUG("HiTLS Set server_name callback is %s", inCtxCfg->sniDealCb); ret = HITLS_CFG_SetServerNameCb(outCfg, GetExtensionCb(inCtxCfg->sniDealCb)); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetServerNameCb Fail"); } // Register values related to server_name. if (strncmp("NULL", inCtxCfg->sniArg, strlen(inCtxCfg->sniArg)) != 0) { LOG_DEBUG("HiTLS Set sniArg"); ret = HITLS_CFG_SetServerNameArg(outCfg, GetExampleData(inCtxCfg->sniArg)); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetServerNameArg Fail"); } #endif #ifdef HITLS_TLS_FEATURE_ALPN // alpn if (strncmp("NULL", inCtxCfg->alpnList, strlen(inCtxCfg->alpnList)) != 0) { LOG_DEBUG("HiTLS Set alpnList is %s", inCtxCfg->alpnList); ret = HITLS_CFG_SetAlpnProtos(outCfg, (const uint8_t *)inCtxCfg->alpnList, strlen(inCtxCfg->alpnList)); ASSERT_RETURN(ret == SUCCESS, "Hitls Set alpnList ERROR"); } // Sets the ALPN selection callback on the server. if (strncmp("NULL", inCtxCfg->alpnSelectCb, strlen(inCtxCfg->alpnSelectCb)) != 0) { LOG_DEBUG("HiTLS Set ALPN callback is %s", inCtxCfg->alpnSelectCb); ret = HITLS_CFG_SetAlpnProtosSelectCb( outCfg, GetExtensionCb(inCtxCfg->alpnSelectCb), GetExampleData(inCtxCfg->alpnUserData)); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetAlpnProtosSelectCb Fail"); } #endif // Loading Certificates ret = HiTLS_X509_LoadCertAndKey(outCfg, inCtxCfg->caCert, inCtxCfg->chainCert, inCtxCfg->eeCert, inCtxCfg->signCert, inCtxCfg->privKey, inCtxCfg->signPrivKey); ASSERT_RETURN(ret == SUCCESS, "Load cert Fail"); #ifdef HITLS_TLS_FEATURE_PSK if (strncmp("NULL", inCtxCfg->psk, strlen(inCtxCfg->psk)) != 0) { ret = ExampleSetPsk(inCtxCfg->psk); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetPskClientCallback Fail"); ret = HITLS_CFG_SetPskClientCallback(outCfg, ExampleClientCb); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetPskClientCallback Fail"); ret = HITLS_CFG_SetPskServerCallback(outCfg, ExampleServerCb); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetPskServerCallback Fail"); } #endif #if defined(HITLS_TLS_FEATURE_SESSION_TICKET) if (strncmp("NULL", inCtxCfg->ticketKeyCb, strlen(inCtxCfg->ticketKeyCb)) != 0) { LOG_DEBUG("HiTLS Set Ticker key callback is %s", inCtxCfg->ticketKeyCb); ret = HITLS_CFG_SetTicketKeyCallback(outCfg, GetTicketKeyCb(inCtxCfg->ticketKeyCb)); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetTicketKeyCallback Fail"); } #endif #ifdef HITLS_TLS_FEATURE_INDICATOR // Load link setup callback if (inCtxCfg->infoCb != NULL) { LOG_DEBUG("HiTLS Set info callback"); ret = HITLS_CFG_SetInfoCb(outCfg, inCtxCfg->infoCb); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetInfoCb Fail"); } if (inCtxCfg->msgCb != NULL) { LOG_DEBUG("HiTLS Set msg callback"); ret = HITLS_CFG_SetMsgCb(outCfg, inCtxCfg->msgCb); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetMsgCb Fail"); } if (inCtxCfg->msgArg != NULL) { LOG_DEBUG("HiTLS Set msgArg"); ret = HITLS_CFG_SetMsgCbArg(outCfg, inCtxCfg->msgArg); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetMsgCbArg Fail"); } #ifdef HITLS_TLS_FEATURE_CERT_CB if (inCtxCfg->certCb != NULL && inCtxCfg->certArg != NULL) { LOG_DEBUG("HiTLS Set cert callback"); ret = HITLS_CFG_SetCertCb(outCfg, inCtxCfg->certCb, inCtxCfg->certArg); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetCertCb Fail"); } #endif #ifdef HITLS_TLS_FEATURE_CLIENT_HELLO_CB if (inCtxCfg->clientHelloCb != NULL && inCtxCfg->clientHelloArg != NULL) { LOG_DEBUG("HiTLS Set clientHello callback"); ret = HITLS_CFG_SetClientHelloCb(outCfg, inCtxCfg->clientHelloCb, inCtxCfg->clientHelloArg); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetClientHelloCb Fail"); } #endif #endif #ifdef HITLS_TLS_FEATURE_FLIGHT // Sets whether to enable the function of sending handshake messages by flight. LOG_DEBUG("HiTLS Set Support isFlightTransmitEnable is %d", inCtxCfg->isFlightTransmitEnable); ret = HITLS_CFG_SetFlightTransmitSwitch(outCfg, inCtxCfg->isFlightTransmitEnable); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetFlightTransmitSwitch ERROR"); #endif #ifdef HITLS_TLS_FEATURE_SECURITY // Setting the security level LOG_DEBUG("HiTLS Set SecurityLevel is %d", inCtxCfg->securitylevel); ret = HITLS_CFG_SetSecurityLevel(outCfg, inCtxCfg->securitylevel); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetSecurityLevel ERROR"); #endif #ifdef HITLS_TLS_CONFIG_MANUAL_DH // Indicates whether the DH key length can be followed by the certificate. LOG_DEBUG("HiTLS Set Support DHAuto is %d", inCtxCfg->isSupportDhAuto); ret = HITLS_CFG_SetDhAutoSupport(outCfg, inCtxCfg->isSupportDhAuto); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetDhAutoSupport ERROR"); #endif #ifdef HITLS_TLS_PROTO_TLS13 // TLS1.3 key exchange mode if (outCfg->maxVersion == HITLS_VERSION_TLS13) { LOG_DEBUG("HiTLS Set keyExchMode is %u", inCtxCfg->keyExchMode); ret = HITLS_CFG_SetKeyExchMode(outCfg, inCtxCfg->keyExchMode); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetKeyExchMode ERROR"); } #endif #ifdef HITLS_TLS_FEATURE_CERT_MODE // Set whether to enable isSupportVerifyNone; LOG_DEBUG("HiTLS Set Support pha is %d", inCtxCfg->isSupportVerifyNone); ret = HITLS_CFG_SetVerifyNoneSupport(outCfg, inCtxCfg->isSupportVerifyNone); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetVerifyNoneSupport ERROR"); #endif LOG_DEBUG("HiTLS Set Empty Record Number is %u", inCtxCfg->emptyRecordsNum); ret = HITLS_CFG_SetEmptyRecordsNum(outCfg, inCtxCfg->emptyRecordsNum); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetEmptyRecordsNum ERROR"); #ifdef HITLS_TLS_FEATURE_MODE // HiTLS Set ModeSupport LOG_DEBUG("HiTLS Set ModeSupport is %u", inCtxCfg->modeSupport); ret = HITLS_CFG_SetModeSupport(outCfg, inCtxCfg->modeSupport); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetModeSupport ERROR"); #endif #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) LOG_DEBUG("HiTLS Set allow Legacy Renegotiate is %d", inCtxCfg->allowLegacyRenegotiate); ret = HITLS_CFG_SetLegacyRenegotiateSupport(outCfg, inCtxCfg->allowLegacyRenegotiate); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetLegacyRenegotiateSupport ERROR"); #endif /* defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) */ #ifdef HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES if (inCtxCfg->caList != NULL) { LOG_DEBUG("HiTLS Set caList"); ret = HITLS_CFG_SetCAList(outCfg, inCtxCfg->caList); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetCAList Fail"); } #endif /* HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES */ #ifdef HITLS_TLS_PROTO_TLS13 // Whether to support middlebox compatibility. LOG_DEBUG("HiTLS Set Support middlebox compatibility is %d", inCtxCfg->isMiddleBoxCompat); ret = HITLS_CFG_SetMiddleBoxCompat(outCfg, (uint32_t)inCtxCfg->isMiddleBoxCompat); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetMiddleBoxCompat ERROR"); #endif #ifdef HITLS_TLS_MAINTAIN_KEYLOG // Set the keylogcb callback function on the server. if (strncmp("NULL", inCtxCfg->keyLogCb, strlen(inCtxCfg->keyLogCb)) != 0) { LOG_DEBUG("HiTLS Set key log callback is %s", inCtxCfg->keyLogCb); ret = HITLS_CFG_SetKeyLogCb(outCfg, GetExtensionCb(inCtxCfg->keyLogCb)); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetKeyLogCb Fail"); } // support exporting keys through environment variables if (strncmp("NULL", inCtxCfg->keyLogCb, strlen(inCtxCfg->keyLogCb)) == 0) { ret = HITLS_CFG_SetKeyLogCb(outCfg, KetLogPrint); ASSERT_RETURN(ret == SUCCESS, "HITLS_CFG_SetKeyLogCb Fail"); } #endif return SUCCESS; } void *HitlsNewSsl(void *ctx) { return HITLS_New(ctx); } void HitlsFreeSsl(void *ssl) { HITLS_Ctx *ctx = (HITLS_Ctx *)ssl; #ifdef HITLS_TLS_FEATURE_PROVIDER HITLS_Lib_Ctx *libCtx = LIBCTX_FROM_CTX(ctx); HITLS_Free(ctx); CRYPT_EAL_LibCtxFree(libCtx); #else HITLS_Free(ctx); #endif } const BSL_UIO_Method *GetDefaultMethod(HILT_TransportType type) { switch (type) { #ifdef HITLS_BSL_UIO_TCP case TCP: return TcpGetDefaultMethod(); #endif #ifdef HITLS_BSL_UIO_UDP case UDP: return UdpGetDefaultMethod(); #endif default: break; } return NULL; } int HitlsSetSsl(void *ssl, HLT_Ssl_Config *sslConfig) { int ret; if (sslConfig->SupportType == SERVER_CTX_SET_TRUE) { HITLS_SetCipherServerPreference((HITLS_Ctx *)ssl, true); } if (sslConfig->SupportType == SERVER_CTX_SET_FALSE) { HITLS_SetCipherServerPreference((HITLS_Ctx *)ssl, false); } HILT_TransportType type = (sslConfig->connType == NONE_TYPE) ? SCTP : sslConfig->connType; BSL_UIO *uio = BSL_UIO_New(GetDefaultMethod(type)); ASSERT_RETURN(uio != NULL, "HITLS_SetUio Fail"); ret = BSL_UIO_Ctrl(uio, BSL_UIO_SET_FD, (int32_t)sizeof(sslConfig->sockFd), &sslConfig->sockFd); if (ret != SUCCESS) { LOG_ERROR("BSL_UIO_SET_FD Fail"); BSL_UIO_Free(uio); return ERROR; } if (BSL_UIO_GetTransportType(uio) == BSL_UIO_UDP) { BSL_SAL_SockAddr serverAddr = NULL; ret = SAL_SockAddrNew(&serverAddr); if (ret != BSL_SUCCESS) { LOG_ERROR("SAL_SockAddrNew failed\n"); BSL_UIO_Free(uio); return ret; } int32_t addrlen = (int32_t)SAL_SockAddrSize(serverAddr); if (getpeername(sslConfig->sockFd, (struct sockaddr *)serverAddr, (socklen_t *)&addrlen) == 0) { ret = BSL_UIO_Ctrl(uio, BSL_UIO_UDP_SET_CONNECTED, addrlen, serverAddr); if (ret != HITLS_SUCCESS) { LOG_ERROR("BSL_UIO_SET_PEER_IP_ADDR failed %d\n", addrlen); SAL_SockAddrFree(serverAddr); BSL_UIO_Free(uio); return ERROR; } } SAL_SockAddrFree(serverAddr); } BSL_UIO_SetInit(uio, 1); ret = HITLS_SetUio(ssl, uio); if (ret != SUCCESS) { LOG_ERROR("HITLS_SetUio Fail"); BSL_UIO_Free(uio); return ERROR; } // Release the UIO to prevent memory leakage. BSL_UIO_Free(uio); return SUCCESS; } void *HitlsAccept(void *ssl) { static int ret; int timeout = TIME_OUT_SEC; if (getenv("SSL_TIMEOUT") != NULL) { timeout = atoi(getenv("SSL_TIMEOUT")); } time_t start = time(NULL); LOG_DEBUG("HiTLS Tls Accept Ing..."); do { ret = HITLS_Accept(ssl); usleep(1000); // stay 1000us } while ((ret == HITLS_REC_NORMAL_RECV_BUF_EMPTY || ret == HITLS_REC_NORMAL_IO_BUSY || ret == HITLS_CALLBACK_CLIENT_HELLO_RETRY || ret == HITLS_CALLBACK_CERT_RETRY) && ((time(NULL) - start < timeout))); // usleep(1000) after each attemp. if (ret != SUCCESS) { LOG_ERROR("HITLS_Accept Error is %d", ret); } else { LOG_DEBUG("HiTLS Tls Accept Success"); } return &ret; } int HitlsConnect(void *ssl) { int ret; int timeout = TIME_OUT_SEC; if (getenv("SSL_TIMEOUT") != NULL) { timeout = atoi(getenv("SSL_TIMEOUT")); } time_t start = time(NULL); LOG_DEBUG("HiTLS Tls Connect Ing..."); do { ret = HITLS_Connect(ssl); usleep(1000); // stay 1000us } while ((ret == HITLS_REC_NORMAL_RECV_BUF_EMPTY || ret == HITLS_REC_NORMAL_IO_BUSY || ret == HITLS_CALLBACK_CERT_RETRY) && ((time(NULL) - start < timeout))); // usleep(1000) after each attemp. if (ret != SUCCESS) { LOG_ERROR("HITLS_Connect Error is %d", ret); } else { LOG_DEBUG("HiTLS Tls Connect Success"); } return ret; } int HitlsWrite(void *ssl, uint8_t *data, uint32_t dataLen) { int ret; int timeout = 4; if (getenv("SSL_TIMEOUT") != NULL) { timeout = atoi(getenv("SSL_TIMEOUT")); } time_t start = time(NULL); LOG_DEBUG("HiTLS Write Ing..."); uint32_t len = 0; do { ret = HITLS_Write(ssl, data, dataLen, &len); usleep(1000); // stay 1000us } while ((ret == HITLS_REC_NORMAL_RECV_BUF_EMPTY || ret == HITLS_REC_NORMAL_IO_BUSY) && (time(NULL) - start < timeout)); // A maximum of 4000 calls LOG_DEBUG("HiTLS Write Result is %d", ret); return ret; } int HitlsRead(void *ssl, uint8_t *data, uint32_t bufSize, uint32_t *readLen) { int ret; int timeout = 8; if (getenv("SSL_TIMEOUT") != NULL) { timeout = atoi(getenv("SSL_TIMEOUT")); } time_t start = time(NULL); LOG_DEBUG("HiTLS Read Ing..."); do { ret = HITLS_Read(ssl, data, bufSize, readLen); usleep(1000); // stay 1000us } while ((ret == HITLS_REC_NORMAL_RECV_BUF_EMPTY || ret == HITLS_REC_NORMAL_IO_BUSY || ret == HITLS_CALLBACK_CERT_RETRY) && ((time(NULL) - start < timeout))); // A maximum of 8000 calls LOG_DEBUG("HiTLS Read Result is %d", ret); return ret; } int HitlsClose(void *ctx) { return HITLS_Close(ctx); } int HitlsRenegotiate(void *ssl) { #ifdef HITLS_TLS_FEATURE_RENEGOTIATION return HITLS_Renegotiate(ssl); #else (void)ssl; return -1; #endif } int HitlsSetMtu(void *ssl, uint16_t mtu) { #ifdef HITLS_TLS_PROTO_DTLS12 return HITLS_SetMtu(ssl, mtu); #else (void)ssl; (void)mtu; return -1; #endif } int HitlsSetSession(void *ssl, void *session) { #ifdef HITLS_TLS_FEATURE_SESSION return HITLS_SetSession(ssl, session); #else (void)ssl; (void)session; return -1; #endif } int HitlsSessionReused(void *ssl) { uint8_t isReused = 0; (void)ssl; #ifdef HITLS_TLS_FEATURE_SESSION int32_t ret; ret = HITLS_IsSessionReused(ssl, &isReused); if (ret != HITLS_SUCCESS) { return 0; } #endif return (int)isReused; } void *HitlsGet1Session(void *ssl) { #ifdef HITLS_TLS_FEATURE_SESSION return HITLS_GetDupSession(ssl); #else (void)ssl; return NULL; #endif } int HitlsSessionHasTicket(void *session) { #ifdef HITLS_TLS_FEATURE_SESSION_TICKET return (HITLS_SESS_HasTicket(session) ? 1 : 0); #else (void)session; return 0; #endif } int HitlsSessionIsResumable(void *session) { #ifdef HITLS_TLS_FEATURE_SESSION_TICKET return (HITLS_SESS_IsResumable(session) ? 1 : 0); #else (void)session; return 0; #endif } void HitlsFreeSession(void *session) { #ifdef HITLS_TLS_FEATURE_SESSION HITLS_SESS_Free(session); #else (void)session; #endif } int HitlsGetErrorCode(void *ssl) { return HITLS_GetErrorCode(ssl); }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/rpc/src/hitls_func.c
C
unknown
42,340
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <semaphore.h> #include "securec.h" #include "logger.h" #include "process.h" #include "handle_cmd.h" #include "hlt.h" #include "tls_res.h" #include "common_func.h" #include "hitls_func.h" #include "sctp_channel.h" #include "tcp_channel.h" #include "udp_channel.h" #include "socket_common.h" #include "cert_callback.h" #include "sctp_channel.h" #include "frame_tls.h" #define DOMAIN_PATH_LEN (128) #define CMD_MAX_LEN 1024 #define SUCCESS 0 #define ERROR (-1) int g_acceptFd; void* HLT_TlsNewCtx(TLS_VERSION tlsVersion) { int ret; void *ctx = NULL; Process *process; process = GetProcess(); switch (process->tlsType) { case HITLS: ctx = HitlsNewCtx(tlsVersion); break; default: ctx = NULL; } if ((process->remoteFlag == 0) && (ctx != NULL)) { // If the value is LocalProcess, insert it to the CTX linked list. ret = InsertCtxToList(ctx); if (ret == ERROR) { LOG_ERROR("InsertCtxToList ERROR"); return NULL; } } return ctx; } #ifdef HITLS_TLS_FEATURE_PROVIDER void* HLT_TlsProviderNewCtx(char *providerPath, char (*providerNames)[MAX_PROVIDER_NAME_LEN], int *providerLibFmts, int providerCnt, char *attrName, TLS_VERSION tlsVersion) { int ret; void *ctx = NULL; Process *process; process = GetProcess(); switch (process->tlsType) { case HITLS: ctx = HitlsProviderNewCtx(providerPath, providerNames, providerLibFmts, providerCnt, attrName, tlsVersion); break; default: ctx = NULL; } if ((process->remoteFlag == 0) && (ctx != NULL)) { // If the value is LocalProcess, insert it to the CTX linked list. ret = InsertCtxToList(ctx); if (ret == ERROR) { LOG_ERROR("InsertCtxToList ERROR"); return NULL; } } return ctx; } #endif void* HLT_TlsNewSsl(void *ctx) { int ret; void *ssl = NULL; Process *process; process = GetProcess(); switch (process->tlsType) { case HITLS: LOG_DEBUG("Hitls New Ssl"); ssl = HitlsNewSsl(ctx); break; default: ssl = NULL; } if ((process->remoteFlag == 0) && (ssl != NULL)) { // If the value is LocalProcess, insert it to the SSL linked list. ret = InsertSslToList(ctx, ssl); if (ret == ERROR) { LOG_ERROR("InsertSslToList ERROR"); return NULL; } } return ssl; } int HLT_TlsSetCtx(void *ctx, HLT_Ctx_Config *ctxConfig) { int ret; Process *process = GetProcess(); switch (process->tlsType) { case HITLS: LOG_DEBUG("HiTLS Set Ctx's Config"); ret = HitlsSetCtx(ctx, ctxConfig); break; default: ret = ERROR; } return ret; } int HLT_TlsSetSsl(void *ssl, HLT_Ssl_Config *sslConfig) { int ret = ERROR; Process *process = GetProcess(); switch (process->tlsType) { case HITLS: LOG_DEBUG("HiTLS Set Ssl's Config"); ret = HitlsSetSsl(ssl, sslConfig); break; default: LOG_DEBUG("Unknown tls type"); break; } return ret; } // listen non-blocking interface unsigned long int HLT_TlsListen(void *ssl) { (void)ssl; Process *process = GetProcess(); switch (process->tlsType) { case HITLS : { return ERROR; // Hitls does not support the listen function. } default: return ERROR; } } // listen blocking interface int HLT_TlsListenBlock(void* ssl) { (void)ssl; Process *process = GetProcess(); switch (process->tlsType) { case HITLS : return ERROR; // Hitls does not support the listen function. default: return ERROR; } } // Non-blocking interface unsigned long int HLT_TlsAccept(void *ssl) { (void)ssl; unsigned long int ret = ERROR; Process *process = GetProcess(); pthread_t t_id; switch (process->tlsType) { case HITLS : ret = pthread_create(&t_id, NULL, (void*)HitlsAccept, (void*)ssl); break; default: break; } if (ret != 0) { return ret; } return t_id; } int HLT_TlsAcceptBlock(void *ssl) { Process *process; process = GetProcess(); switch (process->tlsType) { case HITLS: return *(int *)HitlsAccept(ssl); default: return ERROR; } } int HLT_GetTlsAcceptResultFromId(unsigned long int threadId) { pthread_join(threadId, NULL); return SUCCESS; } int HLT_GetTlsAcceptResult(HLT_Tls_Res* tlsRes) { static int ret; if (tlsRes->acceptId <= 0) { LOG_ERROR("This Res Has Not acceptId"); return ERROR; } if (tlsRes->ctx == NULL) { // Indicates that the remote process accepts the request. ret = HLT_RpcGetTlsAcceptResult(tlsRes->acceptId); } else { // Indicates that the local process accepts the request. int *tmp = NULL; pthread_join(tlsRes->acceptId, (void**)&tmp); if (tmp == NULL) { return ERROR; } ret = *tmp; tlsRes->acceptId = 0; return ret; } tlsRes->acceptId = 0; return ret; } int HLT_TlsConnect(void *ssl) { Process *process; process = GetProcess(); switch (process->tlsType) { case HITLS: return HitlsConnect(ssl); default: return ERROR; } } int HLT_TlsWrite(void *ssl, uint8_t *data, uint32_t dataLen) { Process *process; process = GetProcess(); switch (process->tlsType) { case HITLS : { LOG_DEBUG("Hitls Write Ing..."); return HitlsWrite(ssl, data, dataLen); } default: return ERROR; } } int HLT_TlsRead(void *ssl, uint8_t *data, uint32_t bufSize, uint32_t *readLen) { Process *process; process = GetProcess(); switch (process->tlsType) { case HITLS: { LOG_DEBUG("Hitls Read Ing..."); return HitlsRead(ssl, data, bufSize, readLen); } default: return ERROR; } } int HLT_TlsRenegotiate(void *ssl) { Process *process; process = GetProcess(); switch (process->tlsType) { case HITLS: return HitlsRenegotiate(ssl); default: return ERROR; } } int HLT_TlsVerifyClientPostHandshake(void *ssl) { #ifdef HITLS_TLS_FEATURE_PHA Process *process; process = GetProcess(); switch (process->tlsType) { case HITLS: return HITLS_VerifyClientPostHandshake(ssl); default: return ERROR; } #else (void)ssl; #endif return ERROR; } int HLT_TlsClose(void *ssl) { Process *process; process = GetProcess(); switch (process->tlsType) { case HITLS: return HitlsClose(ssl); default: return ERROR; } } int HLT_TlsSetSession(void *ssl, void *session) { Process *process; process = GetProcess(); switch (process->tlsType) { case HITLS: return (HitlsSetSession(ssl, session) == 0) ? 1 : 0; default: return ERROR; } } int HLT_TlsSessionReused(void *ssl) { Process *process; process = GetProcess(); switch (process->tlsType) { case HITLS: return HitlsSessionReused(ssl); default: return ERROR; } } void *HLT_TlsGet1Session(void *ssl) { Process *process; process = GetProcess(); switch (process->tlsType) { case HITLS: return HitlsGet1Session(ssl); default: return NULL; } } int32_t HLT_SetSessionCacheMode(HLT_Ctx_Config* config, HITLS_SESS_CACHE_MODE mode) { config->setSessionCache = mode; return SUCCESS; } int32_t HLT_SetSessionTicketSupport(HLT_Ctx_Config* config, bool issupport) { config->isSupportSessionTicket = issupport; return SUCCESS; } int HLT_TlsSessionHasTicket(void *session) { Process *process; process = GetProcess(); switch (process->tlsType) { case HITLS: return HitlsSessionHasTicket(session); default: return ERROR; } } int HLT_TlsSessionIsResumable(void *session) { Process *process; process = GetProcess(); switch (process->tlsType) { case HITLS: return HitlsSessionIsResumable(session); default: return ERROR; } } void HLT_TlsFreeSession(void *session) { Process *process; process = GetProcess(); switch (process->tlsType) { case HITLS: HitlsFreeSession(session); break; default: break; } } int RunDataChannelBind(void *param) { int sockFd = -1; LOG_DEBUG("RunDataChannelBind Ing...\n"); DataChannelParam *channelParam = (DataChannelParam*)param; switch (channelParam->type) { #ifdef HITLS_BSL_UIO_TCP case TCP: sockFd = TcpBind(channelParam->port); break; #endif #ifdef HITLS_BSL_UIO_UDP case UDP: sockFd = UdpBind(channelParam->port); break; #endif default: return ERROR; } struct sockaddr_in add; socklen_t len = sizeof(add); getsockname(sockFd, (struct sockaddr *)&add, &len); channelParam->port = ntohs(add.sin_port); channelParam->bindFd = sockFd; g_acceptFd = sockFd; return sockFd; } int RunDataChannelAccept(void *param) { int sockFd = -1; LOG_DEBUG("RunDataChannelAccept Ing...\n"); DataChannelParam *channelParam = (DataChannelParam *)param; switch (channelParam->type) { #ifdef HITLS_BSL_UIO_TCP case TCP: sockFd = TcpAccept(channelParam->ip, channelParam->bindFd, channelParam->isBlock, true); break; #endif #ifdef HITLS_BSL_UIO_UDP case UDP: sockFd = UdpAccept(channelParam->ip, channelParam->bindFd, channelParam->isBlock, false); #endif break; default: return ERROR; } g_acceptFd = sockFd; return sockFd; } pthread_t HLT_DataChannelAccept(DataChannelParam *channelParam) { pthread_t t_id; if (pthread_create(&t_id, NULL, (void*)RunDataChannelAccept, (void*)channelParam) != 0) { LOG_ERROR("Create Thread HLT_RpcDataChannelAccept Error ..."); return 0; } return t_id; } int HLT_DataChannelBind(DataChannelParam *channelParam) { return RunDataChannelBind(channelParam); } int HLT_DataChannelConnect(DataChannelParam *dstChannelParam) { switch (dstChannelParam->type) { #ifdef HITLS_BSL_UIO_TCP case TCP: return TcpConnect(dstChannelParam->ip, dstChannelParam->port); #endif #ifdef HITLS_BSL_UIO_UDP case UDP: return UdpConnect(dstChannelParam->ip, dstChannelParam->port); #endif default: return ERROR; } return ERROR; } int HLT_GetAcceptFd(pthread_t threadId) { pthread_join(threadId, NULL); return g_acceptFd; } HLT_FD HLT_CreateDataChannel(HLT_Process *process1, HLT_Process *process2, DataChannelParam channelParam) { int acceptId; int bindFd; unsigned long int pthreadId; HLT_FD sockFd; char *userPort = getenv("FIXED_PORT"); if (userPort == NULL) { channelParam.port = 0; // The system randomly allocates available ports. } if (process2->remoteFlag == 1) { bindFd = HLT_RpcDataChannelBind(process2, &channelParam); } else { bindFd = HLT_DataChannelBind(&channelParam); } channelParam.bindFd = bindFd; // Start Accept again. if (process2->remoteFlag == 1) { acceptId = HLT_RpcDataChannelAccept(process2, &channelParam); } else { pthreadId = HLT_DataChannelAccept(&channelParam); } // In Connect if (process1->remoteFlag == 1) { sockFd.srcFd = HLT_RpcDataChannelConnect(process1, &channelParam); } else { sockFd.srcFd = HLT_DataChannelConnect(&channelParam); } if (process2->remoteFlag == 1) { if (sockFd.srcFd > 0) { // Indicates that the CONNECT is successful. sockFd.peerFd = HLT_RpcGetAcceptFd(acceptId); } else { sockFd.peerFd = -1; } } else { if (sockFd.srcFd > 0) { // Indicates that the CONNECT is successful. sockFd.peerFd = HLT_GetAcceptFd(pthreadId); sockFd.sockAddr = channelParam.sockAddr; sockFd.connPort = channelParam.port; } else { // If the SCTP link fails to be established, delete the thread to avoid congestion. pthread_cancel(pthreadId); pthread_join(pthreadId, NULL); } } return sockFd; } void HLT_CloseFd(int fd, int linkType) { switch (linkType) { #ifdef HITLS_BSL_UIO_TCP case TCP: TcpClose(fd); break; #endif #ifdef HITLS_BSL_UIO_UDP case UDP: UdpClose(fd); break; #endif default: /* Unknown fd type */ break; } } HLT_Ctx_Config* HLT_NewCtxConfigTLCP(char *setFile, const char *key, bool isClient) { (void)setFile; Process *localProcess; HLT_Ctx_Config *ctxConfig = (HLT_Ctx_Config*)calloc(sizeof(HLT_Ctx_Config), 1u); if (ctxConfig == NULL) { return NULL; } ctxConfig->isSupportRenegotiation = false; ctxConfig->allowClientRenegotiate = false; ctxConfig->allowLegacyRenegotiate = false; ctxConfig->isSupportClientVerify = false; ctxConfig->isSupportNoClientCert = false; ctxConfig->isSupportExtendMasterSecret = false; ctxConfig->isClient = isClient; ctxConfig->setSessionCache = 2; HLT_SetGroups(ctxConfig, "NULL"); HLT_SetCipherSuites(ctxConfig, "NULL"); HLT_SetTls13CipherSuites(ctxConfig, "NULL"); HLT_SetSignature(ctxConfig, "NULL"); HLT_SetEcPointFormats(ctxConfig, "NULL"); HLT_SetPassword(ctxConfig, "NULL"); HLT_SetPsk(ctxConfig, "NULL"); HLT_SetTicketKeyCb(ctxConfig, "NULL"); if (strncmp("SERVER", key, strlen(key)) == 0) { HLT_SetCertPath(ctxConfig, SM2_VERIFY_PATH, SM2_CHAIN_PATH, SM2_SERVER_ENC_CERT_PATH, SM2_SERVER_ENC_KEY_PATH, SM2_SERVER_SIGN_CERT_PATH, SM2_SERVER_SIGN_KEY_PATH); } else if (strncmp("CLIENT", key, strlen(key)) == 0) { HLT_SetCertPath(ctxConfig, SM2_VERIFY_PATH, SM2_CHAIN_PATH, SM2_CLIENT_ENC_CERT_PATH, SM2_CLIENT_ENC_KEY_PATH, SM2_CLIENT_SIGN_CERT_PATH, SM2_CLIENT_SIGN_KEY_PATH); } else { free(ctxConfig); ctxConfig = NULL; return NULL; } // Store CTX configuration resources and release them later. localProcess = GetProcess(); localProcess->tlsResArray[localProcess->tlsResNum] = ctxConfig; localProcess->tlsResNum++; return ctxConfig; } HLT_Ctx_Config* HLT_NewCtxConfig(char *setFile, const char *key) { (void)setFile; HLT_Ctx_Config *ctxConfig; Process *localProcess; ctxConfig = (HLT_Ctx_Config*)malloc(sizeof(HLT_Ctx_Config)); if (ctxConfig == NULL) { return NULL; } (void)memset_s(ctxConfig, sizeof(HLT_Ctx_Config), 0, sizeof(HLT_Ctx_Config)); ctxConfig->needCheckKeyUsage = false; ctxConfig->isSupportRenegotiation = false; ctxConfig->allowClientRenegotiate = false; ctxConfig->allowLegacyRenegotiate = false; ctxConfig->isSupportClientVerify = false; ctxConfig->isSupportNoClientCert = false; ctxConfig->isSupportVerifyNone = false; ctxConfig->isSupportPostHandshakeAuth = false; ctxConfig->isSupportExtendMasterSecret = true; ctxConfig->isSupportSessionTicket = false; ctxConfig->isSupportDhAuto = true; ctxConfig->isEncryptThenMac = true; ctxConfig->isMiddleBoxCompat = true; ctxConfig->keyExchMode = TLS13_KE_MODE_PSK_WITH_DHE; ctxConfig->setSessionCache = HITLS_SESS_CACHE_SERVER; ctxConfig->mtu = 0; ctxConfig->infoCb = NULL; ctxConfig->securitylevel = HITLS_SECURITY_LEVEL_ZERO; ctxConfig->SupportType = 0; ctxConfig->readAhead = 1; ctxConfig->emptyRecordsNum = 32; HLT_SetGroups(ctxConfig, "NULL"); HLT_SetCipherSuites(ctxConfig, "NULL"); HLT_SetTls13CipherSuites(ctxConfig, "NULL"); HLT_SetSignature(ctxConfig, "NULL"); HLT_SetEcPointFormats(ctxConfig, "HITLS_POINT_FORMAT_UNCOMPRESSED"); HLT_SetPassword(ctxConfig, "NULL"); HLT_SetPsk(ctxConfig, "NULL"); HLT_SetTicketKeyCb(ctxConfig, "NULL"); HLT_SetServerName(ctxConfig, "NULL"); HLT_SetServerNameCb(ctxConfig, "NULL"); HLT_SetServerNameArg(ctxConfig, "NULL"); HLT_SetAlpnProtos(ctxConfig, "NULL"); HLT_SetAlpnProtosSelectCb(ctxConfig, "NULL", "NULL"); if (strncmp("SERVER", key, strlen(key)) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA256_CA_PATH, ECDSA_SHA256_CHAIN_PATH, ECDSA_SHA256_EE_PATH1, ECDSA_SHA256_PRIV_PATH1, "NULL", "NULL"); } else if (strncmp("CLIENT", key, strlen(key)) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA256_CA_PATH, ECDSA_SHA256_CHAIN_PATH, ECDSA_SHA256_EE_PATH2, ECDSA_SHA256_PRIV_PATH2, "NULL", "NULL"); } else { free(ctxConfig); ctxConfig = NULL; return NULL; } // Store CTX configuration resources and release them later. localProcess = GetProcess(); localProcess->tlsResArray[localProcess->tlsResNum] = ctxConfig; localProcess->tlsResNum++; return ctxConfig; } HLT_Ssl_Config *HLT_NewSslConfig(char *setFile) { (void)setFile; HLT_Ssl_Config *sslConfig; Process *localProcess; sslConfig = (HLT_Ssl_Config*)malloc(sizeof(HLT_Ssl_Config)); if (sslConfig == NULL) { return NULL; } (void)memset_s(sslConfig, sizeof(HLT_Ssl_Config), 0, sizeof(HLT_Ssl_Config)); // Store SSL configuration resources and release them later. localProcess = GetProcess(); localProcess->tlsResArray[localProcess->tlsResNum] = sslConfig; localProcess->tlsResNum++; return sslConfig; } int HLT_LibraryInit(TLS_TYPE tlsType) { switch (tlsType) { case HITLS: return HitlsInit(); break; default: /* Unknown type */ break; } return ERROR; } int HLT_TlsRegCallback(TlsCallbackType type) { switch (type) { case HITLS_CALLBACK_DEFAULT: FRAME_Init(); break; default: return SUCCESS; } return SUCCESS; } void HLT_FreeAllProcess(void) { int ret; HLT_Tls_Res* tlsRes; Process *remoteProcess; Process *localProcess = GetProcess(); if (localProcess == NULL) { return; } if (localProcess->remoteFlag != 0) { LOG_ERROR("Only Local Process Can Call HLT_FreeAllProcess"); return; } // Clearing HLT_Tls_Res and Threads for (int i = 0; i < localProcess->hltTlsResNum; i++) { tlsRes = localProcess->hltTlsResArray[i]; alarm(60); // Avoid long waits if ((tlsRes->acceptId > 0) && (tlsRes->ctx != NULL)) { pthread_join(tlsRes->acceptId, NULL); } free(tlsRes); } // Sends a signal for the peer process to exit. remoteProcess = GetProcessFromList(); while (remoteProcess != NULL) { ret = HLT_RpcProcessExit(remoteProcess); if (ret != SUCCESS) { LOG_ERROR("HLT_RpcProcessExit Error"); } free(remoteProcess); remoteProcess = GetProcessFromList(); } // Clearing Local Resources // Clearing Ports if (localProcess->connFd > 0) { close(localProcess->connFd); } // Clear the TlsRes linked list. FreeTlsResList(); // Clear CTX SSL configuration resources. for (int i = 0; i < localProcess->tlsResNum; i++) { free(localProcess->tlsResArray[i]); } // Clear the linked list of the remote process. FreeProcessResList(); // Clear local control connection resources FreeControlChannelRes(); // Clear local processes. FreeProcess(); return; } int HLT_FreeResFromSsl(const void *ssl) { return FreeResFromSsl(ssl); } static int LocalProcessTlsInit(HLT_Process *process, TLS_VERSION tlsVersion, HLT_Ctx_Config *ctxConfig, HLT_Ssl_Config *sslConfig, HLT_Tls_Res *tlsRes) { void *ctx, *ssl; #ifdef HITLS_TLS_FEATURE_PROVIDER ctx = HLT_TlsProviderNewCtx(ctxConfig->providerPath, ctxConfig->providerNames, ctxConfig->providerLibFmts, ctxConfig->providerCnt, ctxConfig->attrName, tlsVersion); #else ctx = HLT_TlsNewCtx(tlsVersion); #endif if (ctx == NULL) { LOG_ERROR("HLT_TlsNewCtx or HLT_TlsProviderNewCtx ERROR"); return ERROR; } if (HLT_TlsSetCtx(ctx, ctxConfig) != SUCCESS) { LOG_ERROR("HLT_TlsSetCtx ERROR"); return ERROR; } ssl = HLT_TlsNewSsl(ctx); if (ssl == NULL) { LOG_ERROR("HLT_TlsNewSsl ERROR"); return ERROR; } // When FD is 0, the default configuration is used. if (sslConfig->sockFd == 0) { sslConfig->sockAddr = process->sockAddr; sslConfig->sockFd = process->connFd; sslConfig->connType = process->connType; } if (HLT_TlsSetSsl(ssl, sslConfig) != SUCCESS) { LOG_ERROR("HLT_TlsSetSsl ERROR"); return ERROR; } if (ctxConfig->mtu > 0) { if (HLT_TlsSetMtu(ssl, ctxConfig->mtu) != SUCCESS) { LOG_ERROR("HLT_TlsSetMtu ERROR"); return ERROR; } } tlsRes->ctx = ctx; tlsRes->ssl = ssl; tlsRes->ctxId = -1; // -1 indicates that the field is discarded. tlsRes->sslId = -1; // -1 indicates that the field is discarded. return SUCCESS; } static int RemoteProcessTlsInit(HLT_Process *process, TLS_VERSION tlsVersion, HLT_Ctx_Config *ctxConfig, HLT_Ssl_Config *sslConfig, HLT_Tls_Res *tlsRes) { int ctxId; int sslId; #ifdef HITLS_TLS_FEATURE_PROVIDER ctxId = HLT_RpcProviderTlsNewCtx(process, tlsVersion, ctxConfig->isClient, ctxConfig->providerPath, ctxConfig->providerNames, ctxConfig->providerLibFmts, ctxConfig->providerCnt, ctxConfig->attrName); #else ctxId = HLT_RpcTlsNewCtx(process, tlsVersion, ctxConfig->isClient); #endif if (ctxId < 0) { LOG_ERROR("HLT_RpcTlsNewCtx ERROR"); return ERROR; } if (HLT_RpcTlsSetCtx(process, ctxId, ctxConfig) != SUCCESS) { LOG_ERROR("HLT_RpcTlsSetCtx ERROR"); return ERROR; } sslId = HLT_RpcTlsNewSsl(process, ctxId); if (sslId < 0) { LOG_ERROR("HLT_RpcTlsNewSsl ERROR"); return ERROR; } // When FD is 0, the default configuration is used. if (sslConfig->sockFd == 0) { sslConfig->connPort = process->connPort; sslConfig->sockFd = process->connFd; sslConfig->connType = process->connType; } if (HLT_RpcTlsSetSsl(process, sslId, sslConfig) != SUCCESS) { LOG_ERROR("HLT_RpcTlsSetSsl ERROR"); return ERROR; } if (ctxConfig->mtu > 0) { if (HLT_RpcTlsSetMtu(process, sslId, ctxConfig->mtu) != SUCCESS) { LOG_ERROR("HLT_RpcTlsSetMtu ERROR"); return ERROR; } } tlsRes->ctx = NULL; tlsRes->ssl = NULL; tlsRes->ctxId = ctxId; tlsRes->sslId = sslId; return SUCCESS; } HLT_Tls_Res *HLT_ProcessTlsInit(HLT_Process *process, TLS_VERSION tlsVersion, HLT_Ctx_Config *ctxConfig, HLT_Ssl_Config *sslConfig) { int ret; HLT_Tls_Res *tlsRes = (HLT_Tls_Res*)malloc(sizeof(HLT_Tls_Res)); if (tlsRes == NULL) { LOG_ERROR("Malloc TlsRes ERROR"); return NULL; } // Checking Configuration Parameters if (ctxConfig == NULL) { ctxConfig = HLT_NewCtxConfig(NULL, "SERVER"); } if (sslConfig == NULL) { sslConfig = HLT_NewSslConfig(NULL); } if ((ctxConfig == NULL) || (sslConfig == NULL)) { LOG_ERROR("ctxConfig or sslConfig is NULL"); goto ERR; } sslConfig->SupportType = ctxConfig->SupportType; // Check whether the call is invoked by the local process or by the RPC. if (process->remoteFlag == 0) { ret = LocalProcessTlsInit(process, tlsVersion, ctxConfig, sslConfig, tlsRes); if (ret == ERROR) { LOG_ERROR("LocalProcessTlsInit ERROR"); goto ERR; } } else { ret = RemoteProcessTlsInit(process, tlsVersion, ctxConfig, sslConfig, tlsRes); if (ret == ERROR) { LOG_ERROR("RemoteProcessTlsInit ERROR"); goto ERR; } } // The configuration resources of the HLT_Tls_Res table are stored and will be released later. Process *localProcess = GetProcess(); tlsRes->acceptId = 0; localProcess->hltTlsResArray[localProcess->hltTlsResNum] = tlsRes; localProcess->hltTlsResNum++; return tlsRes; ERR: free(tlsRes); return NULL; } int HLT_TlsSetMtu(void *ssl, uint16_t mtu) { Process *process; process = GetProcess(); switch (process->tlsType) { case HITLS: return HitlsSetMtu(ssl, mtu); default: break; } return ERROR; } int HLT_TlsGetErrorCode(void *ssl) { return HitlsGetErrorCode(ssl); } HLT_Tls_Res* HLT_ProcessTlsAccept(HLT_Process *process, TLS_VERSION tlsVersion, HLT_Ctx_Config *ctxConfig, HLT_Ssl_Config *sslConfig) { unsigned long int acceptId; HLT_Tls_Res *tlsRes = NULL; tlsRes = HLT_ProcessTlsInit(process, tlsVersion, ctxConfig, sslConfig); if (tlsRes == NULL) { LOG_ERROR("HLT_ProcessTlsInit ERROR"); return NULL; } // Check whether the call is invoked by the local process or by the RPC. if (process->remoteFlag == 0) { acceptId = HLT_TlsAccept(tlsRes->ssl); if (acceptId == (unsigned long int)ERROR) { LOG_ERROR("HLT_TlsAccept ERROR"); return NULL; } } else { acceptId = HLT_RpcTlsAccept(process, tlsRes->sslId); if (acceptId == (unsigned long int)ERROR) { LOG_ERROR("HLT_TlsAccept ERROR"); return NULL; } } tlsRes->acceptId = acceptId; return tlsRes; } HLT_Tls_Res* HLT_ProcessTlsConnect(HLT_Process *process, TLS_VERSION tlsVersion, HLT_Ctx_Config *ctxConfig, HLT_Ssl_Config *sslConfig) { int ret; HLT_Tls_Res *tlsRes = (HLT_Tls_Res*)malloc(sizeof(HLT_Tls_Res)); if (tlsRes == NULL) { LOG_ERROR("Malloc TlsRes ERROR"); return NULL; } (void)memset_s(tlsRes, sizeof(HLT_Tls_Res), 0, sizeof(HLT_Tls_Res)); // Checking Configuration Parameters if (ctxConfig == NULL) { ctxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); } if (sslConfig == NULL) { sslConfig = HLT_NewSslConfig(NULL); } if ((ctxConfig == NULL) || (sslConfig == NULL)) { LOG_ERROR("ctxConfig or sslConfig is NULL"); goto ERR; } // Check whether the call is invoked by the local process or by the RPC. if (process->remoteFlag == 0) { ret = LocalProcessTlsInit(process, tlsVersion, ctxConfig, sslConfig, tlsRes); if (ret == ERROR) { LOG_ERROR("LocalProcessTlsInit ERROR"); goto ERR; } ret = HLT_TlsConnect(tlsRes->ssl); if (ret != SUCCESS) { LOG_ERROR("HLT_TlsConnect ERROR is %d", ret); goto ERR; } } else { ret = RemoteProcessTlsInit(process, tlsVersion, ctxConfig, sslConfig, tlsRes); if (ret == ERROR) { LOG_ERROR("Retmote Process Init Tls ERROR"); goto ERR; } ret = HLT_RpcTlsConnect(process, tlsRes->sslId); if (ret != SUCCESS) { LOG_ERROR("HLT_RpcTlsConnect ERROR is %d", ret); goto ERR; } } // The configuration resources of the HLT_Tls_Res table are stored and will be released later. Process *localProcess = GetProcess(); localProcess->hltTlsResArray[localProcess->hltTlsResNum] = tlsRes; localProcess->hltTlsResNum++; return tlsRes; ERR: free(tlsRes); return NULL; } int HLT_ProcessTlsWrite(HLT_Process *process, HLT_Tls_Res *tlsRes, uint8_t *data, uint32_t dataLen) { if (process == NULL) { LOG_ERROR("Process is NULL"); return ERROR; } if (process->remoteFlag == 0) { return HLT_TlsWrite(tlsRes->ssl, data, dataLen); } else { return HLT_RpcTlsWrite(process, tlsRes->sslId, data, dataLen); } } int HLT_ProcessTlsRead(HLT_Process *process, HLT_Tls_Res *tlsRes, uint8_t *data, uint32_t bufSize, uint32_t *dataLen) { if (process == NULL) { LOG_ERROR("Process is NULL"); return ERROR; } if (process->remoteFlag == 0) { return HLT_TlsRead(tlsRes->ssl, data, bufSize, dataLen); } else { return HLT_RpcTlsRead(process, tlsRes->sslId, data, bufSize, dataLen); } } int HLT_SetVersion(HLT_Ctx_Config *ctxConfig, uint16_t minVersion, uint16_t maxVersion) { ctxConfig->minVersion = minVersion; ctxConfig->maxVersion = maxVersion; return SUCCESS; } int HLT_SetSecurityLevel(HLT_Ctx_Config *ctxConfig, int32_t level) { ctxConfig->securitylevel = level; return SUCCESS; } int HLT_SetRenegotiationSupport(HLT_Ctx_Config *ctxConfig, bool support) { ctxConfig->isSupportRenegotiation = support; return SUCCESS; } int HLT_SetLegacyRenegotiateSupport(HLT_Ctx_Config *ctxConfig, bool support) { ctxConfig->allowLegacyRenegotiate = support; return SUCCESS; } int HLT_SetClientRenegotiateSupport(HLT_Ctx_Config *ctxConfig, bool support) { ctxConfig->allowClientRenegotiate = support; return SUCCESS; } int HLT_SetEmptyRecordsNum(HLT_Ctx_Config *ctxConfig, uint32_t emptyNum) { ctxConfig->emptyRecordsNum = emptyNum; return SUCCESS; } int HLT_SetKeyLogCb(HLT_Ctx_Config *ctxConfig, char *SetKeyLogCb) { (void)memset_s(ctxConfig->keyLogCb, KEY_LOG_CB_LEN, 0, KEY_LOG_CB_LEN); if (strcpy_s(ctxConfig->keyLogCb, KEY_LOG_CB_LEN, SetKeyLogCb) != EOK) { LOG_ERROR("HLT_SetKeyLogCb failed."); return -1; } return SUCCESS; } int HLT_SetEncryptThenMac(HLT_Ctx_Config *ctxConfig, int support) { ctxConfig->isEncryptThenMac = support; return SUCCESS; } int HLT_SetMiddleBoxCompat(HLT_Ctx_Config *ctxConfig, int support) { ctxConfig->isMiddleBoxCompat = support; return SUCCESS; } int HLT_SetFlightTransmitSwitch(HLT_Ctx_Config *ctxConfig, bool support) { ctxConfig->isFlightTransmitEnable = support; return SUCCESS; } int HLT_SetClientVerifySupport(HLT_Ctx_Config *ctxConfig, bool support) { ctxConfig->isSupportClientVerify = support; return SUCCESS; } int HLT_SetPostHandshakeAuth(HLT_Ctx_Config *ctxConfig, bool support) { ctxConfig->isSupportPostHandshakeAuth = support; return SUCCESS; } int HLT_SetNoClientCertSupport(HLT_Ctx_Config *ctxConfig, bool support) { ctxConfig->isSupportNoClientCert = support; return SUCCESS; } int HLT_SetExtenedMasterSecretSupport(HLT_Ctx_Config *ctxConfig, bool support) { ctxConfig->isSupportExtendMasterSecret = support; return SUCCESS; } int HLT_SetModeSupport(HLT_Ctx_Config *ctxConfig, uint32_t mode) { ctxConfig->modeSupport = mode; return SUCCESS; } int HLT_SetCipherSuites(HLT_Ctx_Config *ctxConfig, const char *cipherSuites) { int ret; (void)memset_s(ctxConfig->cipherSuites, sizeof(ctxConfig->cipherSuites), 0, sizeof(ctxConfig->cipherSuites)); ret = sprintf_s(ctxConfig->cipherSuites, sizeof(ctxConfig->cipherSuites), cipherSuites); if (ret <= 0) { return ERROR; } return SUCCESS; } int HLT_SetProviderPath(HLT_Ctx_Config *ctxConfig, char *providerPath) { if (strcpy_s(ctxConfig->providerPath, sizeof(ctxConfig->providerPath), providerPath) != EOK) { return ERROR; } return SUCCESS; } int HLT_SetProviderAttrName(HLT_Ctx_Config *ctxConfig, char *attrName) { if (strcpy_s(ctxConfig->attrName, sizeof(ctxConfig->attrName), attrName) != EOK) { return ERROR; } return SUCCESS; } int HLT_AddProviderInfo(HLT_Ctx_Config *ctxConfig, char *providerName, int providerLibFmt) { if (providerName != NULL) { if (strcpy_s(ctxConfig->providerNames[ctxConfig->providerCnt], MAX_PROVIDER_NAME_LEN, providerName) != EOK) { return ERROR; } ctxConfig->providerLibFmts[ctxConfig->providerCnt] = providerLibFmt; ctxConfig->providerCnt += 1; } return SUCCESS; } int HLT_SetTls13CipherSuites(HLT_Ctx_Config *ctxConfig, const char *cipherSuites) { int ret; (void)memset_s(ctxConfig->tls13CipherSuites, sizeof(ctxConfig->tls13CipherSuites), 0, sizeof(ctxConfig->tls13CipherSuites)); ret = sprintf_s(ctxConfig->tls13CipherSuites, sizeof(ctxConfig->tls13CipherSuites), cipherSuites); if (ret <= 0) { return ERROR; } return SUCCESS; } int HLT_SetEcPointFormats(HLT_Ctx_Config *ctxConfig, const char *pointFormat) { int ret; (void)memset_s(ctxConfig->pointFormats, sizeof(ctxConfig->pointFormats), 0, sizeof(ctxConfig->pointFormats)); ret = sprintf_s(ctxConfig->pointFormats, sizeof(ctxConfig->pointFormats), pointFormat); if (ret <= 0) { return ERROR; } return SUCCESS; } int HLT_SetGroups(HLT_Ctx_Config *ctxConfig, const char *groups) { int ret; (void)memset_s(ctxConfig->groups, sizeof(ctxConfig->groups), 0, sizeof(ctxConfig->groups)); ret = sprintf_s(ctxConfig->groups, sizeof(ctxConfig->groups), groups); if (ret <= 0) { return ERROR; } return SUCCESS; } int HLT_SetSignature(HLT_Ctx_Config *ctxConfig, const char *signature) { int ret; (void)memset_s(ctxConfig->signAlgorithms, sizeof(ctxConfig->signAlgorithms), 0, sizeof(ctxConfig->signAlgorithms)); ret = sprintf_s(ctxConfig->signAlgorithms, sizeof(ctxConfig->signAlgorithms), signature); if (ret <= 0) { return ERROR; } return SUCCESS; } int HLT_SetPsk(HLT_Ctx_Config *ctxConfig, char *psk) { (void)memset_s(ctxConfig->psk, PSK_MAX_LEN, 0, PSK_MAX_LEN); if (strcpy_s(ctxConfig->psk, PSK_MAX_LEN, psk) != EOK) { LOG_ERROR("HLT_SetPsk failed."); return -1; } return SUCCESS; } int HLT_SetKeyExchMode(HLT_Ctx_Config *config, uint32_t mode) { config->keyExchMode = mode; return SUCCESS; } int HLT_SetTicketKeyCb(HLT_Ctx_Config *ctxConfig, char *ticketKeyCbName) { (void)memset_s(ctxConfig->ticketKeyCb, TICKET_KEY_CB_NAME_LEN, 0, TICKET_KEY_CB_NAME_LEN); if (strcpy_s(ctxConfig->ticketKeyCb, TICKET_KEY_CB_NAME_LEN, ticketKeyCbName) != EOK) { LOG_ERROR("HLT_SetTicketKeyCb failed."); return -1; } return SUCCESS; } int HLT_SetCaCertPath(HLT_Ctx_Config *ctxConfig, const char *caCertPath) { int ret; (void)memset_s(ctxConfig->caCert, sizeof(ctxConfig->caCert), 0, sizeof(ctxConfig->caCert)); ret = sprintf_s(ctxConfig->caCert, sizeof(ctxConfig->caCert), caCertPath); if (ret <= 0) { return ERROR; } return SUCCESS; } int HLT_SetChainCertPath(HLT_Ctx_Config *ctxConfig, const char *chainCertPath) { int ret; (void)memset_s(ctxConfig->chainCert, sizeof(ctxConfig->chainCert), 0, sizeof(ctxConfig->chainCert)); ret = sprintf_s(ctxConfig->chainCert, sizeof(ctxConfig->chainCert), chainCertPath); if (ret <= 0) { return ERROR; } return SUCCESS; } int HLT_SetEeCertPath(HLT_Ctx_Config *ctxConfig, const char *eeCertPath) { int ret; (void)memset_s(ctxConfig->eeCert, sizeof(ctxConfig->eeCert), 0, sizeof(ctxConfig->eeCert)); ret = sprintf_s(ctxConfig->eeCert, sizeof(ctxConfig->eeCert), eeCertPath); if (ret <= 0) { return ERROR; } return SUCCESS; } int HLT_SetPrivKeyPath(HLT_Ctx_Config *ctxConfig, const char *privKeyPath) { int ret; (void)memset_s(ctxConfig->privKey, sizeof(ctxConfig->privKey), 0, sizeof(ctxConfig->privKey)); ret = sprintf_s(ctxConfig->privKey, sizeof(ctxConfig->privKey), privKeyPath); if (ret <= 0) { return ERROR; } return SUCCESS; } int HLT_SetSignCertPath(HLT_Ctx_Config *ctxConfig, const char *signCertPath) { int ret; (void)memset_s(ctxConfig->signCert, sizeof(ctxConfig->signCert), 0, sizeof(ctxConfig->signCert)); ret = sprintf_s(ctxConfig->signCert, sizeof(ctxConfig->signCert), signCertPath); if (ret <= 0) { return ERROR; } return SUCCESS; } int HLT_SetSignPrivKeyPath(HLT_Ctx_Config *ctxConfig, const char *signPrivKeyPath) { int ret; (void)memset_s(ctxConfig->signPrivKey, sizeof(ctxConfig->signPrivKey), 0, sizeof(ctxConfig->signPrivKey)); ret = sprintf_s(ctxConfig->signPrivKey, sizeof(ctxConfig->signPrivKey), signPrivKeyPath); if (ret <= 0) { return ERROR; } return SUCCESS; } int HLT_SetPassword(HLT_Ctx_Config* ctxConfig, const char* password) { int ret; (void)memset_s(ctxConfig->password, sizeof(ctxConfig->password), 0, sizeof(ctxConfig->password)); ret = sprintf_s(ctxConfig->password, sizeof(ctxConfig->password), password); if (ret <= 0) { return ERROR; } return SUCCESS; } void HLT_SetCertPath(HLT_Ctx_Config *ctxConfig, const char *caPath, const char *chainPath, const char *EePath, const char *PrivPath, const char *signCert, const char *signPrivKey) { HLT_SetCaCertPath(ctxConfig, caPath); if (ctxConfig->isNoSetCert) { return; } HLT_SetChainCertPath(ctxConfig, chainPath); HLT_SetEeCertPath(ctxConfig, EePath); HLT_SetPrivKeyPath(ctxConfig, PrivPath); HLT_SetSignCertPath(ctxConfig, signCert); HLT_SetSignPrivKeyPath(ctxConfig, signPrivKey); } int HLT_SetServerName(HLT_Ctx_Config *ctxConfig, const char *serverName) { (void)memset_s(ctxConfig->serverName, sizeof(ctxConfig->serverName), 0, sizeof(ctxConfig->serverName)); int ret = sprintf_s(ctxConfig->serverName, sizeof(ctxConfig->serverName), serverName); if (ret <= 0) { return ERROR; } return SUCCESS; } int HLT_SetServerNameArg(HLT_Ctx_Config *ctxConfig, char *arg) { (void)memset_s(ctxConfig->sniArg, SERVER_NAME_ARG_NAME_LEN, 0, SERVER_NAME_ARG_NAME_LEN); if (strcpy_s(ctxConfig->sniArg, SERVER_NAME_ARG_NAME_LEN, arg) != EOK) { LOG_ERROR("HLT_SetServerNameArg failed."); return ERROR; } return SUCCESS; } int HLT_SetServerNameCb(HLT_Ctx_Config *ctxConfig, char *sniCbName) { (void)memset_s(ctxConfig->sniDealCb, SERVER_NAME_CB_NAME_LEN, 0, SERVER_NAME_CB_NAME_LEN); if (strcpy_s(ctxConfig->sniDealCb, SERVER_NAME_CB_NAME_LEN, sniCbName) != EOK) { LOG_ERROR("HLT_SetServerNameCb failed."); return ERROR; } return SUCCESS; } int HLT_SetAlpnProtos(HLT_Ctx_Config *ctxConfig, const char *alpnProtos) { (void)memset_s(ctxConfig->alpnList, sizeof(ctxConfig->alpnList), 0, sizeof(ctxConfig->alpnList)); int ret = sprintf_s(ctxConfig->alpnList, sizeof(ctxConfig->alpnList), alpnProtos); if (ret <= 0) { return ERROR; } return SUCCESS; } int HLT_SetAlpnProtosSelectCb(HLT_Ctx_Config *ctxConfig, char *callback, char *userData) { (void)memset_s(ctxConfig->alpnSelectCb, ALPN_CB_NAME_LEN, 0, ALPN_CB_NAME_LEN); if (strcpy_s(ctxConfig->alpnSelectCb, ALPN_CB_NAME_LEN, callback) != EOK) { LOG_ERROR("HLT_SetAlpnCb failed."); return ERROR; } (void)memset_s(ctxConfig->alpnUserData, ALPN_DATA_NAME_LEN, 0, ALPN_DATA_NAME_LEN); if (strcpy_s(ctxConfig->alpnUserData, ALPN_DATA_NAME_LEN, userData) != EOK) { LOG_ERROR("HLT_SetAlpnDataCb failed."); return ERROR; } return SUCCESS; } int HLT_SetClientHelloCb(HLT_Ctx_Config *ctxConfig, HITLS_ClientHelloCb callback, void *arg) { ctxConfig->clientHelloCb = callback; ctxConfig->clientHelloArg = arg; return SUCCESS; } int HLT_SetCertCb(HLT_Ctx_Config *ctxConfig, HITLS_CertCb certCb, void *arg) { ctxConfig->certCb = certCb; ctxConfig->certArg = arg; return SUCCESS; } int HLT_SetCAList(HLT_Ctx_Config *ctxConfig, HITLS_TrustedCAList *caList) { ctxConfig->caList = caList; return SUCCESS; } int HLT_SetFrameHandle(HLT_FrameHandle *frameHandle) { return SetFrameHandle(frameHandle); } void HLT_CleanFrameHandle(void) { CleanFrameHandle(); } bool IsEnableSctpAuth(void) { return false; } void HLT_ConfigTimeOut(const char* timeout) { setenv("SSL_TIMEOUT", timeout, 1); } void HLT_UnsetTimeOut() { unsetenv("SSL_TIMEOUT"); }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/rpc/src/hlt_func.c
C
unknown
41,089
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include "logger.h" #include "process.h" #include "hlt_type.h" #include "control_channel.h" #include "channel_res.h" #include "handle_cmd.h" #include "securec.h" #define SUCCESS 0 #define ERROR (-1) uint64_t g_cmdIndex = 0; pthread_mutex_t g_cmdMutex = PTHREAD_MUTEX_INITIALIZER; #define ASSERT_RETURN(condition, log) \ do { \ if (!(condition)) { \ LOG_ERROR(log); \ return ERROR; \ } \ } while (0) void InitCmdIndex(void) { g_cmdIndex = 0; } static int WaitResult(CmdData *expectCmdData, int cmdIndex, const char *funcName) { int ret; ret = sprintf_s(expectCmdData->id, sizeof(expectCmdData->id), "%d", cmdIndex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = sprintf_s(expectCmdData->funcId, sizeof(expectCmdData->funcId), "%s", funcName); ASSERT_RETURN(ret > 0, "sprintf_s Error"); // Receive the result. ret = WaitResultFromPeer(expectCmdData); ASSERT_RETURN(ret == SUCCESS, "WaitResultFromPeer Error"); return SUCCESS; } int HLT_RpcProviderTlsNewCtx(HLT_Process *peerProcess, TLS_VERSION tlsVersion, bool isClient, char *providerPath, char (*providerNames)[MAX_PROVIDER_NAME_LEN], int32_t *providerLibFmts, int32_t providerCnt, char *attrName) { int ret; uint64_t cmdIndex; Process *srcProcess = NULL; CmdData expectCmdData = {0}; ControlChannelBuf dataBuf; uint32_t offset = 0; ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsNewCtx"); srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d|%d|", g_cmdIndex, __FUNCTION__, tlsVersion, isClient); ASSERT_RETURN(ret > 0, "sprintf_s Error"); offset += ret; if (providerCnt == 0 || providerNames == NULL || providerLibFmts == NULL) { ret = sprintf_s(dataBuf.data + offset, sizeof(dataBuf.data) - offset, "|"); ASSERT_RETURN(ret > 0, "sprintf_s Error"); offset += ret; } for (int i = 0; i < providerCnt - 1; i++) { ret = sprintf_s(dataBuf.data + offset, sizeof(dataBuf.data) - offset, "%s,%d:", providerNames[i], providerLibFmts[i]); ASSERT_RETURN(ret > 0, "sprintf_s Error"); offset += ret; } if (providerCnt >= 1) { ret = sprintf_s(dataBuf.data + offset, sizeof(dataBuf.data) - offset, "%s,%d|", providerNames[providerCnt - 1], providerLibFmts[providerCnt - 1]); ASSERT_RETURN(ret > 0, "sprintf_s Error"); offset += ret; } if (attrName != NULL && strlen(attrName) > 0) { ret = sprintf_s(dataBuf.data + offset, sizeof(dataBuf.data) - offset, "%s|", attrName); } else { ret = sprintf_s(dataBuf.data + offset, sizeof(dataBuf.data) - offset, "|"); } ASSERT_RETURN(ret > 0, "sprintf_s Error"); offset += ret; if (providerPath != NULL && strlen(providerPath) > 0) { ret = sprintf_s(dataBuf.data + offset, sizeof(dataBuf.data) - offset, "%s|", providerPath); } else { ret = sprintf_s(dataBuf.data + offset, sizeof(dataBuf.data) - offset, "|"); } ASSERT_RETURN(ret > 0, "sprintf_s Error"); offset += ret; dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return atoi(expectCmdData.paras[0]); } int HLT_RpcTlsNewCtx(HLT_Process *peerProcess, TLS_VERSION tlsVersion, bool isClient) { int ret; uint64_t cmdIndex; Process *srcProcess = NULL; CmdData expectCmdData = {0}; ControlChannelBuf dataBuf; ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsNewCtx"); srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d|%d", g_cmdIndex, __FUNCTION__, tlsVersion, isClient); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return atoi(expectCmdData.paras[0]); } int HLT_RpcTlsSetCtx(HLT_Process *peerProcess, int ctxId, HLT_Ctx_Config *config) { int ret; uint64_t cmdIndex; Process *srcProcess = NULL; CmdData expectCmdData = {0}; ControlChannelBuf dataBuf; ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsSetCtx"); srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d|" "%u|%u|%s|%s|" "%s|%s|%s|%d|" "%d|%d|%d|%s|" "%s|%s|%s|%s|" "%s|%s|%s|%d|" "%d|%s|%d|%s|" "%s|%s|%s|%s|" "%s|%d|%d|" "%u|%d|%d|" "%d|%d|%d|" "%d|%u|%d|%d|" "%u|%d|%s", g_cmdIndex, __FUNCTION__, ctxId, config->minVersion, config->maxVersion, config->cipherSuites, config->tls13CipherSuites, config->pointFormats, config->groups, config->signAlgorithms, config->isSupportRenegotiation, config->isSupportClientVerify, config->isSupportNoClientCert, config->isSupportExtendMasterSecret, config->eeCert, config->privKey, config->password, config->caCert, config->chainCert, config->signCert, config->signPrivKey, config->psk, config->isSupportSessionTicket, config->setSessionCache, config->ticketKeyCb, config->isFlightTransmitEnable, config->serverName, config->sniDealCb, config->sniArg, config->alpnList, config->alpnSelectCb, config->alpnUserData, config->securitylevel, config->isSupportDhAuto, config->keyExchMode, config->SupportType, config->isSupportPostHandshakeAuth, config->readAhead, config->needCheckKeyUsage, config->isSupportVerifyNone, config->allowClientRenegotiate, config->emptyRecordsNum, config->allowLegacyRenegotiate, config->isEncryptThenMac, config->modeSupport, config->isMiddleBoxCompat, config->attrName); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Wait to receive the result. ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return atoi(expectCmdData.paras[0]); } int HLT_RpcTlsNewSsl(HLT_Process *peerProcess, int ctxId) { int ret; uint64_t cmdIndex; CmdData expectCmdData = {0}; Process *srcProcess = NULL; ControlChannelBuf dataBuf; ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsNewSsl"); // Constructing Commands srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d", g_cmdIndex, __FUNCTION__, ctxId); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Wait to receive the result. ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return atoi(expectCmdData.paras[0]); } int HLT_RpcTlsSetSsl(HLT_Process *peerProcess, int sslId, HLT_Ssl_Config *config) { int ret; uint64_t cmdIndex; Process *srcProcess = NULL; CmdData expectCmdData = {0}; ControlChannelBuf dataBuf; ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsSetSsl"); srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d|%d|%d|%d", g_cmdIndex, __FUNCTION__, sslId, config->sockFd, config->connType, config->connPort); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Wait to receive the result. ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return atoi(expectCmdData.paras[0]); } int HLT_RpcTlsListen(HLT_Process *peerProcess, int sslId) { int ret; uint64_t acceptId; Process *srcProcess = NULL; ControlChannelBuf dataBuf; srcProcess = GetProcess(); ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsListen"); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d", g_cmdIndex, __FUNCTION__, sslId); dataBuf.dataLen = strlen(dataBuf.data); acceptId = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); return acceptId; } int HLT_RpcTlsAccept(HLT_Process *peerProcess, int sslId) { int ret; uint64_t acceptId; Process *srcProcess = NULL; ControlChannelBuf dataBuf; srcProcess = GetProcess(); ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsAccept"); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d", g_cmdIndex, __FUNCTION__, sslId); dataBuf.dataLen = strlen(dataBuf.data); acceptId = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); return acceptId; } int HLT_RpcGetTlsListenResult(int acceptId) { int ret; CmdData expectCmdData = {0}; ret = WaitResult(&expectCmdData, acceptId, "HLT_RpcTlsListen"); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return (int)strtol(expectCmdData.paras[0], NULL, 10); // Convert to a decimal number } int HLT_RpcGetTlsAcceptResult(int acceptId) { int ret; char *endPtr = NULL; CmdData expectCmdData = {0}; ret = WaitResult(&expectCmdData, acceptId, "HLT_RpcTlsAccept"); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return (int)strtol(expectCmdData.paras[0], &endPtr, 0); } int HLT_RpcTlsConnect(HLT_Process *peerProcess, int sslId) { int ret; uint64_t cmdIndex; Process *srcProcess = NULL; CmdData expectCmdData = {0}; ControlChannelBuf dataBuf; ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsConnect"); srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d", g_cmdIndex, __FUNCTION__, sslId); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Waiting for the result returned by the peer ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return atoi(expectCmdData.paras[0]); } int HLT_RpcTlsConnectUnBlock(HLT_Process *peerProcess, int sslId) { uint64_t cmdIndex; Process *srcProcess = NULL; ControlChannelBuf dataBuf; ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsConnect"); srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); int ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d", g_cmdIndex, "HLT_RpcTlsConnect", sslId); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); return cmdIndex; } int HLT_RpcGetTlsConnectResult(int cmdIndex) { int ret; CmdData expectCmdData = {0}; // Waiting for the result returned by the peer ret = WaitResult(&expectCmdData, cmdIndex, "HLT_RpcTlsConnect"); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return atoi(expectCmdData.paras[0]); } int HLT_RpcTlsRead(HLT_Process *peerProcess, int sslId, uint8_t *data, uint32_t bufSize, uint32_t *readLen) { int ret; uint64_t cmdIndex; Process *srcProcess = NULL; CmdData expectCmdData = {0}; ControlChannelBuf dataBuf; ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsRead"); srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d|%u", g_cmdIndex, __FUNCTION__, sslId, bufSize); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Waiting for the result returned by the peer ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); // Parsing result ret = atoi(expectCmdData.paras[0]); if (ret == SUCCESS) { *readLen = atoi(expectCmdData.paras[1]); // The first parameter indicates the read length. memcpy_s( data, bufSize, expectCmdData.paras[2], *readLen); // The second parameter indicates the content to be read. } return ret; } int HLT_RpcTlsReadUnBlock(HLT_Process *peerProcess, int sslId, uint8_t *data, uint32_t bufSize, uint32_t *readLen) { (void)data; (void)readLen; int ret; uint64_t cmdIndex; Process *srcProcess = NULL; ControlChannelBuf dataBuf; ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsRead"); srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d|%u", g_cmdIndex, "HLT_RpcTlsRead", sslId, bufSize); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); return cmdIndex; } int HLT_RpcGetTlsReadResult(int cmdIndex, uint8_t *data, uint32_t bufSize, uint32_t *readLen) { int ret; char *endPtr = NULL; CmdData expectCmdData = {0}; ret = WaitResult(&expectCmdData, cmdIndex, "HLT_RpcTlsRead"); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); // Parsing result ret = (int)strtol(expectCmdData.paras[0], &endPtr, 0); if (ret == SUCCESS) { *readLen = (int)strtol(expectCmdData.paras[1], &endPtr, 0); // The first parameter indicates the read length. // The second parameter indicates the content to be read. memcpy_s(data, bufSize, expectCmdData.paras[2], *readLen); } return ret; } int HLT_RpcTlsWrite(HLT_Process *peerProcess, int sslId, uint8_t *data, uint32_t bufSize) { int ret; uint64_t cmdIndex; Process *srcProcess = NULL; CmdData expectCmdData = {0}; ControlChannelBuf dataBuf; ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsWrite"); srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d|%u|%s", g_cmdIndex, __FUNCTION__, sslId, bufSize, data); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Waiting for the result returned by the peer ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return atoi(expectCmdData.paras[0]); } int HLT_RpcTlsWriteUnBlock(HLT_Process *peerProcess, int sslId, uint8_t *data, uint32_t bufSize) { int ret; uint64_t cmdIndex; Process *srcProcess = NULL; ControlChannelBuf dataBuf; ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsWrite"); srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d|%u|%s", g_cmdIndex, "HLT_RpcTlsWrite", sslId, bufSize, data); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Do not wait for the result returned by the peer. return cmdIndex; } int HLT_RpcGetTlsWriteResult(int cmdIndex) { int ret; CmdData expectCmdData = {0}; ret = WaitResult(&expectCmdData, cmdIndex, "HLT_RpcTlsWrite"); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return (int)strtol(expectCmdData.paras[0], NULL, 10); // Convert to a decimal number } int HLT_RpcTlsRenegotiate(HLT_Process *peerProcess, int sslId) { int ret; uint64_t cmdIndex; char *endPtr = NULL; Process *srcProcess = NULL; ControlChannelBuf dataBuf; CmdData expectCmdData = {0}; srcProcess = GetProcess(); ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsRenegotiate"); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d", g_cmdIndex, __FUNCTION__, sslId); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Waiting for the result ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return (int)strtol(expectCmdData.paras[0], &endPtr, 0); } int HLT_RpcTlsVerifyClientPostHandshake(HLT_Process *peerProcess, int sslId) { int ret; uint64_t cmdIndex; char *endPtr = NULL; Process *srcProcess = NULL; ControlChannelBuf dataBuf; CmdData expectCmdData = {0}; srcProcess = GetProcess(); ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call RpcTlsVerifyClientPostHandshake"); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d", g_cmdIndex, __FUNCTION__, sslId); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Waiting for the result ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return (int)strtol(expectCmdData.paras[0], &endPtr, 0); } int HLT_RpcDataChannelConnect(HLT_Process *peerProcess, DataChannelParam *channelParam) { int ret; uint64_t cmdIndex; Process *srcProcess = NULL; CmdData expectCmdData = {0}; ControlChannelBuf dataBuf; ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcDataChannelConnect"); srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d|%d|%d", g_cmdIndex, __FUNCTION__, channelParam->type, channelParam->port, channelParam->isBlock); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Waiting for the result returned by the peer ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return atoi(expectCmdData.paras[0]); } int HLT_RpcDataChannelBind(HLT_Process *peerProcess, DataChannelParam *channelParam) { int ret; uint64_t bindId; Process *srcProcess = NULL; CmdData expectCmdData = {0}; ControlChannelBuf dataBuf; ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcDataChannelBind"); srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d|%d|%d|%d", g_cmdIndex, __FUNCTION__, channelParam->type, channelParam->port, channelParam->isBlock, channelParam->bindFd); dataBuf.dataLen = strlen(dataBuf.data); bindId = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Waiting for the result returned by the peer ret = WaitResult(&expectCmdData, bindId, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); channelParam->port = atoi(expectCmdData.paras[1]); return atoi(expectCmdData.paras[0]); } int HLT_RpcDataChannelAccept(HLT_Process *peerProcess, DataChannelParam *channelParam) { int ret; uint64_t acceptId; Process *srcProcess = NULL; ControlChannelBuf dataBuf; ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcDataChannelAccept"); srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d|%d|%d|%d", g_cmdIndex, __FUNCTION__, channelParam->type, channelParam->port, channelParam->isBlock, channelParam->bindFd); dataBuf.dataLen = strlen(dataBuf.data); acceptId = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); return acceptId; } int HLT_RpcGetAcceptFd(int acceptId) { int ret; CmdData expectCmdData = {0}; ret = WaitResult(&expectCmdData, acceptId, "HLT_RpcDataChannelAccept"); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return atoi(expectCmdData.paras[0]); } int HLT_RpcTlsRegCallback(HLT_Process *peerProcess, TlsCallbackType type) { int ret; uint64_t cmdIndex; Process *srcProcess; CmdData expectCmdData = {0}; ControlChannelBuf dataBuf; ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsRegCallback"); srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d", g_cmdIndex, __FUNCTION__, type); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Waiting for the result ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return atoi(expectCmdData.paras[0]); } int HLT_RpcProcessExit(HLT_Process *peerProcess) { int ret; uint64_t cmdIndex; Process *srcProcess; CmdData expectCmdData = {0}; ControlChannelBuf dataBuf; srcProcess = GetProcess(); ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcProcessExit"); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d", g_cmdIndex, __FUNCTION__, peerProcess->connFd); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Waiting for the result ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return SUCCESS; } int HLT_RpcTlsGetStatus(HLT_Process *peerProcess, int sslId) { ASSERT_RETURN(peerProcess != NULL, "HLT_RpcTlsGetStatus Parameter Error"); ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsGetStatus"); int ret; uint64_t cmdIndex; char *endPtr = NULL; Process *srcProcess; CmdData expectCmdData = {0}; ControlChannelBuf dataBuf; srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d", g_cmdIndex, __FUNCTION__, sslId); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Waiting for the result ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return (int)strtol(expectCmdData.paras[0], &endPtr, 0); } int HLT_RpcTlsGetAlertFlag(HLT_Process *peerProcess, int sslId) { ASSERT_RETURN(peerProcess != NULL, "HLT_RpcTlsGetAlertFlag Parameter Error"); ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcProcessExit"); int ret; uint64_t cmdIndex; char *endPtr = NULL; Process *srcProcess; CmdData expectCmdData = {0}; ControlChannelBuf dataBuf; srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d", g_cmdIndex, __FUNCTION__, sslId); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Waiting for the result ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return (int)strtol(expectCmdData.paras[0], &endPtr, 0); } int HLT_RpcTlsGetAlertLevel(HLT_Process *peerProcess, int sslId) { ASSERT_RETURN(peerProcess != NULL, "HLT_RpcTlsGetAlertLevel Parameter Error"); ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsGetAlertLevel"); int ret; uint64_t cmdIndex; char *endPtr = NULL; Process *srcProcess; CmdData expectCmdData = {0}; ControlChannelBuf dataBuf; srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d", g_cmdIndex, __FUNCTION__, sslId); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Waiting for the result ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return (int)strtol(expectCmdData.paras[0], &endPtr, 0); } int HLT_RpcTlsGetAlertDescription(HLT_Process *peerProcess, int sslId) { ASSERT_RETURN(peerProcess != NULL, "HLT_RpcTlsGetAlertDescription Parameter Error"); ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsGetAlertDescription"); int ret; uint64_t cmdIndex; char *endPtr = NULL; Process *srcProcess; CmdData expectCmdData = {0}; ControlChannelBuf dataBuf; srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d", g_cmdIndex, __FUNCTION__, sslId); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Waiting for the result ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return (int)strtol(expectCmdData.paras[0], &endPtr, 0); } int HLT_RpcTlsClose(HLT_Process *peerProcess, int sslId) { int ret; uint64_t cmdIndex; char *endPtr = NULL; Process *srcProcess = NULL; ControlChannelBuf dataBuf; CmdData expectCmdData = {0}; srcProcess = GetProcess(); ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsClose"); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d", g_cmdIndex, __FUNCTION__, sslId); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Waiting for the result ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return (int)strtol(expectCmdData.paras[0], &endPtr, 0); } int HLT_RpcFreeResFormSsl(HLT_Process *peerProcess, int sslId) { int ret; uint64_t cmdIndex; char *endPtr = NULL; Process *srcProcess = NULL; ControlChannelBuf dataBuf; CmdData expectCmdData = {0}; srcProcess = GetProcess(); ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcFreeResFormSsl"); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d", g_cmdIndex, __FUNCTION__, sslId); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Waiting for the result ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return (int)strtol(expectCmdData.paras[0], &endPtr, 0); } int HLT_RpcSctpClose(HLT_Process *peerProcess, int fd) { int ret; uint64_t cmdIndex; char *endPtr = NULL; Process *srcProcess = NULL; ControlChannelBuf dataBuf; CmdData expectCmdData = {0}; srcProcess = GetProcess(); ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcSctpClose"); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d", g_cmdIndex, __FUNCTION__, fd); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Waiting for the result ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return (int)strtol((const char *)expectCmdData.paras[0], &endPtr, 0); } int HLT_RpcCloseFd(HLT_Process *peerProcess, int fd, int linkType) { int ret; uint64_t cmdIndex; Process *srcProcess = NULL; ControlChannelBuf dataBuf; srcProcess = GetProcess(); ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcCloseFd"); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d|%d", g_cmdIndex, __FUNCTION__, fd, linkType); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // The close fd does not need to wait for the result. return ret; } int HLT_RpcTlsSetMtu(HLT_Process *peerProcess, int sslId, uint16_t mtu) { int ret; uint64_t cmdIndex; char *endPtr = NULL; Process *srcProcess = NULL; ControlChannelBuf dataBuf; CmdData expectCmdData = {0}; srcProcess = GetProcess(); ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsSetMtu"); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d|%d", g_cmdIndex, __FUNCTION__, sslId, mtu); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Waiting for the result ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return (int)strtol(expectCmdData.paras[0], &endPtr, 0); } int HLT_RpcTlsGetErrorCode(HLT_Process *peerProcess, int sslId) { ASSERT_RETURN(peerProcess != NULL, "HLT_RpcTlsGetStatus Parameter Error"); ASSERT_RETURN(peerProcess->remoteFlag == 1, "Only Remote Process Support Call HLT_RpcTlsGetErrorCode"); int ret; uint64_t cmdIndex; char *endPtr = NULL; Process *srcProcess; CmdData expectCmdData = {0}; ControlChannelBuf dataBuf; srcProcess = GetProcess(); pthread_mutex_lock(&g_cmdMutex); ret = sprintf_s(dataBuf.data, sizeof(dataBuf.data), "%llu|%s|%d", g_cmdIndex, __FUNCTION__, sslId); dataBuf.dataLen = strlen(dataBuf.data); cmdIndex = g_cmdIndex; g_cmdIndex++; pthread_mutex_unlock(&g_cmdMutex); ASSERT_RETURN(ret > 0, "sprintf_s Error"); ret = ControlChannelWrite(srcProcess->controlChannelFd, peerProcess->srcDomainPath, &dataBuf); ASSERT_RETURN(ret == SUCCESS, "ControlChannelWrite Error"); // Waiting for the result ret = WaitResult(&expectCmdData, cmdIndex, __FUNCTION__); ASSERT_RETURN(ret == SUCCESS, "WaitResult Error"); return (int)strtol(expectCmdData.paras[0], &endPtr, 0); }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/rpc/src/hlt_rpc_func.c
C
unknown
38,001
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include "securec.h" #include "hlt.h" #include "handle_cmd.h" #include "tls_res.h" #include "logger.h" #include "lock.h" #include "hitls_error.h" #include "hitls_type.h" #include "tls.h" #include "alert.h" #include "hitls.h" #include "common_func.h" #include "sctp_channel.h" #include "rpc_func.h" #define HITLS_READBUF_MAXLEN (20 * 1024) /* 20K */ #define SUCCESS 0 #define ERROR (-1) #define ASSERT_RETURN(condition) \ do { \ if (!(condition)) { \ LOG_ERROR("sprintf_s Error"); \ return ERROR; \ } \ } while (0) RpcFunList g_rpcFuncList[] = { #ifdef HITLS_TLS_FEATURE_PROVIDER {"HLT_RpcProviderTlsNewCtx", RpcProviderTlsNewCtx}, #else {"HLT_RpcTlsNewCtx", RpcTlsNewCtx}, #endif {"HLT_RpcTlsSetCtx", RpcTlsSetCtx}, {"HLT_RpcTlsNewSsl", RpcTlsNewSsl}, {"HLT_RpcTlsSetSsl", RpcTlsSetSsl}, {"HLT_RpcTlsListen", RpcTlsListen}, {"HLT_RpcTlsAccept", RpcTlsAccept}, {"HLT_RpcTlsConnect", RpcTlsConnect}, {"HLT_RpcTlsRead", RpcTlsRead}, {"HLT_RpcTlsWrite", RpcTlsWrite}, {"HLT_RpcTlsRenegotiate", RpcTlsRenegotiate}, {"HLT_RpcDataChannelAccept", RpcDataChannelAccept}, {"HLT_RpcDataChannelConnect", RpcDataChannelConnect}, {"HLT_RpcProcessExit", RpcProcessExit}, {"HLT_RpcTlsRegCallback", RpcTlsRegCallback}, {"HLT_RpcTlsGetStatus", RpcTlsGetStatus}, {"HLT_RpcTlsGetAlertFlag", RpcTlsGetAlertFlag}, {"HLT_RpcTlsGetAlertLevel", RpcTlsGetAlertLevel}, {"HLT_RpcTlsGetAlertDescription", RpcTlsGetAlertDescription}, {"HLT_RpcTlsClose", RpcTlsClose}, {"HLT_RpcFreeResFormSsl", RpcFreeResFormSsl}, {"HLT_RpcCloseFd", RpcCloseFd}, {"HLT_RpcTlsSetMtu", RpcTlsSetMtu}, {"HLT_RpcTlsGetErrorCode", RpcTlsGetErrorCode}, {"HLT_RpcDataChannelBind", RpcDataChannelBind}, {"HLT_RpcTlsVerifyClientPostHandshake", RpcTlsVerifyClientPostHandshake}, }; RpcFunList *GetRpcFuncList(void) { return g_rpcFuncList; } int GetRpcFuncNum(void) { return sizeof(g_rpcFuncList) / sizeof(g_rpcFuncList[0]); } #ifdef HITLS_TLS_FEATURE_PROVIDER /** * Parse the provider string in format "name1,fmt1:name2,fmt2:...:nameN,fmtN" */ static int ParseProviderString(const char *providerStr, char (*providerNames)[MAX_PROVIDER_NAME_LEN], int32_t *providerLibFmts, int32_t *providerCnt) { if (providerStr == NULL) { LOG_DEBUG("Provider names is NULL"); return SUCCESS; } if (providerStr == NULL || providerLibFmts == NULL || providerCnt == NULL) { LOG_ERROR("Invalid input parameters"); return ERROR; } int count = 1; const char *ptr = providerStr; while (*ptr) { if (*ptr == ':') { count++; } ptr++; } *providerCnt = count; if (count == 0) { LOG_ERROR("Provider string is empty"); return SUCCESS; } char *tempStr = strdup(providerStr); if (tempStr == NULL) { LOG_ERROR("Failed to duplicate provider string"); return ERROR; } char *saveptr1 = NULL; char *saveptr2 = NULL; char *token = strtok_r(tempStr, ":", &saveptr1); int i = 0; while (token != NULL && i < count) { char *name = strtok_r(token, ",", &saveptr2); char *fmt = strtok_r(NULL, ",", &saveptr2); if (name == NULL || fmt == NULL) { LOG_ERROR("Invalid provider format"); free(tempStr); return ERROR; } if (strcpy_s(providerNames[i], MAX_PROVIDER_NAME_LEN, name) != EOK) { LOG_ERROR("Failed to allocate memory for provider name"); free(tempStr); return ERROR; } providerLibFmts[i] = atoi(fmt); token = strtok_r(NULL, ":", &saveptr1); i++; } free(tempStr); return SUCCESS; } int RpcProviderTlsNewCtx(CmdData *cmdData) { int id; TLS_VERSION tlsVersion; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); tlsVersion = atoi(cmdData->paras[0]); char *providerNames = strlen(cmdData->paras[2]) > 0 ? cmdData->paras[2] : NULL; char *attrName = strlen(cmdData->paras[3]) > 0 ? cmdData->paras[3] : NULL; char *providerPath = strlen(cmdData->paras[4]) > 0 ? cmdData->paras[4] : NULL; char parsedProviderNames[MAX_PROVIDER_COUNT][MAX_PROVIDER_NAME_LEN] = {0}; int32_t providerLibFmts[MAX_PROVIDER_COUNT] = {0}; int32_t providerCnt = 0; if (ParseProviderString(providerNames, parsedProviderNames, providerLibFmts, &providerCnt) != SUCCESS) { LOG_ERROR("Failed to parse provider string"); id = ERROR; goto EXIT; } // Invoke the corresponding function. void *ctx = HLT_TlsProviderNewCtx(providerPath, parsedProviderNames, providerLibFmts, providerCnt, attrName, tlsVersion); if (ctx == NULL) { LOG_ERROR("HLT_TlsProviderNewCtx Return NULL"); id = ERROR; goto EXIT; } // Insert to CTX linked list id = InsertCtxToList(ctx); EXIT: // Return Result if (sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, id) <= 0) { return ERROR; } return SUCCESS; } #endif int RpcTlsNewCtx(CmdData *cmdData) { int id; TLS_VERSION tlsVersion; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); tlsVersion = atoi(cmdData->paras[0]); // Invoke the corresponding function. void* ctx = HLT_TlsNewCtx(tlsVersion); if (ctx == NULL) { LOG_ERROR("HLT_TlsNewCtx Return NULL"); id = ERROR; goto EXIT; } // Insert to CTX linked list id = InsertCtxToList(ctx); EXIT: // Return Result if (sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, id) <= 0) { return ERROR; } return SUCCESS; } int RpcTlsSetCtx(CmdData *cmdData) { int ret; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); // Find the corresponding CTX. ResList *ctxList = GetCtxList(); int ctxId = atoi(cmdData->paras[0]); void *ctx = GetTlsResFromId(ctxList, ctxId); if (ctx == NULL) { LOG_ERROR("GetResFromId Error"); ret = ERROR; goto EXIT; } // Configurations related to parsing HLT_Ctx_Config ctxConfig = {0}; ret = ParseCtxConfigFromString(cmdData->paras, &ctxConfig); if (ret != SUCCESS) { LOG_ERROR("ParseCtxConfigFromString Error"); ret = ERROR; goto EXIT; } // Configure the data ret = HLT_TlsSetCtx(ctx, &ctxConfig); EXIT: // Return the result ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, ret); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcTlsNewSsl(CmdData *cmdData) { int id, ret; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); // Invoke the corresponding function. ResList *ctxList = GetCtxList(); int ctxId = atoi(cmdData->paras[0]); void *ctx = GetTlsResFromId(ctxList, ctxId); if (ctx == NULL) { LOG_ERROR("Not Find Ctx"); id = ERROR; goto EXIT; } void *ssl = HLT_TlsNewSsl(ctx); if (ssl == NULL) { LOG_ERROR("HLT_TlsNewSsl Return NULL"); id = ERROR; goto EXIT; } // Insert to the SSL linked list. id = InsertSslToList(ctx, ssl); EXIT: // Return the result. ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, id); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcTlsSetSsl(CmdData *cmdData) { int ret; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); ResList *sslList = GetSslList(); int sslId = atoi(cmdData->paras[0]); void *ssl = GetTlsResFromId(sslList, sslId); if (ssl == NULL) { LOG_ERROR("Not Find Ssl"); ret = ERROR; goto EXIT; } HLT_Ssl_Config sslConfig = {0}; sslConfig.sockFd = atoi(cmdData->paras[1]); // The first parameter indicates the FD value. sslConfig.connType = atoi(cmdData->paras[2]); // The second parameter indicates the link type. // The third parameter of indicates the Ctrl command that needs to register the hook. sslConfig.connPort = atoi(cmdData->paras[3]); ret = HLT_TlsSetSsl(ssl, &sslConfig); EXIT: // Return the result. ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, ret); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcTlsListen(CmdData *cmdData) { int ret; int sslId; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); ResList *sslList = GetSslList(); sslId = strtol(cmdData->paras[0], NULL, 10); // Convert to a decimal number void *ssl = GetTlsResFromId(sslList, sslId); if (ssl == NULL) { LOG_ERROR("Not Find Ssl"); ret = ERROR; goto EXIT; } ret = HLT_TlsListenBlock(ssl); EXIT: // Return the result ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, ret); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcTlsAccept(CmdData *cmdData) { int ret; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); ResList *sslList = GetSslList(); int sslId = atoi(cmdData->paras[0]); void *ssl = GetTlsResFromId(sslList, sslId); if (ssl == NULL) { LOG_ERROR("Not Find Ssl"); ret = ERROR; goto EXIT; } // If there is a problem, the user must use non-blocking, and the remote call must use blocking ret = HLT_TlsAcceptBlock(ssl); EXIT: // Return the result ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, ret); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcTlsConnect(CmdData *cmdData) { int ret; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); ResList *sslList = GetSslList(); int sslId = atoi(cmdData->paras[0]); void *ssl = GetTlsResFromId(sslList, sslId); if (ssl == NULL) { LOG_ERROR("Not Find Ssl"); ret = ERROR; goto EXIT; } ret = HLT_TlsConnect(ssl); EXIT: // Return the result ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, ret); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcTlsRead(CmdData *cmdData) { int ret = SUCCESS; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); ResList *sslList = GetSslList(); int sslId = atoi(cmdData->paras[0]); void *ssl = GetTlsResFromId(sslList, sslId); if (ssl == NULL) { LOG_ERROR("Not Find Ssl"); ret = ERROR; goto ERR; } int dataLen = atoi(cmdData->paras[1]); uint32_t readLen = 0; if (dataLen == 0) { LOG_ERROR("dataLen is 0"); ret = ERROR; goto ERR; } uint8_t *data = (uint8_t *)calloc(1u, dataLen); if (data == NULL) { LOG_ERROR("Calloc Error"); ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, ret); ASSERT_RETURN(ret > 0); } (void)memset_s(data, dataLen, 0, dataLen); ret = HLT_TlsRead(ssl, data, dataLen, &readLen); ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d|%u|%s", cmdData->id, cmdData->funcId, ret, readLen, data); free(data); return SUCCESS; ERR: // Return the result ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d|", cmdData->id, cmdData->funcId, ret); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcTlsWrite(CmdData *cmdData) { int ret; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); ResList *sslList = GetSslList(); int sslId = atoi(cmdData->paras[0]); void *ssl = GetTlsResFromId(sslList, sslId); if (ssl == NULL) { LOG_ERROR("Not Find Ssl"); ret = ERROR; goto ERR; } int dataLen = atoi(cmdData->paras[1]); // The first parameter indicates the data length. if (dataLen == 0) { LOG_ERROR("dataLen is 0"); ret = ERROR; goto ERR; } uint8_t *data = (uint8_t *)calloc(1u, dataLen); if (data == NULL) { LOG_ERROR("Calloc Error"); ret = ERROR; goto ERR; } if (dataLen >= CONTROL_CHANNEL_MAX_MSG_LEN) { free(data); goto ERR; } // The second parameter of indicates the content of the write data. ret = memcpy_s(data, dataLen, cmdData->paras[2], dataLen); if (ret != EOK) { LOG_ERROR("memcpy_s Error"); free(data); goto ERR; } ret = HLT_TlsWrite(ssl, data, dataLen); free(data); ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, ret); ASSERT_RETURN(ret > 0); return SUCCESS; ERR: // Return the result ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, ret); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcTlsRenegotiate(CmdData *cmdData) { int ret = ERROR; ResList *sslList = GetSslList(); int sslId = (int)strtol(cmdData->paras[0], NULL, 10); // Convert to a decimal number void *ssl = GetTlsResFromId(sslList, sslId); if (ssl == NULL) { LOG_ERROR("Not Find Ssl"); goto EXIT; } ret = HLT_TlsRenegotiate(ssl); EXIT: // Return the result ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, ret); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcTlsVerifyClientPostHandshake(CmdData *cmdData) { int ret = ERROR; ResList *sslList = GetSslList(); int sslId = (int)strtol(cmdData->paras[0], NULL, 10); // Convert to a decimal number void *ssl = GetTlsResFromId(sslList, sslId); if (ssl == NULL) { LOG_ERROR("Not Find Ssl"); goto EXIT; } ret = HLT_TlsVerifyClientPostHandshake(ssl); EXIT: // Return Result ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, ret); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcProcessExit(CmdData *cmdData) { int ret; // If 1 is returned, the process needs to exit (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, getpid()); ASSERT_RETURN(ret > 0); return 1; } int RpcDataChannelAccept(CmdData *cmdData) { int sockFd, ret; DataChannelParam channelParam; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); (void)memset_s(&channelParam, sizeof(DataChannelParam), 0, sizeof(DataChannelParam)); channelParam.type = atoi(cmdData->paras[0]); channelParam.port = atoi(cmdData->paras[1]); // The first parameter of indicates the port number channelParam.isBlock = atoi(cmdData->paras[2]); // The second parameter of indicates whether to block channelParam.bindFd = atoi(cmdData->paras[3]); // The third parameter of indicates whether the cis blocked. // Invoke the blocking interface sockFd = RunDataChannelAccept(&channelParam); // Return the result. ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, sockFd); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcDataChannelBind(CmdData *cmdData) { int sockFd, ret; DataChannelParam channelParam; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); (void)memset_s(&channelParam, sizeof(DataChannelParam), 0, sizeof(DataChannelParam)); channelParam.type = atoi(cmdData->paras[0]); channelParam.port = atoi(cmdData->paras[1]); // The first parameter of indicates the port number channelParam.isBlock = atoi(cmdData->paras[2]); // The second parameter of indicates whether to block channelParam.bindFd = atoi(cmdData->paras[3]); // The third parameter of indicates whether the cis blocked. // Invoke the blocking interface sockFd = RunDataChannelBind(&channelParam); // Return the result. ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d|%d", cmdData->id, cmdData->funcId, sockFd, channelParam.port); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcDataChannelConnect(CmdData *cmdData) { int ret, sockFd; DataChannelParam channelParam; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); (void)memset_s(&channelParam, sizeof(DataChannelParam), 0, sizeof(DataChannelParam)); channelParam.type = atoi(cmdData->paras[0]); channelParam.port = atoi(cmdData->paras[1]); // The first parameter of indicates the port number. channelParam.isBlock = atoi(cmdData->paras[2]); // The second parameter of indicates whether the is blocked sockFd = HLT_DataChannelConnect(&channelParam); // Return the result. ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, sockFd); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcTlsRegCallback(CmdData *cmdData) { int ret; TlsCallbackType type; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); type = atoi(cmdData->paras[0]); // Invoke the corresponding function ret = HLT_TlsRegCallback(type); ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, ret); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcTlsGetStatus(CmdData *cmdData) { int ret, sslId; uint32_t sslState = 0; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); ResList *sslList = GetSslList(); sslId = atoi(cmdData->paras[0]); void *ssl = GetTlsResFromId(sslList, sslId); if (ssl != NULL) { sslState = ((HITLS_Ctx *)ssl)->state; } ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%u", cmdData->id, cmdData->funcId, sslState); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcTlsGetAlertFlag(CmdData *cmdData) { int ret, sslId; ALERT_Info alertInfo = {0}; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); ResList *sslList = GetSslList(); sslId = atoi(cmdData->paras[0]); void *ssl = GetTlsResFromId(sslList, sslId); if (ssl != NULL) { ALERT_GetInfo(ssl, &alertInfo); } ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, alertInfo.flag); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcTlsGetAlertLevel(CmdData *cmdData) { int ret, sslId; ALERT_Info alertInfo = {0}; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); ResList *sslList = GetSslList(); sslId = atoi(cmdData->paras[0]); void *ssl = GetTlsResFromId(sslList, sslId); if (ssl != NULL) { ALERT_GetInfo(ssl, &alertInfo); } ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, alertInfo.level); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcTlsGetAlertDescription(CmdData *cmdData) { int ret, sslId; ALERT_Info alertInfo = {0}; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); ResList *sslList = GetSslList(); sslId = atoi(cmdData->paras[0]); void *ssl = GetTlsResFromId(sslList, sslId); if (ssl != NULL) { ALERT_GetInfo(ssl, &alertInfo); } ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, alertInfo.description); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcTlsClose(CmdData *cmdData) { int ret, sslId; void *ssl = NULL; char *endPtr = NULL; ASSERT_RETURN(memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)) == EOK); ResList *sslList = GetSslList(); sslId = (int)strtol(cmdData->paras[0], &endPtr, 0); ssl = GetTlsResFromId(sslList, sslId); ASSERT_RETURN(ssl != NULL); ret = HLT_TlsClose(ssl); // Return the result ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, ret); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcFreeResFormSsl(CmdData *cmdData) { int ret, sslId; void *ssl = NULL; char *endPtr = NULL; ASSERT_RETURN(memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)) == EOK); ResList *sslList = GetSslList(); sslId = (int)strtol(cmdData->paras[0], &endPtr, 0); ssl = GetTlsResFromId(sslList, sslId); ASSERT_RETURN(ssl != NULL); ret = HLT_FreeResFromSsl(ssl); // Return the result ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, ret); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcCloseFd(CmdData *cmdData) { int ret, fd, linkType; char *endPtr = NULL; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); fd = (int)strtol(cmdData->paras[0], &endPtr, 0); linkType = (int)strtol(cmdData->paras[1], &endPtr, 0); ret = SUCCESS; HLT_CloseFd(fd, linkType); ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, ret); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcTlsSetMtu(CmdData *cmdData) { int ret, sslId; uint16_t mtu; void *ssl = NULL; char *endPtr = NULL; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); ResList *sslList = GetSslList(); sslId = (int)strtol(cmdData->paras[0], &endPtr, 0); mtu = (int)strtol(cmdData->paras[1], &endPtr, 0); ssl = GetTlsResFromId(sslList, sslId); ASSERT_RETURN(ssl != NULL); ret = HLT_TlsSetMtu(ssl, mtu); ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, ret); ASSERT_RETURN(ret > 0); return SUCCESS; } int RpcTlsGetErrorCode(CmdData *cmdData) { int sslId; int errorCode; void *ssl = NULL; char *endPtr = NULL; (void)memset_s(cmdData->result, sizeof(cmdData->result), 0, sizeof(cmdData->result)); ResList *sslList = GetSslList(); sslId = (int)strtol(cmdData->paras[0], &endPtr, 0); ssl = GetTlsResFromId(sslList, sslId); ASSERT_RETURN(ssl != NULL); errorCode = HLT_TlsGetErrorCode(ssl); int ret = sprintf_s(cmdData->result, sizeof(cmdData->result), "%s|%s|%d", cmdData->id, cmdData->funcId, errorCode); ASSERT_RETURN(ret > 0); return SUCCESS; }
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/rpc/src/rpc_func.c
C
unknown
23,838
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CONTROL_CHANNEL_H #define CONTROL_CHANNEL_H #include "channel_res.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Initialize the control channel */ int ControlChannelInit(ControlChannelRes *info); /** * @brief Close the control channel */ int ControlChannelClose(ControlChannelRes *info); /** * @brief Read data from the control channel */ int ControlChannelRead(int32_t sockFd, ControlChannelBuf *dataBuf); /** * @brief Write data to the control channel */ int ControlChannelWrite(int32_t sockFd, char *peerDomainPath, ControlChannelBuf *dataBuf); /** * @brief Control channel initiation */ int ControlChannelConnect(ControlChannelRes *info); /** * @brief The control channel waits for a connection */ int ControlChannelAccept(ControlChannelRes *info); #ifdef __cplusplus } #endif #endif // CONTROL_CHANNEL_H
2401_83913325/openHiTLS-examples_2461
testcode/framework/tls/transfer/include/control_channel.h
C
unknown
1,395