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