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