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