623fd4
diff --git a/src/lib/crypto/OSSLCryptoFactory.cpp b/src/lib/crypto/OSSLCryptoFactory.cpp
623fd4
index 32daca2..ace4bcb 100644
623fd4
--- a/src/lib/crypto/OSSLCryptoFactory.cpp
623fd4
+++ b/src/lib/crypto/OSSLCryptoFactory.cpp
623fd4
@@ -226,31 +226,49 @@ err:
623fd4
 // Destructor
623fd4
 OSSLCryptoFactory::~OSSLCryptoFactory()
623fd4
 {
623fd4
-#ifdef WITH_GOST
623fd4
-	// Finish the GOST engine
623fd4
-	if (eg != NULL)
623fd4
+	bool ossl_shutdown = false;
623fd4
+
623fd4
+#if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
623fd4
+	// OpenSSL 1.1.0+ will register an atexit() handler to run
623fd4
+	// OPENSSL_cleanup(). If that has already happened we must
623fd4
+	// not attempt to free any ENGINEs because they'll already
623fd4
+	// have been destroyed and the use-after-free would cause
623fd4
+	// a deadlock or crash.
623fd4
+	//
623fd4
+	// Detect that situation because reinitialisation will fail
623fd4
+	// after OPENSSL_cleanup() has run.
623fd4
+	(void)ERR_set_mark();
623fd4
+	ossl_shutdown = !OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_RDRAND, NULL);
623fd4
+	(void)ERR_pop_to_mark();
623fd4
+#endif
623fd4
+	if (!ossl_shutdown)
623fd4
 	{
623fd4
-		ENGINE_finish(eg);
623fd4
-		ENGINE_free(eg);
623fd4
-		eg = NULL;
623fd4
-	}
623fd4
+#ifdef WITH_GOST
623fd4
+		// Finish the GOST engine
623fd4
+		if (eg != NULL)
623fd4
+		{
623fd4
+			ENGINE_finish(eg);
623fd4
+			ENGINE_free(eg);
623fd4
+			eg = NULL;
623fd4
+		}
623fd4
 #endif
623fd4
 
623fd4
-	// Finish the rd_rand engine
623fd4
-	ENGINE_finish(rdrand_engine);
623fd4
-	ENGINE_free(rdrand_engine);
623fd4
-	rdrand_engine = NULL;
623fd4
+		// Finish the rd_rand engine
623fd4
+		ENGINE_finish(rdrand_engine);
623fd4
+		ENGINE_free(rdrand_engine);
623fd4
+		rdrand_engine = NULL;
623fd4
 
623fd4
+		// Recycle locks
623fd4
+#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
623fd4
+		if (setLockingCallback)
623fd4
+		{
623fd4
+			CRYPTO_set_locking_callback(NULL);
623fd4
+		}
623fd4
+#endif
623fd4
+	}
623fd4
 	// Destroy the one-and-only RNG
623fd4
 	delete rng;
623fd4
 
623fd4
-	// Recycle locks
623fd4
-#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
623fd4
-	if (setLockingCallback)
623fd4
-	{
623fd4
-		CRYPTO_set_locking_callback(NULL);
623fd4
-	}
623fd4
-#endif
623fd4
 	for (unsigned i = 0; i < nlocks; i++)
623fd4
 	{
623fd4
 		MutexFactory::i()->recycleMutex(locks[i]);