SSLManager.h 18 KB

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