1//
2// SSLManager.h
3//
4// Library: NetSSL_OpenSSL
5// Package: SSLCore
6// Module: SSLManager
7//
8// Definition of the SSLManager class.
9//
10// Copyright (c) 2006-2010, Applied Informatics Software Engineering GmbH.
11// and Contributors.
12//
13// SPDX-License-Identifier: BSL-1.0
14//
15
16
17#ifndef NetSSL_SSLManager_INCLUDED
18#define NetSSL_SSLManager_INCLUDED
19
20
21#include "Poco/Net/NetSSL.h"
22#include "Poco/Net/VerificationErrorArgs.h"
23#include "Poco/Net/Context.h"
24#include "Poco/Net/PrivateKeyFactoryMgr.h"
25#include "Poco/Net/CertificateHandlerFactoryMgr.h"
26#include "Poco/Net/InvalidCertificateHandler.h"
27#include "Poco/Util/AbstractConfiguration.h"
28#include "Poco/BasicEvent.h"
29#include "Poco/SharedPtr.h"
30#include "Poco/Mutex.h"
31#include <openssl/ssl.h>
32#ifdef OPENSSL_FIPS
33#include <openssl/fips.h>
34#endif
35
36
37namespace Poco {
38namespace Net {
39
40
41class Context;
42
43
44class NetSSL_API SSLManager
45 /// SSLManager is a singleton for holding the default server/client
46 /// Context and handling callbacks for certificate verification errors
47 /// and private key passphrases.
48 ///
49 /// Proper initialization of SSLManager is critical.
50 ///
51 /// SSLManager can be initialized manually, by calling initializeServer()
52 /// and/or initializeClient(), or initialization can be automatic. In the latter
53 /// case, a Poco::Util::Application instance must be available and the required
54 /// configuration properties must be set (see below).
55 ///
56 /// Note that manual initialization must happen very early in the application,
57 /// before defaultClientContext() or defaultServerContext() are called.
58 ///
59 /// If defaultClientContext() and defaultServerContext() are never called
60 /// in an application, initialization of SSLManager can be omitted.
61 /// However, in this case, delegates for the ServerVerificationError,
62 /// ClientVerificationError and PrivateKeyPassphraseRequired events
63 /// must be registered.
64 ///
65 /// An exemplary documentation which sets either the server or client default context and creates
66 /// a PrivateKeyPassphraseHandler that reads the password from the XML file looks like this:
67 ///
68 /// <AppConfig>
69 /// <openSSL>
70 /// <server|client>
71 /// <privateKeyFile>mycert.key</privateKeyFile>
72 /// <certificateFile>mycert.crt</certificateFile>
73 /// <caConfig>rootcert.pem</caConfig>
74 /// <verificationMode>none|relaxed|strict|once</verificationMode>
75 /// <verificationDepth>1..9</verificationDepth>
76 /// <loadDefaultCAFile>true|false</loadDefaultCAFile>
77 /// <cipherList>ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH</cipherList>
78 /// <preferServerCiphers>true|false</preferServerCiphers>
79 /// <privateKeyPassphraseHandler>
80 /// <name>KeyFileHandler</name>
81 /// <options>
82 /// <password>test</password>
83 /// </options>
84 /// </privateKeyPassphraseHandler>
85 /// <invalidCertificateHandler>
86 /// <name>ConsoleCertificateHandler</name>
87 /// </invalidCertificateHandler>
88 /// <cacheSessions>true|false</cacheSessions>
89 /// <sessionIdContext>someString</sessionIdContext> <!-- server only -->
90 /// <sessionCacheSize>0..n</sessionCacheSize> <!-- server only -->
91 /// <sessionTimeout>0..n</sessionTimeout> <!-- server only -->
92 /// <extendedVerification>true|false</extendedVerification>
93 /// <requireTLSv1>true|false</requireTLSv1>
94 /// <requireTLSv1_1>true|false</requireTLSv1_1>
95 /// <requireTLSv1_2>true|false</requireTLSv1_2>
96 /// <disableProtocols>sslv2,sslv3,tlsv1,tlsv1_1,tlsv1_2</disableProtocols>
97 /// <dhParamsFile>dh.pem</dhParamsFile>
98 /// <ecdhCurve>prime256v1</ecdhCurve>
99 /// </server|client>
100 /// <fips>false</fips>
101 /// </openSSL>
102 /// </AppConfig>
103 ///
104 /// Following is a list of supported configuration properties. Property names must always
105 /// be prefixed with openSSL.server or openSSL.client. Some properties are only supported
106 /// for servers.
107 ///
108 /// - privateKeyFile (string): The path to the file containing the private key for the certificate
109 /// in PEM format (or containing both the private key and the certificate).
110 /// - certificateFile (string): The Path to the file containing the server's or client's certificate
111 /// in PEM format. Can be omitted if the the file given in privateKeyFile contains the certificate as well.
112 /// - caConfig (string): The path to the file or directory containing the trusted root certificates.
113 /// - verificationMode (string): Specifies whether and how peer certificates are validated (see
114 /// the Context class for details). Valid values are none, relaxed, strict, once.
115 /// - verificationDepth (integer, 1-9): Sets the upper limit for verification chain sizes. Verification
116 /// will fail if a certificate chain larger than this is encountered.
117 /// - loadDefaultCAFile (boolean): Specifies whether the builtin CA certificates from OpenSSL are used.
118 /// - cipherList (string): Specifies the supported ciphers in OpenSSL notation
119 /// (e.g. "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH").
120 /// - preferServerCiphers (bool): When choosing a cipher, use the server's preferences instead of the
121 /// client preferences. When not called, the SSL server will always follow the clients
122 /// preferences. When called, the SSL/TLS server will choose following its own
123 /// preferences.
124 /// - privateKeyPassphraseHandler.name (string): The name of the class (subclass of PrivateKeyPassphraseHandler)
125 /// used for obtaining the passphrase for accessing the private key.
126 /// - privateKeyPassphraseHandler.options.password (string): The password to be used by KeyFileHandler.
127 /// - invalidCertificateHandler.name: The name of the class (subclass of CertificateHandler)
128 /// used for confirming invalid certificates.
129 /// - cacheSessions (boolean): Enables or disables session caching.
130 /// - sessionIdContext (string): contains the application's unique session ID context, which becomes
131 /// part of each session identifier generated by the server. Can be an arbitrary sequence
132 /// of bytes with a maximum length of SSL_MAX_SSL_SESSION_ID_LENGTH. Should be specified
133 /// for a server to enable session caching. Should be specified even if session caching
134 /// is disabled to avoid problems with clients that request session caching (e.g. Firefox 3.6).
135 /// If not specified, defaults to ${application.name}.
136 /// - sessionCacheSize (integer): Sets the maximum size of the server session cache, in number of
137 /// sessions. The default size (according to OpenSSL documentation) is 1024*20, which may be too
138 /// large for many applications, especially on embedded platforms with limited memory.
139 /// Specifying a size of 0 will set an unlimited cache size.
140 /// - sessionTimeout (integer): Sets the timeout (in seconds) of cached sessions on the server.
141 /// - extendedVerification (boolean): Enable or disable the automatic post-connection
142 /// extended certificate verification.
143 /// - requireTLSv1 (boolean): Require a TLSv1 connection.
144 /// - requireTLSv1_1 (boolean): Require a TLSv1.1 connection.
145 /// - requireTLSv1_2 (boolean): Require a TLSv1.2 connection.
146 /// - disableProtocols (string): A comma-separated list of protocols that should be
147 /// disabled. Valid protocol names are sslv2, sslv3, tlsv1, tlsv1_1, tlsv1_2.
148 /// - dhParamsFile (string): Specifies a file containing Diffie-Hellman parameters.
149 /// If not specified or empty, the default parameters are used.
150 /// - ecdhCurve (string): Specifies the name of the curve to use for ECDH, based
151 /// on the curve names specified in RFC 4492. Defaults to "prime256v1".
152 /// - fips: Enable or disable OpenSSL FIPS mode. Only supported if the OpenSSL version
153 /// that this library is built against supports FIPS mode.
154{
155public:
156 typedef Poco::SharedPtr<PrivateKeyPassphraseHandler> PrivateKeyPassphraseHandlerPtr;
157 typedef Poco::SharedPtr<InvalidCertificateHandler> InvalidCertificateHandlerPtr;
158
159 Poco::BasicEvent<VerificationErrorArgs> ServerVerificationError;
160 /// Fired whenever a certificate verification error is detected by the server during a handshake.
161
162 Poco::BasicEvent<VerificationErrorArgs> ClientVerificationError;
163 /// Fired whenever a certificate verification error is detected by the client during a handshake.
164
165 Poco::BasicEvent<std::string> PrivateKeyPassphraseRequired;
166 /// Fired when a encrypted certificate is loaded. Not setting the password
167 /// in the event parameter will result in a failure to load the certificate.
168
169 static SSLManager& instance();
170 /// Returns the instance of the SSLManager singleton.
171
172 void initializeServer(PrivateKeyPassphraseHandlerPtr ptrPassphraseHandler, InvalidCertificateHandlerPtr ptrCertificateHandler, Context::Ptr ptrContext);
173 /// Initializes the server side of the SSLManager with a default passphrase handler, a default invalid certificate handler and a default context. If this method
174 /// is never called the SSLmanager will try to initialize its members from an application configuration.
175 ///
176 /// PtrPassphraseHandler and ptrCertificateHandler can be 0. However, in this case, event delegates
177 /// must be registered with the ServerVerificationError and PrivateKeyPassphraseRequired events.
178 ///
179 /// Note: Always create the handlers (or register the corresponding event delegates) before creating
180 /// the Context, as during creation of the Context the passphrase for the private key might be needed.
181 ///
182 /// Valid initialization code would be:
183 /// SharedPtr<PrivateKeyPassphraseHandler> pConsoleHandler = new KeyConsoleHandler;
184 /// SharedPtr<InvalidCertificateHandler> pInvalidCertHandler = new ConsoleCertificateHandler;
185 /// Context::Ptr pContext = new Context(Context::SERVER_USE, "any.pem", "any.pem", "rootcert.pem", Context::VERIFY_RELAXED, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
186 /// SSLManager::instance().initializeServer(pConsoleHandler, pInvalidCertHandler, pContext);
187
188 void initializeClient(PrivateKeyPassphraseHandlerPtr ptrPassphraseHandler, InvalidCertificateHandlerPtr ptrHandler, Context::Ptr ptrContext);
189 /// Initializes the client side of the SSLManager with a default passphrase handler, a default invalid certificate handler and a default context. If this method
190 /// is never called the SSLmanager will try to initialize its members from an application configuration.
191 ///
192 /// PtrPassphraseHandler and ptrCertificateHandler can be 0. However, in this case, event delegates
193 /// must be registered with the ClientVerificationError and PrivateKeyPassphraseRequired events.
194 ///
195 /// Note: Always create the handlers (or register the corresponding event delegates) before creating
196 /// the Context, as during creation of the Context the passphrase for the private key might be needed.
197 ///
198 /// Valid initialization code would be:
199 /// SharedPtr<PrivateKeyPassphraseHandler> pConsoleHandler = new KeyConsoleHandler;
200 /// SharedPtr<InvalidCertificateHandler> pInvalidCertHandler = new ConsoleCertificateHandler;
201 /// Context::Ptr pContext = new Context(Context::CLIENT_USE, "", "", "rootcert.pem", Context::VERIFY_RELAXED, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
202 /// SSLManager::instance().initializeClient(pConsoleHandler, pInvalidCertHandler, pContext);
203
204 Context::Ptr defaultServerContext();
205 /// Returns the default Context used by the server.
206 ///
207 /// Unless initializeServer() has been called, the first call to this method initializes the default Context
208 /// from the application configuration.
209
210 Context::Ptr defaultClientContext();
211 /// Returns the default Context used by the client.
212 ///
213 /// Unless initializeClient() has been called, the first call to this method initializes the default Context
214 /// from the application configuration.
215
216 PrivateKeyPassphraseHandlerPtr serverPassphraseHandler();
217 /// Returns the configured passphrase handler of the server. If none is set, the method will create a default one
218 /// from an application configuration.
219
220 InvalidCertificateHandlerPtr serverCertificateHandler();
221 /// Returns an initialized certificate handler (used by the server to verify client cert) which determines how invalid certificates are treated.
222 /// If none is set, it will try to auto-initialize one from an application configuration.
223
224 PrivateKeyPassphraseHandlerPtr clientPassphraseHandler();
225 /// Returns the configured passphrase handler of the client. If none is set, the method will create a default one
226 /// from an application configuration.
227
228 InvalidCertificateHandlerPtr clientCertificateHandler();
229 /// Returns an initialized certificate handler (used by the client to verify server cert) which determines how invalid certificates are treated.
230 /// If none is set, it will try to auto-initialize one from an application configuration.
231
232 PrivateKeyFactoryMgr& privateKeyFactoryMgr();
233 /// Returns the private key factory manager which stores the
234 /// factories for the different registered passphrase handlers for private keys.
235
236 CertificateHandlerFactoryMgr& certificateHandlerFactoryMgr();
237 /// Returns the CertificateHandlerFactoryMgr which stores the
238 /// factories for the different registered certificate handlers.
239
240 static bool isFIPSEnabled();
241 // Returns true if FIPS mode is enabled, false otherwise.
242
243 void shutdown();
244 /// Shuts down the SSLManager and releases the default Context
245 /// objects. After a call to shutdown(), the SSLManager can no
246 /// longer be used.
247 ///
248 /// Normally, it's not necessary to call this method directly, as this
249 /// will be called either by uninitializeSSL(), or when
250 /// the SSLManager instance is destroyed.
251
252 static const std::string CFG_SERVER_PREFIX;
253 static const std::string CFG_CLIENT_PREFIX;
254
255protected:
256 static int verifyClientCallback(int ok, X509_STORE_CTX* pStore);
257 /// The return value of this method defines how errors in
258 /// verification are handled. Return 0 to terminate the handshake,
259 /// or 1 to continue despite the error.
260
261 static int verifyServerCallback(int ok, X509_STORE_CTX* pStore);
262 /// The return value of this method defines how errors in
263 /// verification are handled. Return 0 to terminate the handshake,
264 /// or 1 to continue despite the error.
265
266 static int privateKeyPassphraseCallback(char* pBuf, int size, int flag, void* userData);
267 /// Method is invoked by OpenSSL to retrieve a passwd for an encrypted certificate.
268 /// The request is delegated to the PrivatekeyPassword event. This method returns the
269 /// length of the password.
270
271 static Poco::Util::AbstractConfiguration& appConfig();
272 /// Returns the application configuration.
273 ///
274 /// Throws a InvalidStateException if not application instance
275 /// is available.
276
277private:
278 SSLManager();
279 /// Creates the SSLManager.
280
281 ~SSLManager();
282 /// Destroys the SSLManager.
283
284 void initDefaultContext(bool server);
285 /// Inits the default context, the first time it is accessed.
286
287 void initEvents(bool server);
288 /// Registers delegates at the events according to the configuration.
289
290 void initPassphraseHandler(bool server);
291 /// Inits the passphrase handler.
292
293 void initCertificateHandler(bool server);
294 /// Inits the certificate handler.
295
296 static int verifyCallback(bool server, int ok, X509_STORE_CTX* pStore);
297 /// The return value of this method defines how errors in
298 /// verification are handled. Return 0 to terminate the handshake,
299 /// or 1 to continue despite the error.
300
301 PrivateKeyFactoryMgr _factoryMgr;
302 CertificateHandlerFactoryMgr _certHandlerFactoryMgr;
303 Context::Ptr _ptrDefaultServerContext;
304 PrivateKeyPassphraseHandlerPtr _ptrServerPassphraseHandler;
305 InvalidCertificateHandlerPtr _ptrServerCertificateHandler;
306 Context::Ptr _ptrDefaultClientContext;
307 PrivateKeyPassphraseHandlerPtr _ptrClientPassphraseHandler;
308 InvalidCertificateHandlerPtr _ptrClientCertificateHandler;
309 Poco::FastMutex _mutex;
310
311 static const std::string CFG_PRIV_KEY_FILE;
312 static const std::string CFG_CERTIFICATE_FILE;
313 static const std::string CFG_CA_LOCATION;
314 static const std::string CFG_VER_MODE;
315 static const Context::VerificationMode VAL_VER_MODE;
316 static const std::string CFG_VER_DEPTH;
317 static const int VAL_VER_DEPTH;
318 static const std::string CFG_ENABLE_DEFAULT_CA;
319 static const bool VAL_ENABLE_DEFAULT_CA;
320 static const std::string CFG_CIPHER_LIST;
321 static const std::string CFG_CYPHER_LIST; // for backwards compatibility
322 static const std::string VAL_CIPHER_LIST;
323 static const std::string CFG_PREFER_SERVER_CIPHERS;
324 static const std::string CFG_DELEGATE_HANDLER;
325 static const std::string VAL_DELEGATE_HANDLER;
326 static const std::string CFG_CERTIFICATE_HANDLER;
327 static const std::string VAL_CERTIFICATE_HANDLER;
328 static const std::string CFG_CACHE_SESSIONS;
329 static const std::string CFG_SESSION_ID_CONTEXT;
330 static const std::string CFG_SESSION_CACHE_SIZE;
331 static const std::string CFG_SESSION_TIMEOUT;
332 static const std::string CFG_EXTENDED_VERIFICATION;
333 static const std::string CFG_REQUIRE_TLSV1;
334 static const std::string CFG_REQUIRE_TLSV1_1;
335 static const std::string CFG_REQUIRE_TLSV1_2;
336 static const std::string CFG_DISABLE_PROTOCOLS;
337 static const std::string CFG_DH_PARAMS_FILE;
338 static const std::string CFG_ECDH_CURVE;
339
340#ifdef OPENSSL_FIPS
341 static const std::string CFG_FIPS_MODE;
342 static const bool VAL_FIPS_MODE;
343#endif
344
345 friend class Poco::SingletonHolder<SSLManager>;
346 friend class Context;
347};
348
349
350//
351// inlines
352//
353inline PrivateKeyFactoryMgr& SSLManager::privateKeyFactoryMgr()
354{
355 return _factoryMgr;
356}
357
358
359inline CertificateHandlerFactoryMgr& SSLManager::certificateHandlerFactoryMgr()
360{
361 return _certHandlerFactoryMgr;
362}
363
364
365inline bool SSLManager::isFIPSEnabled()
366{
367#ifdef OPENSSL_FIPS
368 return FIPS_mode() ? true : false;
369#else
370 return false;
371#endif
372}
373
374
375inline int SSLManager::verifyServerCallback(int ok, X509_STORE_CTX* pStore)
376{
377 return SSLManager::verifyCallback(true, ok, pStore);
378}
379
380
381inline int SSLManager::verifyClientCallback(int ok, X509_STORE_CTX* pStore)
382{
383 return SSLManager::verifyCallback(false, ok, pStore);
384}
385
386
387} } // namespace Poco::Net
388
389
390#endif // NetSSL_SSLManager_INCLUDED
391