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