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