From e18f9b7337bf666f7c8ace22103c3734f345fd63 Mon Sep 17 00:00:00 2001 From: Bryan Paxton Date: Sun, 26 Jul 2020 14:25:24 -0500 Subject: [PATCH 1/2] Ensure we never return 1 from sodium_init() onload sodium_init() will return 0 on success, -1 on failure, and 1 if sodium is already loaded and initialized (which is not an error). In the case where libsodium is already initialized and the system is restarted we may return 1 from onload nif function resulting in a crash. - change the call to sodium_init() to check for an error return (-1) and return -1 explicitly in this case, otherwise always return zero at the end of our onload function. --- c_src/enacl_nif.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/c_src/enacl_nif.c b/c_src/enacl_nif.c index d4bd73c..b62f746 100644 --- a/c_src/enacl_nif.c +++ b/c_src/enacl_nif.c @@ -41,7 +41,11 @@ static int enacl_crypto_load(ErlNifEnv *env, void **priv_data, return -1; } - return sodium_init(); + if (sodium_init() == -1) { + return -1; + } + + return 0; } /* GENERAL ROUTINES From 0351de9882927e03c6611e077cb753463bff7525 Mon Sep 17 00:00:00 2001 From: Bryan Paxton Date: Tue, 28 Jul 2020 18:30:59 -0500 Subject: [PATCH 2/2] add upgrade and unload handlers --- c_src/enacl_nif.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/c_src/enacl_nif.c b/c_src/enacl_nif.c index b62f746..268096a 100644 --- a/c_src/enacl_nif.c +++ b/c_src/enacl_nif.c @@ -48,6 +48,17 @@ static int enacl_crypto_load(ErlNifEnv *env, void **priv_data, return 0; } +static int enacl_crypto_upgrade(ErlNifEnv* env, void **priv_data, + void **old_priv_data, + ERL_NIF_TERM load_info) { + return 0; +} + +static int enacl_crypto_unload(ErlNifEnv* env, void **priv_data, + ERL_NIF_TERM load_info) { + return 0; +} + /* GENERAL ROUTINES * * These don't generally fit somewhere else nicely, so we keep them in the main @@ -421,4 +432,4 @@ static ErlNifFunc nif_funcs[] = { "crypto_secretstream_xchacha20poly1305_pull", 3, enacl_crypto_secretstream_xchacha20poly1305_pull)}; -ERL_NIF_INIT(enacl_nif, nif_funcs, enacl_crypto_load, NULL, NULL, NULL); +ERL_NIF_INIT(enacl_nif, nif_funcs, enacl_crypto_load, NULL, enacl_crypto_upgrade, enacl_crypto_unload);