SSLManager.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. //
  2. // SSLManager.h
  3. //
  4. // $Id: //poco/1.4/NetSSL_OpenSSL/include/Poco/Net/SSLManager.h#4 $
  5. //
  6. // Library: NetSSL_OpenSSL
  7. // Package: SSLCore
  8. // Module: SSLManager
  9. //
  10. // Definition of the SSLManager class.
  11. //
  12. // Copyright (c) 2006-2010, Applied Informatics Software Engineering GmbH.
  13. // and Contributors.
  14. //
  15. // Permission is hereby granted, free of charge, to any person or organization
  16. // obtaining a copy of the software and accompanying documentation covered by
  17. // this license (the "Software") to use, reproduce, display, distribute,
  18. // execute, and transmit the Software, and to prepare derivative works of the
  19. // Software, and to permit third-parties to whom the Software is furnished to
  20. // do so, all subject to the following:
  21. //
  22. // The copyright notices in the Software and this entire statement, including
  23. // the above license grant, this restriction and the following disclaimer,
  24. // must be included in all copies of the Software, in whole or in part, and
  25. // all derivative works of the Software, unless such copies or derivative
  26. // works are solely in the form of machine-executable object code generated by
  27. // a source language processor.
  28. //
  29. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  30. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  31. // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
  32. // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
  33. // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
  34. // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  35. // DEALINGS IN THE SOFTWARE.
  36. //
  37. #ifndef NetSSL_SSLManager_INCLUDED
  38. #define NetSSL_SSLManager_INCLUDED
  39. #include "Poco/Net/NetSSL.h"
  40. #include "Poco/Net/VerificationErrorArgs.h"
  41. #include "Poco/Net/Context.h"
  42. #include "Poco/Net/PrivateKeyFactoryMgr.h"
  43. #include "Poco/Net/CertificateHandlerFactoryMgr.h"
  44. #include "Poco/Net/InvalidCertificateHandler.h"
  45. #include "Poco/Util/AbstractConfiguration.h"
  46. #include "Poco/BasicEvent.h"
  47. #include "Poco/SharedPtr.h"
  48. #include "Poco/Mutex.h"
  49. #include <openssl/ssl.h>
  50. #ifdef OPENSSL_FIPS
  51. #include <openssl/fips.h>
  52. #endif
  53. namespace Poco {
  54. namespace Net {
  55. class Context;
  56. class NetSSL_API SSLManager
  57. /// SSLManager is a singleton for holding the default server/client
  58. /// Context and handling callbacks for certificate verification errors
  59. /// and private key passphrases.
  60. ///
  61. /// Proper initialization of SSLManager is critical.
  62. ///
  63. /// SSLManager can be initialized manually, by calling initializeServer()
  64. /// and/or initializeClient(), or intialization can be automatic. In the latter
  65. /// case, a Poco::Util::Application instance must be available and the required
  66. /// configuration properties must be set (see below).
  67. ///
  68. /// Note that manual intialization must happen very early in the application,
  69. /// before defaultClientContext() or defaultServerContext() are called.
  70. ///
  71. /// If defaultClientContext() and defaultServerContext() are never called
  72. /// in an application, initialization of SSLManager can be omitted.
  73. /// However, in this case, delegates for the ServerVerificationError,
  74. /// ClientVerificationError and PrivateKeyPassphraseRequired events
  75. /// must be registered.
  76. ///
  77. /// An exemplary documentation which sets either the server or client default context and creates
  78. /// a PrivateKeyPassphraseHandler that reads the password from the XML file looks like this:
  79. ///
  80. /// <AppConfig>
  81. /// <openSSL>
  82. /// <server|client>
  83. /// <privateKeyFile>mycert.key</privateKeyFile>
  84. /// <certificateFile>mycert.crt</certificateFile>
  85. /// <caConfig>rootcert.pem</caConfig>
  86. /// <verificationMode>none|relaxed|strict|once</verificationMode>
  87. /// <verificationDepth>1..9</verificationDepth>
  88. /// <loadDefaultCAFile>true|false</loadDefaultCAFile>
  89. /// <cipherList>ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH</cipherList>
  90. /// <privateKeyPassphraseHandler>
  91. /// <name>KeyFileHandler</name>
  92. /// <options>
  93. /// <password>test</password>
  94. /// </options>
  95. /// </privateKeyPassphraseHandler>
  96. /// <invalidCertificateHandler>
  97. /// <name>ConsoleCertificateHandler</name>
  98. /// </invalidCertificateHandler>
  99. /// <cacheSessions>true|false</cacheSessions>
  100. /// <sessionIdContext>someString</sessionIdContext> <!-- server only -->
  101. /// <sessionCacheSize>0..n</sessionCacheSize> <!-- server only -->
  102. /// <sessionTimeout>0..n</sessionTimeout> <!-- server only -->
  103. /// <extendedVerification>true|false</extendedVerification>
  104. /// <requireTLSv1>true|false</requireTLSv1>
  105. /// </server|client>
  106. /// <fips>false</fips>
  107. /// </openSSL>
  108. /// </AppConfig>
  109. ///
  110. /// Following is a list of supported configuration properties. Property names must always
  111. /// be prefixed with openSSL.server or openSSL.client. Some properties are only supported
  112. /// for servers.
  113. ///
  114. /// - privateKeyFile (string): The path to the file containing the private key for the certificate
  115. /// in PEM format (or containing both the private key and the certificate).
  116. /// - certificateFile (string): The Path to the file containing the server's or client's certificate
  117. /// in PEM format. Can be omitted if the the file given in privateKeyFile contains the certificate as well.
  118. /// - caConfig (string): The path to the file or directory containing the trusted root certificates.
  119. /// - verificationMode (string): Specifies whether and how peer certificates are validated (see
  120. /// the Context class for details). Valid values are none, relaxed, strict, once.
  121. /// - verificationDepth (integer, 1-9): Sets the upper limit for verification chain sizes. Verification
  122. /// will fail if a certificate chain larger than this is encountered.
  123. /// - loadDefaultCAFile (boolean): Specifies wheter the builtin CA certificates from OpenSSL are used.
  124. /// - cipherList (string): Specifies the supported ciphers in OpenSSL notation
  125. /// (e.g. "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH").
  126. /// - privateKeyPassphraseHandler.name (string): The name of the class (subclass of PrivateKeyPassphraseHandler)
  127. /// used for obtaining the passphrase for accessing the private key.
  128. /// - privateKeyPassphraseHandler.options.password (string): The password to be used by KeyFileHandler.
  129. /// - invalidCertificateHandler.name: The name of the class (subclass of CertificateHandler)
  130. /// used for confirming invalid certificates.
  131. /// - cacheSessions (boolean): Enables or disables session caching.
  132. /// - sessionIdContext (string): contains the application's unique session ID context, which becomes
  133. /// part of each session identifier generated by the server. Can be an arbitrary sequence
  134. /// of bytes with a maximum length of SSL_MAX_SSL_SESSION_ID_LENGTH. Should be specified
  135. /// for a server to enable session caching. Should be specified even if session caching
  136. /// is disabled to avoid problems with clients that request session caching (e.g. Firefox 3.6).
  137. /// If not specified, defaults to ${application.name}.
  138. /// - sessionCacheSize (integer): Sets the maximum size of the server session cache, in number of
  139. /// sessions. The default size (according to OpenSSL documentation) is 1024*20, which may be too
  140. /// large for many applications, especially on embedded platforms with limited memory.
  141. /// Specifying a size of 0 will set an unlimited cache size.
  142. /// - sessionTimeout (integer): Sets the timeout (in seconds) of cached sessions on the server.
  143. /// - extendedVerification (boolean): Enable or disable the automatic post-connection
  144. /// extended certificate verification.
  145. /// - requireTLSv1 (boolean): Require a TLSv1 connection.
  146. /// - fips: Enable or disable OpenSSL FIPS mode. Only supported if the OpenSSL version
  147. /// that this library is built against supports FIPS mode.
  148. {
  149. public:
  150. typedef Poco::SharedPtr<PrivateKeyPassphraseHandler> PrivateKeyPassphraseHandlerPtr;
  151. typedef Poco::SharedPtr<InvalidCertificateHandler> InvalidCertificateHandlerPtr;
  152. Poco::BasicEvent<VerificationErrorArgs> ServerVerificationError;
  153. /// Fired whenever a certificate verification error is detected by the server during a handshake.
  154. Poco::BasicEvent<VerificationErrorArgs> ClientVerificationError;
  155. /// Fired whenever a certificate verification error is detected by the client during a handshake.
  156. Poco::BasicEvent<std::string> PrivateKeyPassphraseRequired;
  157. /// Fired when a encrypted certificate is loaded. Not setting the password
  158. /// in the event parameter will result in a failure to load the certificate.
  159. static SSLManager& instance();
  160. /// Returns the instance of the SSLManager singleton.
  161. void initializeServer(PrivateKeyPassphraseHandlerPtr ptrPassphraseHandler, InvalidCertificateHandlerPtr ptrCertificateHandler, Context::Ptr ptrContext);
  162. /// Initializes the server side of the SSLManager with a default passphrase handler, a default invalid certificate handler and a default context. If this method
  163. /// is never called the SSLmanager will try to initialize its members from an application configuration.
  164. ///
  165. /// PtrPassphraseHandler and ptrCertificateHandler can be 0. However, in this case, event delegates
  166. /// must be registered with the ServerVerificationError and PrivateKeyPassphraseRequired events.
  167. ///
  168. /// Note: Always create the handlers (or register the corresponding event delegates) before creating
  169. /// the Context, as during creation of the Context the passphrase for the private key might be needed.
  170. ///
  171. /// Valid initialization code would be:
  172. /// SharedPtr<PrivateKeyPassphraseHandler> pConsoleHandler = new KeyConsoleHandler;
  173. /// SharedPtr<InvalidCertificateHandler> pInvalidCertHandler = new ConsoleCertificateHandler;
  174. /// 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");
  175. /// SSLManager::instance().initializeServer(pConsoleHandler, pInvalidCertHandler, pContext);
  176. void initializeClient(PrivateKeyPassphraseHandlerPtr ptrPassphraseHandler, InvalidCertificateHandlerPtr ptrHandler, Context::Ptr ptrContext);
  177. /// Initializes the client 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 ClientVerificationError 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::CLIENT_USE, "", "", "rootcert.pem", Context::VERIFY_RELAXED, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
  190. /// SSLManager::instance().initializeClient(pConsoleHandler, pInvalidCertHandler, pContext);
  191. Context::Ptr defaultServerContext();
  192. /// Returns the default Context used by the server.
  193. ///
  194. /// Unless initializeServer() has been called, the first call to this method initializes the default Context
  195. /// from the application configuration.
  196. Context::Ptr defaultClientContext();
  197. /// Returns the default Context used by the client.
  198. ///
  199. /// Unless initializeClient() has been called, the first call to this method initializes the default Context
  200. /// from the application configuration.
  201. PrivateKeyPassphraseHandlerPtr serverPassphraseHandler();
  202. /// Returns the configured passphrase handler of the server. If none is set, the method will create a default one
  203. /// from an application configuration.
  204. InvalidCertificateHandlerPtr serverCertificateHandler();
  205. /// Returns an initialized certificate handler (used by the server to verify client cert) which determines how invalid certificates are treated.
  206. /// If none is set, it will try to auto-initialize one from an application configuration.
  207. PrivateKeyPassphraseHandlerPtr clientPassphraseHandler();
  208. /// Returns the configured passphrase handler of the client. If none is set, the method will create a default one
  209. /// from an application configuration.
  210. InvalidCertificateHandlerPtr clientCertificateHandler();
  211. /// Returns an initialized certificate handler (used by the client to verify server cert) which determines how invalid certificates are treated.
  212. /// If none is set, it will try to auto-initialize one from an application configuration.
  213. PrivateKeyFactoryMgr& privateKeyFactoryMgr();
  214. /// Returns the private key factory manager which stores the
  215. /// factories for the different registered passphrase handlers for private keys.
  216. CertificateHandlerFactoryMgr& certificateHandlerFactoryMgr();
  217. /// Returns the CertificateHandlerFactoryMgr which stores the
  218. /// factories for the different registered certificate handlers.
  219. static bool isFIPSEnabled();
  220. // Returns true if FIPS mode is enabled, false otherwise.
  221. void shutdown();
  222. /// Shuts down the SSLManager and releases the default Context
  223. /// objects. After a call to shutdown(), the SSLManager can no
  224. /// longer be used.
  225. ///
  226. /// Normally, it's not necessary to call this method directly, as this
  227. /// will be called either by uninitializeSSL(), or when
  228. /// the SSLManager instance is destroyed.
  229. static const std::string CFG_SERVER_PREFIX;
  230. static const std::string CFG_CLIENT_PREFIX;
  231. protected:
  232. static int verifyClientCallback(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 verifyServerCallback(int ok, X509_STORE_CTX* pStore);
  237. /// The return value of this method defines how errors in
  238. /// verification are handled. Return 0 to terminate the handshake,
  239. /// or 1 to continue despite the error.
  240. static int privateKeyPassphraseCallback(char* pBuf, int size, int flag, void* userData);
  241. /// Method is invoked by OpenSSL to retrieve a passwd for an encrypted certificate.
  242. /// The request is delegated to the PrivatekeyPassword event. This method returns the
  243. /// length of the password.
  244. static Poco::Util::AbstractConfiguration& appConfig();
  245. /// Returns the application configuration.
  246. ///
  247. /// Throws a
  248. private:
  249. SSLManager();
  250. /// Creates the SSLManager.
  251. ~SSLManager();
  252. /// Destroys the SSLManager.
  253. void initDefaultContext(bool server);
  254. /// Inits the default context, the first time it is accessed.
  255. void initEvents(bool server);
  256. /// Registers delegates at the events according to the configuration.
  257. void initPassphraseHandler(bool server);
  258. /// Inits the passphrase handler.
  259. void initCertificateHandler(bool server);
  260. /// Inits the certificate handler.
  261. static int verifyCallback(bool server, 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. PrivateKeyFactoryMgr _factoryMgr;
  266. CertificateHandlerFactoryMgr _certHandlerFactoryMgr;
  267. Context::Ptr _ptrDefaultServerContext;
  268. PrivateKeyPassphraseHandlerPtr _ptrServerPassphraseHandler;
  269. InvalidCertificateHandlerPtr _ptrServerCertificateHandler;
  270. Context::Ptr _ptrDefaultClientContext;
  271. PrivateKeyPassphraseHandlerPtr _ptrClientPassphraseHandler;
  272. InvalidCertificateHandlerPtr _ptrClientCertificateHandler;
  273. Poco::FastMutex _mutex;
  274. static const std::string CFG_PRIV_KEY_FILE;
  275. static const std::string CFG_CERTIFICATE_FILE;
  276. static const std::string CFG_CA_LOCATION;
  277. static const std::string CFG_VER_MODE;
  278. static const Context::VerificationMode VAL_VER_MODE;
  279. static const std::string CFG_VER_DEPTH;
  280. static const int VAL_VER_DEPTH;
  281. static const std::string CFG_ENABLE_DEFAULT_CA;
  282. static const bool VAL_ENABLE_DEFAULT_CA;
  283. static const std::string CFG_CIPHER_LIST;
  284. static const std::string CFG_CYPHER_LIST; // for backwards compatibility
  285. static const std::string VAL_CIPHER_LIST;
  286. static const std::string CFG_DELEGATE_HANDLER;
  287. static const std::string VAL_DELEGATE_HANDLER;
  288. static const std::string CFG_CERTIFICATE_HANDLER;
  289. static const std::string VAL_CERTIFICATE_HANDLER;
  290. static const std::string CFG_CACHE_SESSIONS;
  291. static const std::string CFG_SESSION_ID_CONTEXT;
  292. static const std::string CFG_SESSION_CACHE_SIZE;
  293. static const std::string CFG_SESSION_TIMEOUT;
  294. static const std::string CFG_EXTENDED_VERIFICATION;
  295. static const std::string CFG_REQUIRE_TLSV1;
  296. #ifdef OPENSSL_FIPS
  297. static const std::string CFG_FIPS_MODE;
  298. static const bool VAL_FIPS_MODE;
  299. #endif
  300. friend class Poco::SingletonHolder<SSLManager>;
  301. friend class Context;
  302. };
  303. //
  304. // inlines
  305. //
  306. inline PrivateKeyFactoryMgr& SSLManager::privateKeyFactoryMgr()
  307. {
  308. return _factoryMgr;
  309. }
  310. inline CertificateHandlerFactoryMgr& SSLManager::certificateHandlerFactoryMgr()
  311. {
  312. return _certHandlerFactoryMgr;
  313. }
  314. inline bool SSLManager::isFIPSEnabled()
  315. {
  316. #ifdef OPENSSL_FIPS
  317. return FIPS_mode() ? true : false;
  318. #else
  319. return false;
  320. #endif
  321. }
  322. inline int SSLManager::verifyServerCallback(int ok, X509_STORE_CTX* pStore)
  323. {
  324. return SSLManager::verifyCallback(true, ok, pStore);
  325. }
  326. inline int SSLManager::verifyClientCallback(int ok, X509_STORE_CTX* pStore)
  327. {
  328. return SSLManager::verifyCallback(false, ok, pStore);
  329. }
  330. } } // namespace Poco::Net
  331. #endif // NetSSL_SSLManager_INCLUDED