From bfba9daf1519b03b62e613d5c67d96c4c999fe29 Mon Sep 17 00:00:00 2001 From: Simone Orru Date: Wed, 17 May 2023 15:34:30 +0200 Subject: [PATCH] Improve checks on certificate Signed-off-by: Simone Orru --- CHANGELOG.md | 4 ++++ astarte_credentials.c | 41 ++++++++++++++++++++++++++++++++++- include/astarte_credentials.h | 3 +++ 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 72988017..178c648f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [1.1.3] - Unreleased +### Fixed +- Fix crash when using an invalid client certificate. + ## [1.1.2] - 2023-04-13 ### Fixed - Fix hardware ID generation for IDF 5.0. diff --git a/astarte_credentials.c b/astarte_credentials.c index 96172f91..32711307 100644 --- a/astarte_credentials.c +++ b/astarte_credentials.c @@ -835,7 +835,46 @@ astarte_err_t astarte_credentials_erase_stored_credentials_secret() bool astarte_credentials_has_certificate() { CREDS_STORAGE_FUNCS(funcs); - return funcs->astarte_credentials_exists(creds_ctx.opaque, ASTARTE_CREDENTIALS_CERTIFICATE); + if (!funcs->astarte_credentials_exists(creds_ctx.opaque, ASTARTE_CREDENTIALS_CERTIFICATE)) { + return false; + } + + astarte_err_t astarte_ret = ASTARTE_ERR; + char *client_crt_cn = NULL; + + char *client_crt_pem = calloc(CERT_LENGTH, sizeof(char)); + if (!client_crt_pem) { + ESP_LOGE(TAG, "Out of memory %s: %d", __FILE__, __LINE__); + astarte_ret = ASTARTE_ERR_OUT_OF_MEMORY; + goto exit; + } + + astarte_ret = astarte_credentials_get_certificate(client_crt_pem, CERT_LENGTH); + if (astarte_ret != ASTARTE_OK) { + ESP_LOGE(TAG, "astarte_credentials_get_certificate returned %d", astarte_ret); + goto exit; + } + + client_crt_cn = calloc(CN_LENGTH, sizeof(char)); + if (!client_crt_cn) { + ESP_LOGE(TAG, "Out of memory %s: %d", __FILE__, __LINE__); + goto exit; + } + + astarte_ret + = astarte_credentials_get_certificate_common_name(client_crt_pem, client_crt_cn, CN_LENGTH); + if (astarte_ret != ASTARTE_OK) { + ESP_LOGE(TAG, "astarte_credentials_get_certificate_common_name returned %d", astarte_ret); + goto exit; + } + + astarte_ret = ASTARTE_OK; + +exit: + free(client_crt_pem); + free(client_crt_cn); + + return astarte_ret == ASTARTE_OK; } bool astarte_credentials_has_csr() diff --git a/include/astarte_credentials.h b/include/astarte_credentials.h index ba5a90df..5487029d 100644 --- a/include/astarte_credentials.h +++ b/include/astarte_credentials.h @@ -17,6 +17,9 @@ #include #include +#define CERT_LENGTH 4096 +#define CN_LENGTH 512 + #define ASTARTE_CREDENTIALS_DEFAULT_NVS_PARTITION NULL enum credential_type_t