#include "tls/bs_tls_mbed.h" #if (BS_TLS_MBEDTLS_EN) /* * 简单的 mbedtls TLS client 封装,供 plat_comm 使用。 * 证书校验策略、CA 证书加载等可根据项目需要在此扩展。 */ /* 可根据项目实际把根证书放到只读 Flash,这里先留空,由用户自行填充 */ static const char *s_default_root_ca_pem = NULL; int bs_tls_client_connect(BS_TLS_CTX *ctx, int fd, const char *host) { int ret; const char *pers = "ccu-bs-tls"; if (ctx == NULL || host == NULL) { return -1; } memset(ctx, 0, sizeof(BS_TLS_CTX)); mbedtls_net_init(&ctx->net_ctx); mbedtls_ssl_init(&ctx->ssl); mbedtls_ssl_config_init(&ctx->conf); mbedtls_ctr_drbg_init(&ctx->ctr_drbg); mbedtls_entropy_init(&ctx->entropy); if ((ret = mbedtls_ctr_drbg_seed(&ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy, (const unsigned char *)pers, strlen(pers))) != 0) { return ret; } if ((ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT)) != 0) { return ret; } /* 证书校验策略:先使用 VERIFY_OPTIONAL,后续可根据需要收紧为 VERIFY_REQUIRED */ mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL); mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg); /* TODO: 如需严格校验证书,可在此加载根证书: * mbedtls_x509_crt_init(...); * mbedtls_x509_crt_parse(..., s_default_root_ca_pem, ...); * mbedtls_ssl_conf_ca_chain(&ctx->conf, &cacert, NULL); */ if ((ret = mbedtls_ssl_setup(&ctx->ssl, &ctx->conf)) != 0) { return ret; } if ((ret = mbedtls_ssl_set_hostname(&ctx->ssl, host)) != 0) { return ret; } /* 将已有的 TCP socket fd 绑定到 mbedtls 的 net_sockets 封装上 */ ctx->net_ctx.fd = fd; mbedtls_ssl_set_bio(&ctx->ssl, &ctx->net_ctx, mbedtls_net_send, mbedtls_net_recv, NULL); while ((ret = mbedtls_ssl_handshake(&ctx->ssl)) != 0) { if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { return ret; } } ctx->inited = 1U; return 0; } int bs_tls_client_send(BS_TLS_CTX *ctx, const unsigned char *buf, size_t len) { if (ctx == NULL || ctx->inited == 0U) { return -1; } return mbedtls_ssl_write(&ctx->ssl, buf, len); } int bs_tls_client_recv(BS_TLS_CTX *ctx, unsigned char *buf, size_t len) { if (ctx == NULL || ctx->inited == 0U) { return -1; } return mbedtls_ssl_read(&ctx->ssl, buf, len); } void bs_tls_client_close(BS_TLS_CTX *ctx) { if (ctx == NULL || ctx->inited == 0U) { return; } (void)mbedtls_ssl_close_notify(&ctx->ssl); mbedtls_ssl_free(&ctx->ssl); mbedtls_ssl_config_free(&ctx->conf); mbedtls_ctr_drbg_free(&ctx->ctr_drbg); mbedtls_entropy_free(&ctx->entropy); mbedtls_net_free(&ctx->net_ctx); ctx->inited = 0U; } #endif /* BS_TLS_MBEDTLS_EN */