Skip to content

Commit

Permalink
Merge pull request #360 from david-cermak/fix/modem_example_mbedtls_w…
Browse files Browse the repository at this point in the history
…rapper

fix(modem): TLS example: Add restore session support in mbedtls wrapper
  • Loading branch information
david-cermak authored Nov 28, 2023
2 parents afbca53 + 79d38e5 commit 0c6bb4b
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#pragma once

#include <utility>
#include <memory>
#include <span>
#include "mbedtls/ssl.h"
#include "mbedtls/entropy.h"
Expand All @@ -22,6 +23,7 @@ class Tls {
Tls();
virtual ~Tls();
bool init(is_server server, do_verify verify);
bool deinit();
int handshake();
int write(const unsigned char *buf, size_t len);
int read(unsigned char *buf, size_t len);
Expand All @@ -41,12 +43,33 @@ class Tls {
mbedtls_entropy_context entropy_{};
virtual void delay() {}

bool set_session();
bool get_session();
void reset_session();
bool is_session_loaded();

private:
static void print_error(const char *function, int error_code);
static int bio_write(void *ctx, const unsigned char *buf, size_t len);
static int bio_read(void *ctx, unsigned char *buf, size_t len);
int mbedtls_pk_parse_key( mbedtls_pk_context *ctx,
const unsigned char *key, size_t keylen,
const unsigned char *pwd, size_t pwdlen);
struct unique_session {
unique_session()
{
::mbedtls_ssl_session_init(&s);
}
~unique_session()
{
::mbedtls_ssl_session_free(&s);
}
mbedtls_ssl_session *ptr()
{
return &s;
}
mbedtls_ssl_session s;
};
std::unique_ptr<unique_session> session_;

};
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,16 @@ bool Tls::init(is_server server, do_verify verify)
return true;
}

bool Tls::deinit()
{
::mbedtls_ssl_config_free(&conf_);
::mbedtls_ssl_free(&ssl_);
::mbedtls_pk_free(&pk_key_);
::mbedtls_x509_crt_free(&public_cert_);
::mbedtls_x509_crt_free(&ca_cert_);
return true;
}

void Tls::print_error(const char *function, int error_code)
{
static char error_buf[100];
Expand Down Expand Up @@ -132,3 +142,39 @@ Tls::~Tls()
::mbedtls_x509_crt_free(&public_cert_);
::mbedtls_x509_crt_free(&ca_cert_);
}

bool Tls::get_session()
{
if (session_ == nullptr) {
session_ = std::make_unique<unique_session>();
}
int ret = ::mbedtls_ssl_get_session(&ssl_, session_->ptr());
if (ret != 0) {
print_error("mbedtls_ssl_get_session() failed", ret);
return false;
}
return true;
}

bool Tls::set_session()
{
if (session_ == nullptr) {
printf("session hasn't been initialized");
return false;
}
int ret = mbedtls_ssl_set_session(&ssl_, session_->ptr());
if (ret != 0) {
print_error("mbedtls_ssl_set_session() failed", ret);
return false;
}
return true;
}

void Tls::reset_session()
{
session_.reset(nullptr);
}
bool Tls::is_session_loaded()
{
return session_ != nullptr;
}

0 comments on commit 0c6bb4b

Please sign in to comment.