You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

475 lines
16 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright (c) 2015, Peter Thorson. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions are met:
  6. * * Redistributions of source code must retain the above copyright
  7. * notice, this list of conditions and the following disclaimer.
  8. * * Redistributions in binary form must reproduce the above copyright
  9. * notice, this list of conditions and the following disclaimer in the
  10. * documentation and/or other materials provided with the distribution.
  11. * * Neither the name of the WebSocket++ Project nor the
  12. * names of its contributors may be used to endorse or promote products
  13. * derived from this software without specific prior written permission.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. * ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY
  19. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  20. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  21. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  22. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  24. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. *
  26. */
  27. #ifndef WEBSOCKETPP_TRANSPORT_SECURITY_TLS_HPP
  28. #define WEBSOCKETPP_TRANSPORT_SECURITY_TLS_HPP
  29. #include <websocketpp/transport/asio/security/base.hpp>
  30. #include <websocketpp/uri.hpp>
  31. #include <websocketpp/common/asio_ssl.hpp>
  32. #include <websocketpp/common/asio.hpp>
  33. #include <websocketpp/common/connection_hdl.hpp>
  34. #include <websocketpp/common/functional.hpp>
  35. #include <websocketpp/common/memory.hpp>
  36. #include <sstream>
  37. #include <string>
  38. namespace websocketpp {
  39. namespace transport {
  40. namespace asio {
  41. /// A socket policy for the asio transport that implements a TLS encrypted
  42. /// socket by wrapping with an asio::ssl::stream
  43. namespace tls_socket {
  44. /// The signature of the socket_init_handler for this socket policy
  45. typedef lib::function<void(connection_hdl,lib::asio::ssl::stream<
  46. lib::asio::ip::tcp::socket>&)> socket_init_handler;
  47. /// The signature of the tls_init_handler for this socket policy
  48. typedef lib::function<lib::shared_ptr<lib::asio::ssl::context>(connection_hdl)>
  49. tls_init_handler;
  50. /// TLS enabled Asio connection socket component
  51. /**
  52. * transport::asio::tls_socket::connection implements a secure connection socket
  53. * component that uses Asio's ssl::stream to wrap an ip::tcp::socket.
  54. */
  55. class connection : public lib::enable_shared_from_this<connection> {
  56. public:
  57. /// Type of this connection socket component
  58. typedef connection type;
  59. /// Type of a shared pointer to this connection socket component
  60. typedef lib::shared_ptr<type> ptr;
  61. /// Type of the ASIO socket being used
  62. typedef lib::asio::ssl::stream<lib::asio::ip::tcp::socket> socket_type;
  63. /// Type of a shared pointer to the ASIO socket being used
  64. typedef lib::shared_ptr<socket_type> socket_ptr;
  65. /// Type of a pointer to the ASIO io_service being used
  66. typedef lib::asio::io_service * io_service_ptr;
  67. /// Type of a pointer to the ASIO io_service strand being used
  68. typedef lib::shared_ptr<lib::asio::io_service::strand> strand_ptr;
  69. /// Type of a shared pointer to the ASIO TLS context being used
  70. typedef lib::shared_ptr<lib::asio::ssl::context> context_ptr;
  71. explicit connection() {
  72. //std::cout << "transport::asio::tls_socket::connection constructor"
  73. // << std::endl;
  74. }
  75. /// Get a shared pointer to this component
  76. ptr get_shared() {
  77. return shared_from_this();
  78. }
  79. /// Check whether or not this connection is secure
  80. /**
  81. * @return Whether or not this connection is secure
  82. */
  83. bool is_secure() const {
  84. return true;
  85. }
  86. /// Retrieve a pointer to the underlying socket
  87. /**
  88. * This is used internally. It can also be used to set socket options, etc
  89. */
  90. socket_type::lowest_layer_type & get_raw_socket() {
  91. return m_socket->lowest_layer();
  92. }
  93. /// Retrieve a pointer to the layer below the ssl stream
  94. /**
  95. * This is used internally.
  96. */
  97. socket_type::next_layer_type & get_next_layer() {
  98. return m_socket->next_layer();
  99. }
  100. /// Retrieve a pointer to the wrapped socket
  101. /**
  102. * This is used internally.
  103. */
  104. socket_type & get_socket() {
  105. return *m_socket;
  106. }
  107. /// Set the socket initialization handler
  108. /**
  109. * The socket initialization handler is called after the socket object is
  110. * created but before it is used. This gives the application a chance to
  111. * set any ASIO socket options it needs.
  112. *
  113. * @param h The new socket_init_handler
  114. */
  115. void set_socket_init_handler(socket_init_handler h) {
  116. m_socket_init_handler = h;
  117. }
  118. /// Set TLS init handler
  119. /**
  120. * The tls init handler is called when needed to request a TLS context for
  121. * the library to use. A TLS init handler must be set and it must return a
  122. * valid TLS context in order for this endpoint to be able to initialize
  123. * TLS connections
  124. *
  125. * @param h The new tls_init_handler
  126. */
  127. void set_tls_init_handler(tls_init_handler h) {
  128. m_tls_init_handler = h;
  129. }
  130. /// Get the remote endpoint address
  131. /**
  132. * The iostream transport has no information about the ultimate remote
  133. * endpoint. It will return the string "iostream transport". To indicate
  134. * this.
  135. *
  136. * TODO: allow user settable remote endpoint addresses if this seems useful
  137. *
  138. * @return A string identifying the address of the remote endpoint
  139. */
  140. std::string get_remote_endpoint(lib::error_code & ec) const {
  141. std::stringstream s;
  142. lib::asio::error_code aec;
  143. lib::asio::ip::tcp::endpoint ep = m_socket->lowest_layer().remote_endpoint(aec);
  144. if (aec) {
  145. ec = error::make_error_code(error::pass_through);
  146. s << "Error getting remote endpoint: " << aec
  147. << " (" << aec.message() << ")";
  148. return s.str();
  149. } else {
  150. ec = lib::error_code();
  151. s << ep;
  152. return s.str();
  153. }
  154. }
  155. protected:
  156. /// Perform one time initializations
  157. /**
  158. * init_asio is called once immediately after construction to initialize
  159. * Asio components to the io_service
  160. *
  161. * @param service A pointer to the endpoint's io_service
  162. * @param strand A pointer to the connection's strand
  163. * @param is_server Whether or not the endpoint is a server or not.
  164. */
  165. lib::error_code init_asio (io_service_ptr service, strand_ptr strand,
  166. bool is_server)
  167. {
  168. if (!m_tls_init_handler) {
  169. return socket::make_error_code(socket::error::missing_tls_init_handler);
  170. }
  171. m_context = m_tls_init_handler(m_hdl);
  172. if (!m_context) {
  173. return socket::make_error_code(socket::error::invalid_tls_context);
  174. }
  175. m_socket = lib::make_shared<socket_type>(
  176. _WEBSOCKETPP_REF(*service),lib::ref(*m_context));
  177. if (m_socket_init_handler) {
  178. m_socket_init_handler(m_hdl, get_socket());
  179. }
  180. m_io_service = service;
  181. m_strand = strand;
  182. m_is_server = is_server;
  183. return lib::error_code();
  184. }
  185. /// Set hostname hook
  186. /**
  187. * Called by the transport as a connection is being established to provide
  188. * the hostname being connected to to the security/socket layer.
  189. *
  190. * This socket policy uses the hostname to set the appropriate TLS SNI
  191. * header.
  192. *
  193. * @since 0.6.0
  194. *
  195. * @param u The uri to set
  196. */
  197. void set_uri(uri_ptr u) {
  198. m_uri = u;
  199. }
  200. /// Pre-initialize security policy
  201. /**
  202. * Called by the transport after a new connection is created to initialize
  203. * the socket component of the connection. This method is not allowed to
  204. * write any bytes to the wire. This initialization happens before any
  205. * proxies or other intermediate wrappers are negotiated.
  206. *
  207. * @param callback Handler to call back with completion information
  208. */
  209. void pre_init(init_handler callback) {
  210. // TODO: is this the best way to check whether this function is
  211. // available in the version of OpenSSL being used?
  212. // TODO: consider case where host is an IP address
  213. #if OPENSSL_VERSION_NUMBER >= 0x90812f
  214. if (!m_is_server) {
  215. // For clients on systems with a suitable OpenSSL version, set the
  216. // TLS SNI hostname header so connecting to TLS servers using SNI
  217. // will work.
  218. long res = SSL_set_tlsext_host_name(
  219. get_socket().native_handle(), m_uri->get_host().c_str());
  220. if (!(1 == res)) {
  221. callback(socket::make_error_code(socket::error::tls_failed_sni_hostname));
  222. }
  223. }
  224. #endif
  225. callback(lib::error_code());
  226. }
  227. /// Post-initialize security policy
  228. /**
  229. * Called by the transport after all intermediate proxies have been
  230. * negotiated. This gives the security policy the chance to talk with the
  231. * real remote endpoint for a bit before the websocket handshake.
  232. *
  233. * @param callback Handler to call back with completion information
  234. */
  235. void post_init(init_handler callback) {
  236. m_ec = socket::make_error_code(socket::error::tls_handshake_timeout);
  237. // TLS handshake
  238. if (m_strand) {
  239. m_socket->async_handshake(
  240. get_handshake_type(),
  241. m_strand->wrap(lib::bind(
  242. &type::handle_init, get_shared(),
  243. callback,
  244. lib::placeholders::_1
  245. ))
  246. );
  247. } else {
  248. m_socket->async_handshake(
  249. get_handshake_type(),
  250. lib::bind(
  251. &type::handle_init, get_shared(),
  252. callback,
  253. lib::placeholders::_1
  254. )
  255. );
  256. }
  257. }
  258. /// Sets the connection handle
  259. /**
  260. * The connection handle is passed to any handlers to identify the
  261. * connection
  262. *
  263. * @param hdl The new handle
  264. */
  265. void set_handle(connection_hdl hdl) {
  266. m_hdl = hdl;
  267. }
  268. void handle_init(init_handler callback,lib::asio::error_code const & ec) {
  269. if (ec) {
  270. m_ec = socket::make_error_code(socket::error::tls_handshake_failed);
  271. } else {
  272. m_ec = lib::error_code();
  273. }
  274. callback(m_ec);
  275. }
  276. lib::error_code get_ec() const {
  277. return m_ec;
  278. }
  279. /// Cancel all async operations on this socket
  280. /**
  281. * Attempts to cancel all async operations on this socket and reports any
  282. * failures.
  283. *
  284. * NOTE: Windows XP and earlier do not support socket cancellation.
  285. *
  286. * @return The error that occurred, if any.
  287. */
  288. lib::asio::error_code cancel_socket() {
  289. lib::asio::error_code ec;
  290. get_raw_socket().cancel(ec);
  291. return ec;
  292. }
  293. void async_shutdown(socket::shutdown_handler callback) {
  294. if (m_strand) {
  295. m_socket->async_shutdown(m_strand->wrap(callback));
  296. } else {
  297. m_socket->async_shutdown(callback);
  298. }
  299. }
  300. public:
  301. /// Translate any security policy specific information about an error code
  302. /**
  303. * Translate_ec takes an Asio error code and attempts to convert its value
  304. * to an appropriate websocketpp error code. In the case that the Asio and
  305. * Websocketpp error types are the same (such as using boost::asio and
  306. * boost::system_error or using standalone asio and std::system_error the
  307. * code will be passed through natively.
  308. *
  309. * In the case of a mismatch (boost::asio with std::system_error) a
  310. * translated code will be returned. Any error that is determined to be
  311. * related to TLS but does not have a more specific websocketpp error code
  312. * is returned under the catch all error `tls_error`. Non-TLS related errors
  313. * are returned as the transport generic error `pass_through`
  314. *
  315. * @since 0.3.0
  316. *
  317. * @param ec The error code to translate_ec
  318. * @return The translated error code
  319. */
  320. template <typename ErrorCodeType>
  321. static
  322. lib::error_code translate_ec(ErrorCodeType ec) {
  323. if (ec.category() == lib::asio::error::get_ssl_category()) {
  324. // We know it is a TLS related error, but otherwise don't know more.
  325. // Pass through as TLS generic.
  326. return make_error_code(transport::error::tls_error);
  327. } else {
  328. // We don't know any more information about this error so pass
  329. // through
  330. return make_error_code(transport::error::pass_through);
  331. }
  332. }
  333. static
  334. /// Overload of translate_ec to catch cases where lib::error_code is the
  335. /// same type as lib::asio::error_code
  336. lib::error_code translate_ec(lib::error_code ec) {
  337. return ec;
  338. }
  339. private:
  340. socket_type::handshake_type get_handshake_type() {
  341. if (m_is_server) {
  342. return lib::asio::ssl::stream_base::server;
  343. } else {
  344. return lib::asio::ssl::stream_base::client;
  345. }
  346. }
  347. io_service_ptr m_io_service;
  348. strand_ptr m_strand;
  349. context_ptr m_context;
  350. socket_ptr m_socket;
  351. uri_ptr m_uri;
  352. bool m_is_server;
  353. lib::error_code m_ec;
  354. connection_hdl m_hdl;
  355. socket_init_handler m_socket_init_handler;
  356. tls_init_handler m_tls_init_handler;
  357. };
  358. /// TLS enabled Asio endpoint socket component
  359. /**
  360. * transport::asio::tls_socket::endpoint implements a secure endpoint socket
  361. * component that uses Asio's ssl::stream to wrap an ip::tcp::socket.
  362. */
  363. class endpoint {
  364. public:
  365. /// The type of this endpoint socket component
  366. typedef endpoint type;
  367. /// The type of the corresponding connection socket component
  368. typedef connection socket_con_type;
  369. /// The type of a shared pointer to the corresponding connection socket
  370. /// component.
  371. typedef socket_con_type::ptr socket_con_ptr;
  372. explicit endpoint() {}
  373. /// Checks whether the endpoint creates secure connections
  374. /**
  375. * @return Whether or not the endpoint creates secure connections
  376. */
  377. bool is_secure() const {
  378. return true;
  379. }
  380. /// Set socket init handler
  381. /**
  382. * The socket init handler is called after a connection's socket is created
  383. * but before it is used. This gives the end application an opportunity to
  384. * set asio socket specific parameters.
  385. *
  386. * @param h The new socket_init_handler
  387. */
  388. void set_socket_init_handler(socket_init_handler h) {
  389. m_socket_init_handler = h;
  390. }
  391. /// Set TLS init handler
  392. /**
  393. * The tls init handler is called when needed to request a TLS context for
  394. * the library to use. A TLS init handler must be set and it must return a
  395. * valid TLS context in order for this endpoint to be able to initialize
  396. * TLS connections
  397. *
  398. * @param h The new tls_init_handler
  399. */
  400. void set_tls_init_handler(tls_init_handler h) {
  401. m_tls_init_handler = h;
  402. }
  403. protected:
  404. /// Initialize a connection
  405. /**
  406. * Called by the transport after a new connection is created to initialize
  407. * the socket component of the connection.
  408. *
  409. * @param scon Pointer to the socket component of the connection
  410. *
  411. * @return Error code (empty on success)
  412. */
  413. lib::error_code init(socket_con_ptr scon) {
  414. scon->set_socket_init_handler(m_socket_init_handler);
  415. scon->set_tls_init_handler(m_tls_init_handler);
  416. return lib::error_code();
  417. }
  418. private:
  419. socket_init_handler m_socket_init_handler;
  420. tls_init_handler m_tls_init_handler;
  421. };
  422. } // namespace tls_socket
  423. } // namespace asio
  424. } // namespace transport
  425. } // namespace websocketpp
  426. #endif // WEBSOCKETPP_TRANSPORT_SECURITY_TLS_HPP