1 //
2 // OpenSSLInitializer.h
3 //
4 // Library: Crypto
5 // Package: CryptoCore
6 // Module: OpenSSLInitializer
7 //
8 // Definition of the OpenSSLInitializer class.
9 //
10 // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH.
11 // and Contributors.
12 //
13 // SPDX-License-Identifier: BSL-1.0
14 //
15
16
17 #ifndef Crypto_OpenSSLInitializer_INCLUDED
18 #define Crypto_OpenSSLInitializer_INCLUDED
19
20
21 #include "Poco/Crypto/Crypto.h"
22 #include "Poco/Mutex.h"
23 #include "Poco/AtomicCounter.h"
24 #include <openssl/crypto.h>
25
26 #if defined(OPENSSL_FIPS) && OPENSSL_VERSION_NUMBER < 0x010001000L
27 #include <openssl/fips.h>
28 #endif
29
30
31 extern "C"
32 {
33 struct CRYPTO_dynlock_value
34 {
35 Poco::FastMutex _mutex;
36 };
37 }
38
39
40 namespace Poco {
41 namespace Crypto {
42
43
44 class Crypto_API OpenSSLInitializer
45 /// Initalizes the OpenSSL library.
46 ///
47 /// The class ensures the earliest initialization and the
48 /// latest shutdown of the OpenSSL library.
49 {
50 public:
51 OpenSSLInitializer();
52 /// Automatically initialize OpenSSL on startup.
53
54 ~OpenSSLInitializer();
55 /// Automatically shut down OpenSSL on exit.
56
57 static void initialize();
58 /// Initializes the OpenSSL machinery.
59
60 static void uninitialize();
61 /// Shuts down the OpenSSL machinery.
62
63 static bool isFIPSEnabled();
64 // Returns true if FIPS mode is enabled, false otherwise.
65
66 static void enableFIPSMode(bool enabled);
67 // Enable or disable FIPS mode. If FIPS is not available, this method doesn't do anything.
68
69 protected:
70 enum
71 {
72 SEEDSIZE = 256
73 };
74
75 // OpenSSL multithreading support
76 static void lock(int mode, int n, const char* file, int line);
77 static unsigned long id();
78 static struct CRYPTO_dynlock_value* dynlockCreate(const char* file, int line);
79 static void dynlock(int mode, struct CRYPTO_dynlock_value* lock, const char* file, int line);
80 static void dynlockDestroy(struct CRYPTO_dynlock_value* lock, const char* file, int line);
81
82 private:
83 static Poco::FastMutex* _mutexes;
84 static Poco::AtomicCounter _rc;
85 };
86
87
88 //
89 // inlines
90 //
isFIPSEnabled()91 inline bool OpenSSLInitializer::isFIPSEnabled()
92 {
93 #ifdef OPENSSL_FIPS
94 return FIPS_mode() ? true : false;
95 #else
96 return false;
97 #endif
98 }
99
100 #ifdef OPENSSL_FIPS
enableFIPSMode(bool enabled)101 inline void OpenSSLInitializer::enableFIPSMode(bool enabled)
102 {
103 FIPS_mode_set(enabled);
104 }
105 #else
enableFIPSMode(bool)106 inline void OpenSSLInitializer::enableFIPSMode(bool /*enabled*/)
107 {
108 }
109 #endif
110
111
112 } } // namespace Poco::Crypto
113
114
115 #endif // Crypto_OpenSSLInitializer_INCLUDED
116