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