From d1881acbdcffbc43c5a38e357562f0f814783039 Mon Sep 17 00:00:00 2001 From: Jonathan Reams Date: Sun, 31 Aug 2014 13:30:44 -0400 Subject: [PATCH] Clean up after using randombytes from libsodium When Curve authentication is used, libsodium opens a file descriptor to /dev/urandom to generate random bytes. When the ZMQ context terminates, it should ensure that file gets closed. --- src/ctx.cpp | 14 ++++++++++++++ tweetnacl/contrib/randombytes/devurandom.c | 10 ++++++++++ tweetnacl/contrib/randombytes/devurandom.h | 1 + 3 files changed, 25 insertions(+) diff --git a/src/ctx.cpp b/src/ctx.cpp index 2842d7b6..399c2677 100644 --- a/src/ctx.cpp +++ b/src/ctx.cpp @@ -36,6 +36,14 @@ #include "err.hpp" #include "msg.hpp" +#ifdef HAVE_LIBSODIUM +#ifdef HAVE_TWEETNACL +#include "randombytes.h" +#else +#include "sodium.h" +#endif +#endif + #define ZMQ_CTX_TAG_VALUE_GOOD 0xabadcafe #define ZMQ_CTX_TAG_VALUE_BAD 0xdeadbeef @@ -93,6 +101,12 @@ zmq::ctx_t::~ctx_t () // corresponding io_thread/socket objects. free (slots); + // If we've done any Curve encryption, we may have a file handle + // to /dev/urandom open that needs to be cleaned up. +#ifdef HAVE_LIBSODIUM + randombytes_close(); +#endif + // Remove the tag, so that the object is considered dead. tag = ZMQ_CTX_TAG_VALUE_BAD; } diff --git a/tweetnacl/contrib/randombytes/devurandom.c b/tweetnacl/contrib/randombytes/devurandom.c index f3b8d418..4fdd40ad 100644 --- a/tweetnacl/contrib/randombytes/devurandom.c +++ b/tweetnacl/contrib/randombytes/devurandom.c @@ -32,3 +32,13 @@ void randombytes(unsigned char *x,unsigned long long xlen) xlen -= i; } } + +int randombytes_close(void) +{ + int rc = -1; + if(fd != -1 && close(fd) == 0) { + fd = -1; + rc = 0; + } + return rc; +} diff --git a/tweetnacl/contrib/randombytes/devurandom.h b/tweetnacl/contrib/randombytes/devurandom.h index 2e0caf8a..63e9e543 100644 --- a/tweetnacl/contrib/randombytes/devurandom.h +++ b/tweetnacl/contrib/randombytes/devurandom.h @@ -12,6 +12,7 @@ extern "C" { #endif extern void randombytes(unsigned char *,unsigned long long); +extern int randombytes_close(void); #ifdef __cplusplus }