WebSocket++  0.7.0
C++ websocket client/server library
tls.hpp
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 
28 #ifndef WEBSOCKETPP_TRANSPORT_SECURITY_TLS_HPP
29 #define WEBSOCKETPP_TRANSPORT_SECURITY_TLS_HPP
30 
31 #include <websocketpp/transport/asio/security/base.hpp>
32 
33 #include <websocketpp/uri.hpp>
34 
35 #include <websocketpp/common/asio_ssl.hpp>
36 #include <websocketpp/common/asio.hpp>
37 #include <websocketpp/common/connection_hdl.hpp>
38 #include <websocketpp/common/functional.hpp>
39 #include <websocketpp/common/memory.hpp>
40 
41 #include <sstream>
42 #include <string>
43 
44 namespace websocketpp {
45 namespace transport {
46 namespace asio {
47 /// A socket policy for the asio transport that implements a TLS encrypted
48 /// socket by wrapping with an asio::ssl::stream
49 namespace tls_socket {
50 
51 /// The signature of the socket_init_handler for this socket policy
52 typedef lib::function<void(connection_hdl,lib::asio::ssl::stream<
54 /// The signature of the tls_init_handler for this socket policy
57 
58 /// TLS enabled Asio connection socket component
59 /**
60  * transport::asio::tls_socket::connection implements a secure connection socket
61  * component that uses Asio's ssl::stream to wrap an ip::tcp::socket.
62  */
64 public:
65  /// Type of this connection socket component
66  typedef connection type;
67  /// Type of a shared pointer to this connection socket component
68  typedef lib::shared_ptr<type> ptr;
69 
70  /// Type of the ASIO socket being used
72  /// Type of a shared pointer to the ASIO socket being used
74  /// Type of a pointer to the ASIO io_service being used
76  /// Type of a pointer to the ASIO io_service strand being used
78  /// Type of a shared pointer to the ASIO TLS context being used
80 
81  explicit connection() {
82  //std::cout << "transport::asio::tls_socket::connection constructor"
83  // << std::endl;
84  }
85 
86  /// Get a shared pointer to this component
88  return shared_from_this();
89  }
90 
91  /// Check whether or not this connection is secure
92  /**
93  * @return Whether or not this connection is secure
94  */
95  bool is_secure() const {
96  return true;
97  }
98 
99  /// Retrieve a pointer to the underlying socket
100  /**
101  * This is used internally. It can also be used to set socket options, etc
102  */
104  return m_socket->lowest_layer();
105  }
106 
107  /// Retrieve a pointer to the layer below the ssl stream
108  /**
109  * This is used internally.
110  */
112  return m_socket->next_layer();
113  }
114 
115  /// Retrieve a pointer to the wrapped socket
116  /**
117  * This is used internally.
118  */
120  return *m_socket;
121  }
122 
123  /// Set the socket initialization handler
124  /**
125  * The socket initialization handler is called after the socket object is
126  * created but before it is used. This gives the application a chance to
127  * set any ASIO socket options it needs.
128  *
129  * @param h The new socket_init_handler
130  */
131  void set_socket_init_handler(socket_init_handler h) {
132  m_socket_init_handler = h;
133  }
134 
135  /// Set TLS init handler
136  /**
137  * The tls init handler is called when needed to request a TLS context for
138  * the library to use. A TLS init handler must be set and it must return a
139  * valid TLS context in order for this endpoint to be able to initialize
140  * TLS connections
141  *
142  * @param h The new tls_init_handler
143  */
144  void set_tls_init_handler(tls_init_handler h) {
145  m_tls_init_handler = h;
146  }
147 
148  /// Get the remote endpoint address
149  /**
150  * The iostream transport has no information about the ultimate remote
151  * endpoint. It will return the string "iostream transport". To indicate
152  * this.
153  *
154  * TODO: allow user settable remote endpoint addresses if this seems useful
155  *
156  * @return A string identifying the address of the remote endpoint
157  */
158  std::string get_remote_endpoint(lib::error_code & ec) const {
159  std::stringstream s;
160 
161  lib::asio::error_code aec;
162  lib::asio::ip::tcp::endpoint ep = m_socket->lowest_layer().remote_endpoint(aec);
163 
164  if (aec) {
165  ec = error::make_error_code(error::pass_through);
166  s << "Error getting remote endpoint: " << aec
167  << " (" << aec.message() << ")";
168  return s.str();
169  } else {
170  ec = lib::error_code();
171  s << ep;
172  return s.str();
173  }
174  }
175 protected:
176  /// Perform one time initializations
177  /**
178  * init_asio is called once immediately after construction to initialize
179  * Asio components to the io_service
180  *
181  * @param service A pointer to the endpoint's io_service
182  * @param strand A pointer to the connection's strand
183  * @param is_server Whether or not the endpoint is a server or not.
184  */
186  bool is_server)
187  {
188  if (!m_tls_init_handler) {
189  return socket::make_error_code(socket::error::missing_tls_init_handler);
190  }
191  m_context = m_tls_init_handler(m_hdl);
192 
193  if (!m_context) {
194  return socket::make_error_code(socket::error::invalid_tls_context);
195  }
196  m_socket = lib::make_shared<socket_type>(
197  _WEBSOCKETPP_REF(*service),lib::ref(*m_context));
198 
199  m_io_service = service;
200  m_strand = strand;
201  m_is_server = is_server;
202 
203  return lib::error_code();
204  }
205 
206  /// Set hostname hook
207  /**
208  * Called by the transport as a connection is being established to provide
209  * the hostname being connected to to the security/socket layer.
210  *
211  * This socket policy uses the hostname to set the appropriate TLS SNI
212  * header.
213  *
214  * @since 0.6.0
215  *
216  * @param u The uri to set
217  */
218  void set_uri(uri_ptr u) {
219  m_uri = u;
220  }
221 
222  /// Pre-initialize security policy
223  /**
224  * Called by the transport after a new connection is created to initialize
225  * the socket component of the connection. This method is not allowed to
226  * write any bytes to the wire. This initialization happens before any
227  * proxies or other intermediate wrappers are negotiated.
228  *
229  * @param callback Handler to call back with completion information
230  */
231  void pre_init(init_handler callback) {
232  // TODO: is this the best way to check whether this function is
233  // available in the version of OpenSSL being used?
234  // TODO: consider case where host is an IP address
235 #if OPENSSL_VERSION_NUMBER >= 0x90812f
236  if (!m_is_server) {
237  // For clients on systems with a suitable OpenSSL version, set the
238  // TLS SNI hostname header so connecting to TLS servers using SNI
239  // will work.
240  long res = SSL_set_tlsext_host_name(
241  get_socket().native_handle(), m_uri->get_host().c_str());
242  if (!(1 == res)) {
243  callback(socket::make_error_code(socket::error::tls_failed_sni_hostname));
244  }
245  }
246 #endif
247 
248  if (m_socket_init_handler) {
249  m_socket_init_handler(m_hdl,get_socket());
250  }
251 
252  callback(lib::error_code());
253  }
254 
255  /// Post-initialize security policy
256  /**
257  * Called by the transport after all intermediate proxies have been
258  * negotiated. This gives the security policy the chance to talk with the
259  * real remote endpoint for a bit before the websocket handshake.
260  *
261  * @param callback Handler to call back with completion information
262  */
263  void post_init(init_handler callback) {
264  m_ec = socket::make_error_code(socket::error::tls_handshake_timeout);
265 
266  // TLS handshake
267  if (m_strand) {
268  m_socket->async_handshake(
269  get_handshake_type(),
270  m_strand->wrap(lib::bind(
271  &type::handle_init, get_shared(),
272  callback,
273  lib::placeholders::_1
274  ))
275  );
276  } else {
277  m_socket->async_handshake(
278  get_handshake_type(),
279  lib::bind(
280  &type::handle_init, get_shared(),
281  callback,
282  lib::placeholders::_1
283  )
284  );
285  }
286  }
287 
288  /// Sets the connection handle
289  /**
290  * The connection handle is passed to any handlers to identify the
291  * connection
292  *
293  * @param hdl The new handle
294  */
295  void set_handle(connection_hdl hdl) {
296  m_hdl = hdl;
297  }
298 
299  void handle_init(init_handler callback,lib::asio::error_code const & ec) {
300  if (ec) {
301  m_ec = socket::make_error_code(socket::error::tls_handshake_failed);
302  } else {
303  m_ec = lib::error_code();
304  }
305 
306  callback(m_ec);
307  }
308 
309  lib::error_code get_ec() const {
310  return m_ec;
311  }
312 
313  /// Cancel all async operations on this socket
314  /**
315  * Attempts to cancel all async operations on this socket and reports any
316  * failures.
317  *
318  * NOTE: Windows XP and earlier do not support socket cancellation.
319  *
320  * @return The error that occurred, if any.
321  */
323  lib::asio::error_code ec;
324  get_raw_socket().cancel(ec);
325  return ec;
326  }
327 
328  void async_shutdown(socket::shutdown_handler callback) {
329  if (m_strand) {
330  m_socket->async_shutdown(m_strand->wrap(callback));
331  } else {
332  m_socket->async_shutdown(callback);
333  }
334  }
335 
336  /// Translate any security policy specific information about an error code
337  /**
338  * Translate_ec takes an Asio error code and attempts to convert its value
339  * to an appropriate websocketpp error code. In the case that the Asio and
340  * Websocketpp error types are the same (such as using boost::asio and
341  * boost::system_error or using standalone asio and std::system_error the
342  * code will be passed through natively.
343  *
344  * In the case of a mismatch (boost::asio with std::system_error) a
345  * translated code will be returned. Any error that is determined to be
346  * related to TLS but does not have a more specific websocketpp error code
347  * is returned under the catch all error `tls_error`. Non-TLS related errors
348  * are returned as the transport generic error `pass_through`
349  *
350  * @since 0.3.0
351  *
352  * @param ec The error code to translate_ec
353  * @return The translated error code
354  */
355  template <typename ErrorCodeType>
357  return make_error_code(transport::error::pass_through);
358  }
359 
360  /// Overload of translate_ec to catch cases where lib::error_code is the
361  /// same type as lib::asio::error_code
363  // Normalize the tls_short_read error as it is used by the library and
364  // needs a consistent value. All other errors pass through natively.
365  // TODO: how to get the SSL category from std::error?
366  /*if (ec.category() == lib::asio::error::get_ssl_category()) {
367  if (ERR_GET_REASON(ec.value()) == SSL_R_SHORT_READ) {
368  return make_error_code(transport::error::tls_short_read);
369  }
370  }*/
371  return ec;
372  }
373 private:
374  socket_type::handshake_type get_handshake_type() {
375  if (m_is_server) {
376  return lib::asio::ssl::stream_base::server;
377  } else {
378  return lib::asio::ssl::stream_base::client;
379  }
380  }
381 
382  io_service_ptr m_io_service;
383  strand_ptr m_strand;
384  context_ptr m_context;
385  socket_ptr m_socket;
386  uri_ptr m_uri;
387  bool m_is_server;
388 
389  lib::error_code m_ec;
390 
391  connection_hdl m_hdl;
392  socket_init_handler m_socket_init_handler;
393  tls_init_handler m_tls_init_handler;
394 };
395 
396 /// TLS enabled Asio endpoint socket component
397 /**
398  * transport::asio::tls_socket::endpoint implements a secure endpoint socket
399  * component that uses Asio's ssl::stream to wrap an ip::tcp::socket.
400  */
401 class endpoint {
402 public:
403  /// The type of this endpoint socket component
404  typedef endpoint type;
405 
406  /// The type of the corresponding connection socket component
408  /// The type of a shared pointer to the corresponding connection socket
409  /// component.
411 
412  explicit endpoint() {}
413 
414  /// Checks whether the endpoint creates secure connections
415  /**
416  * @return Whether or not the endpoint creates secure connections
417  */
418  bool is_secure() const {
419  return true;
420  }
421 
422  /// Set socket init handler
423  /**
424  * The socket init handler is called after a connection's socket is created
425  * but before it is used. This gives the end application an opportunity to
426  * set asio socket specific parameters.
427  *
428  * @param h The new socket_init_handler
429  */
430  void set_socket_init_handler(socket_init_handler h) {
431  m_socket_init_handler = h;
432  }
433 
434  /// Set TLS init handler
435  /**
436  * The tls init handler is called when needed to request a TLS context for
437  * the library to use. A TLS init handler must be set and it must return a
438  * valid TLS context in order for this endpoint to be able to initialize
439  * TLS connections
440  *
441  * @param h The new tls_init_handler
442  */
443  void set_tls_init_handler(tls_init_handler h) {
444  m_tls_init_handler = h;
445  }
446 protected:
447  /// Initialize a connection
448  /**
449  * Called by the transport after a new connection is created to initialize
450  * the socket component of the connection.
451  *
452  * @param scon Pointer to the socket component of the connection
453  *
454  * @return Error code (empty on success)
455  */
457  scon->set_socket_init_handler(m_socket_init_handler);
458  scon->set_tls_init_handler(m_tls_init_handler);
459  return lib::error_code();
460  }
461 
462 private:
463  socket_init_handler m_socket_init_handler;
464  tls_init_handler m_tls_init_handler;
465 };
466 
467 } // namespace tls_socket
468 } // namespace asio
469 } // namespace transport
470 } // namespace websocketpp
471 
472 #endif // WEBSOCKETPP_TRANSPORT_SECURITY_TLS_HPP
socket_type & get_socket()
Retrieve a pointer to the wrapped socket.
Definition: tls.hpp:119
lib::asio::error_code cancel_socket()
Cancel all async operations on this socket.
Definition: tls.hpp:322
void pre_init(init_handler callback)
Pre-initialize security policy.
Definition: tls.hpp:231
connection type
Type of this connection socket component.
Definition: tls.hpp:66
void set_handle(connection_hdl hdl)
Sets the connection handle.
Definition: tls.hpp:295
bool is_secure() const
Check whether or not this connection is secure.
Definition: tls.hpp:95
lib::function< lib::shared_ptr< lib::asio::ssl::context >connection_hdl)> tls_init_handler
The signature of the tls_init_handler for this socket policy.
Definition: tls.hpp:56
lib::error_code translate_ec(ErrorCodeType ec)
Translate any security policy specific information about an error code.
Definition: tls.hpp:356
lib::error_code init(socket_con_ptr scon)
Initialize a connection.
Definition: tls.hpp:456
socket_type::next_layer_type & get_next_layer()
Retrieve a pointer to the layer below the ssl stream.
Definition: tls.hpp:111
std::string get_remote_endpoint(lib::error_code &ec) const
Get the remote endpoint address.
Definition: tls.hpp:158
connection socket_con_type
The type of the corresponding connection socket component.
Definition: tls.hpp:407
void set_tls_init_handler(tls_init_handler h)
Set TLS init handler.
Definition: tls.hpp:443
lib::shared_ptr< lib::asio::ssl::context > context_ptr
Type of a shared pointer to the ASIO TLS context being used.
Definition: tls.hpp:79
void set_uri(uri_ptr u)
Set hostname hook.
Definition: tls.hpp:218
void set_socket_init_handler(socket_init_handler h)
Set socket init handler.
Definition: tls.hpp:430
lib::asio::io_service * io_service_ptr
Type of a pointer to the ASIO io_service being used.
Definition: tls.hpp:75
ptr get_shared()
Get a shared pointer to this component.
Definition: tls.hpp:87
lib::error_code init_asio(io_service_ptr service, strand_ptr strand, bool is_server)
Perform one time initializations.
Definition: tls.hpp:185
socket_type::lowest_layer_type & get_raw_socket()
Retrieve a pointer to the underlying socket.
Definition: tls.hpp:103
endpoint type
The type of this endpoint socket component.
Definition: tls.hpp:404
void handle_accept(connection_ptr con, lib::error_code const &ec)
Handler callback for start_accept.
void set_tls_init_handler(tls_init_handler h)
Set TLS init handler.
Definition: tls.hpp:144
void set_socket_init_handler(socket_init_handler h)
Set the socket initialization handler.
Definition: tls.hpp:131
void post_init(init_handler callback)
Post-initialize security policy.
Definition: tls.hpp:263
TLS enabled Asio endpoint socket component.
Definition: tls.hpp:401
lib::error_code translate_ec(lib::error_code ec)
Definition: tls.hpp:362
bool is_secure() const
Checks whether the endpoint creates secure connections.
Definition: tls.hpp:418
lib::function< void(lib::error_code const &)> connect_handler
The type and signature of the callback passed to the connect method.
Definition: endpoint.hpp:72