@@ -45,6 +45,8 @@ static int _handle_error(int err, const char * function, int line)
4545
4646void ssl_init (sslclient_context *ssl_client)
4747{
48+ // reset embedded pointers to zero
49+ memset (ssl_client, 0 , sizeof (sslclient_context));
4850 mbedtls_ssl_init (&ssl_client->ssl_ctx );
4951 mbedtls_ssl_config_init (&ssl_client->ssl_conf );
5052 mbedtls_ctr_drbg_init (&ssl_client->drbg_ctx );
@@ -232,6 +234,7 @@ int start_ssl_client(sslclient_context *ssl_client, const char *host, uint32_t p
232234 ret = mbedtls_pk_parse_key (&ssl_client->client_key , (const unsigned char *)cli_key, strlen (cli_key) + 1 , NULL , 0 );
233235
234236 if (ret != 0 ) {
237+ mbedtls_x509_crt_free (&ssl_client->client_cert ); // cert+key are free'd in pair
235238 return handle_error (ret);
236239 }
237240
@@ -243,7 +246,7 @@ int start_ssl_client(sslclient_context *ssl_client, const char *host, uint32_t p
243246 // Hostname set here should match CN in server certificate
244247 if ((ret = mbedtls_ssl_set_hostname (&ssl_client->ssl_ctx , host)) != 0 ){
245248 return handle_error (ret);
246- }
249+ }
247250
248251 mbedtls_ssl_conf_rng (&ssl_client->ssl_conf , mbedtls_ctr_drbg_random, &ssl_client->drbg_ctx );
249252
@@ -260,8 +263,8 @@ int start_ssl_client(sslclient_context *ssl_client, const char *host, uint32_t p
260263 return handle_error (ret);
261264 }
262265 if ((millis ()-handshake_start_time)>ssl_client->handshake_timeout )
263- return -1 ;
264- vTaskDelay (2 );// 2 ticks
266+ return -1 ;
267+ vTaskDelay (2 );// 2 ticks
265268 }
266269
267270
@@ -280,7 +283,6 @@ int start_ssl_client(sslclient_context *ssl_client, const char *host, uint32_t p
280283 memset (buf, 0 , sizeof (buf));
281284 mbedtls_x509_crt_verify_info (buf, sizeof (buf), " ! " , flags);
282285 log_e (" Failed to verify peer certificate! verification info: %s" , buf);
283- stop_ssl_socket (ssl_client, rootCABuff, cli_cert, cli_key); // It's not safe continue.
284286 return handle_error (ret);
285287 } else {
286288 log_v (" Certificate verified." );
@@ -313,10 +315,20 @@ void stop_ssl_socket(sslclient_context *ssl_client, const char *rootCABuff, cons
313315 ssl_client->socket = -1 ;
314316 }
315317
318+ // avoid memory leak if ssl connection attempt failed
319+ if (ssl_client->ssl_conf .ca_chain != NULL ) {
320+ mbedtls_x509_crt_free (&ssl_client->ca_cert );
321+ }
322+ if (ssl_client->ssl_conf .key_cert != NULL ) {
323+ mbedtls_x509_crt_free (&ssl_client->client_cert );
324+ mbedtls_pk_free (&ssl_client->client_key );
325+ }
316326 mbedtls_ssl_free (&ssl_client->ssl_ctx );
317327 mbedtls_ssl_config_free (&ssl_client->ssl_conf );
318328 mbedtls_ctr_drbg_free (&ssl_client->drbg_ctx );
319329 mbedtls_entropy_free (&ssl_client->entropy_ctx );
330+ // reset embedded pointers to zero
331+ memset (ssl_client, 0 , sizeof (sslclient_context));
320332}
321333
322334
0 commit comments