@@ -45,6 +45,8 @@ static int _handle_error(int err, const char * function, int line)
45
45
46
46
void ssl_init (sslclient_context *ssl_client)
47
47
{
48
+ // reset embedded pointers to zero
49
+ memset (ssl_client, 0 , sizeof (sslclient_context));
48
50
mbedtls_ssl_init (&ssl_client->ssl_ctx );
49
51
mbedtls_ssl_config_init (&ssl_client->ssl_conf );
50
52
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
232
234
ret = mbedtls_pk_parse_key (&ssl_client->client_key , (const unsigned char *)cli_key, strlen (cli_key) + 1 , NULL , 0 );
233
235
234
236
if (ret != 0 ) {
237
+ mbedtls_x509_crt_free (&ssl_client->client_cert ); // cert+key are free'd in pair
235
238
return handle_error (ret);
236
239
}
237
240
@@ -243,7 +246,7 @@ int start_ssl_client(sslclient_context *ssl_client, const char *host, uint32_t p
243
246
// Hostname set here should match CN in server certificate
244
247
if ((ret = mbedtls_ssl_set_hostname (&ssl_client->ssl_ctx , host)) != 0 ){
245
248
return handle_error (ret);
246
- }
249
+ }
247
250
248
251
mbedtls_ssl_conf_rng (&ssl_client->ssl_conf , mbedtls_ctr_drbg_random, &ssl_client->drbg_ctx );
249
252
@@ -260,8 +263,8 @@ int start_ssl_client(sslclient_context *ssl_client, const char *host, uint32_t p
260
263
return handle_error (ret);
261
264
}
262
265
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
265
268
}
266
269
267
270
@@ -280,7 +283,6 @@ int start_ssl_client(sslclient_context *ssl_client, const char *host, uint32_t p
280
283
memset (buf, 0 , sizeof (buf));
281
284
mbedtls_x509_crt_verify_info (buf, sizeof (buf), " ! " , flags);
282
285
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.
284
286
return handle_error (ret);
285
287
} else {
286
288
log_v (" Certificate verified." );
@@ -313,10 +315,20 @@ void stop_ssl_socket(sslclient_context *ssl_client, const char *rootCABuff, cons
313
315
ssl_client->socket = -1 ;
314
316
}
315
317
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
+ }
316
326
mbedtls_ssl_free (&ssl_client->ssl_ctx );
317
327
mbedtls_ssl_config_free (&ssl_client->ssl_conf );
318
328
mbedtls_ctr_drbg_free (&ssl_client->drbg_ctx );
319
329
mbedtls_entropy_free (&ssl_client->entropy_ctx );
330
+ // reset embedded pointers to zero
331
+ memset (ssl_client, 0 , sizeof (sslclient_context));
320
332
}
321
333
322
334
0 commit comments