tls.hpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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.hpp>
  32. #include <websocketpp/common/asio_ssl.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 Boost 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. m_io_service = service;
  178. m_strand = strand;
  179. m_is_server = is_server;
  180. return lib::error_code();
  181. }
  182. /// Set hostname hook
  183. /**
  184. * Called by the transport as a connection is being established to provide
  185. * the hostname being connected to to the security/socket layer.
  186. *
  187. * This socket policy uses the hostname to set the appropriate TLS SNI
  188. * header.
  189. *
  190. * @since 0.6.0
  191. *
  192. * @param u The uri to set
  193. */
  194. void set_uri(uri_ptr u) {
  195. m_uri = u;
  196. }
  197. /// Pre-initialize security policy
  198. /**
  199. * Called by the transport after a new connection is created to initialize
  200. * the socket component of the connection. This method is not allowed to
  201. * write any bytes to the wire. This initialization happens before any
  202. * proxies or other intermediate wrappers are negotiated.
  203. *
  204. * @param callback Handler to call back with completion information
  205. */
  206. void pre_init(init_handler callback) {
  207. // TODO: is this the best way to check whether this function is
  208. // available in the version of OpenSSL being used?
  209. // TODO: consider case where host is an IP address
  210. #if OPENSSL_VERSION_NUMBER >= 0x90812f
  211. if (!m_is_server) {
  212. // For clients on systems with a suitable OpenSSL version, set the
  213. // TLS SNI hostname header so connecting to TLS servers using SNI
  214. // will work.
  215. long res = SSL_set_tlsext_host_name(
  216. get_socket().native_handle(), m_uri->get_host().c_str());
  217. if (!(1 == res)) {
  218. callback(socket::make_error_code(socket::error::tls_failed_sni_hostname));
  219. }
  220. }
  221. #endif
  222. if (m_socket_init_handler) {
  223. m_socket_init_handler(m_hdl,get_socket());
  224. }
  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. void cancel_socket() {
  281. get_raw_socket().cancel();
  282. }
  283. void async_shutdown(socket_shutdown_handler callback) {
  284. m_socket->async_shutdown(callback);
  285. }
  286. /// Translate any security policy specific information about an error code
  287. /**
  288. * Translate_ec takes a boost error code and attempts to convert its value
  289. * to an appropriate websocketpp error code. Any error that is determined to
  290. * be related to TLS but does not have a more specific websocketpp error
  291. * code is returned under the catch all error "tls_error".
  292. *
  293. * Non-TLS related errors are returned as the transport generic pass_through
  294. * error.
  295. *
  296. * @since 0.3.0
  297. *
  298. * @param ec The error code to translate_ec
  299. * @return The translated error code
  300. */
  301. lib::error_code translate_ec(boost::system::error_code ec) {
  302. if (ec.category() == lib::asio::error::get_ssl_category()) {
  303. if (ERR_GET_REASON(ec.value()) == SSL_R_SHORT_READ) {
  304. return make_error_code(transport::error::tls_short_read);
  305. } else {
  306. // We know it is a TLS related error, but otherwise don't know
  307. // more. Pass through as TLS generic.
  308. return make_error_code(transport::error::tls_error);
  309. }
  310. } else {
  311. // We don't know any more information about this error so pass
  312. // through
  313. return make_error_code(transport::error::pass_through);
  314. }
  315. }
  316. private:
  317. socket_type::handshake_type get_handshake_type() {
  318. if (m_is_server) {
  319. return lib::asio::ssl::stream_base::server;
  320. } else {
  321. return lib::asio::ssl::stream_base::client;
  322. }
  323. }
  324. io_service_ptr m_io_service;
  325. strand_ptr m_strand;
  326. context_ptr m_context;
  327. socket_ptr m_socket;
  328. uri_ptr m_uri;
  329. bool m_is_server;
  330. lib::error_code m_ec;
  331. connection_hdl m_hdl;
  332. socket_init_handler m_socket_init_handler;
  333. tls_init_handler m_tls_init_handler;
  334. };
  335. /// TLS enabled Asio endpoint socket component
  336. /**
  337. * transport::asio::tls_socket::endpoint implements a secure endpoint socket
  338. * component that uses Asio's ssl::stream to wrap an ip::tcp::socket.
  339. */
  340. class endpoint {
  341. public:
  342. /// The type of this endpoint socket component
  343. typedef endpoint type;
  344. /// The type of the corresponding connection socket component
  345. typedef connection socket_con_type;
  346. /// The type of a shared pointer to the corresponding connection socket
  347. /// component.
  348. typedef socket_con_type::ptr socket_con_ptr;
  349. explicit endpoint() {}
  350. /// Checks whether the endpoint creates secure connections
  351. /**
  352. * @return Whether or not the endpoint creates secure connections
  353. */
  354. bool is_secure() const {
  355. return true;
  356. }
  357. /// Set socket init handler
  358. /**
  359. * The socket init handler is called after a connection's socket is created
  360. * but before it is used. This gives the end application an opportunity to
  361. * set asio socket specific parameters.
  362. *
  363. * @param h The new socket_init_handler
  364. */
  365. void set_socket_init_handler(socket_init_handler h) {
  366. m_socket_init_handler = h;
  367. }
  368. /// Set TLS init handler
  369. /**
  370. * The tls init handler is called when needed to request a TLS context for
  371. * the library to use. A TLS init handler must be set and it must return a
  372. * valid TLS context in order for this endpoint to be able to initialize
  373. * TLS connections
  374. *
  375. * @param h The new tls_init_handler
  376. */
  377. void set_tls_init_handler(tls_init_handler h) {
  378. m_tls_init_handler = h;
  379. }
  380. protected:
  381. /// Initialize a connection
  382. /**
  383. * Called by the transport after a new connection is created to initialize
  384. * the socket component of the connection.
  385. *
  386. * @param scon Pointer to the socket component of the connection
  387. *
  388. * @return Error code (empty on success)
  389. */
  390. lib::error_code init(socket_con_ptr scon) {
  391. scon->set_socket_init_handler(m_socket_init_handler);
  392. scon->set_tls_init_handler(m_tls_init_handler);
  393. return lib::error_code();
  394. }
  395. private:
  396. socket_init_handler m_socket_init_handler;
  397. tls_init_handler m_tls_init_handler;
  398. };
  399. } // namespace tls_socket
  400. } // namespace asio
  401. } // namespace transport
  402. } // namespace websocketpp
  403. #endif // WEBSOCKETPP_TRANSPORT_SECURITY_TLS_HPP