mosquitto icon indicating copy to clipboard operation
mosquitto copied to clipboard

lib: Valgrind leak reported when TLS supported but not used

Open dirkfeytons opened this issue 6 months ago • 0 comments

Using Mosquitto 2.0.18 with support for TLS compiled in, and OpenSSL 3 on Linux.

Broker config:

listener 1883
allow_anonymous true

Then running valgrind --show-leak-kinds=all --leak-check=full mosquitto_sub -h 127.0.0.1 -p 1883 -t '#' and stopping it will have Valgrind report the following leak:

==10755== 56 bytes in 1 blocks are still reachable in loss record 1 of 1
==10755==    at 0x484880F: malloc (vg_replace_malloc.c:431)
==10755==    by 0x4B0FAB9: CRYPTO_malloc (mem.c:190)
==10755==    by 0x4B0FAE8: CRYPTO_zalloc (mem.c:197)
==10755==    by 0x4B213D6: CRYPTO_THREAD_lock_new (threads_pthread.c:50)
==10755==    by 0x4A33386: do_init_module_list_lock (conf_mod.c:101)
==10755==    by 0x4A33371: do_init_module_list_lock_ossl_ (conf_mod.c:99)
==10755==    by 0x4DEBEE7: __pthread_once_slow (pthread_once.c:116)
==10755==    by 0x4B21519: CRYPTO_THREAD_run_once (threads_pthread.c:156)
==10755==    by 0x4A341D4: conf_modules_finish_int (conf_mod.c:521)
==10755==    by 0x4A34077: CONF_modules_unload (conf_mod.c:482)
==10755==    by 0x11D70B: net__cleanup (net_mosq.c:162)
==10755==    by 0x11C8E7: mosquitto_lib_cleanup (mosquitto.c:95)

Root cause seems to be that in ./lib/net_mosq.c::net__cleanup() some OpenSSL cleanup functions are called but OpenSSL was never initialized because no TLS is used. The call to CONF_modules_unload() causes some of the automatic initialization of OpenSSL to kick in but some memory allocated there is not freed. AFAICS OpenSSL normally installs an atexit() handler to make sure everything is freed but this has not happened in this scenario; presumably because there never was a full init needed.

One could argue this is an issue in OpenSSL but as a simple workaround Mosquitto could in net__cleanup() only call the various OpenSSL cleanup functions if is_tls_initialized is set to true. With such a change Valgrind is no longer reporting issues.

dirkfeytons avatar Jan 08 '24 17:01 dirkfeytons