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