ssl_stream.hpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. //
  2. // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/boostorg/beast
  8. //
  9. #ifndef BOOST_BEAST_CORE_SSL_STREAM_HPP
  10. #define BOOST_BEAST_CORE_SSL_STREAM_HPP
  11. #include <boost/beast/core/detail/config.hpp>
  12. // This include is necessary to work with `ssl::stream` and `boost::beast::websocket::stream`
  13. #include <boost/beast/websocket/ssl.hpp>
  14. #include <boost/beast/core/flat_stream.hpp>
  15. // VFALCO We include this because anyone who uses ssl will
  16. // very likely need to check for ssl::error::stream_truncated
  17. #include <boost/asio/ssl/error.hpp>
  18. #include <boost/asio/ssl/stream.hpp>
  19. #include <cstddef>
  20. #include <memory>
  21. #include <type_traits>
  22. #include <utility>
  23. namespace boost {
  24. namespace beast {
  25. /** Provides stream-oriented functionality using OpenSSL
  26. The stream class template provides asynchronous and blocking
  27. stream-oriented functionality using SSL.
  28. @par Thread Safety
  29. @e Distinct @e objects: Safe.@n
  30. @e Shared @e objects: Unsafe. The application must also ensure that all
  31. asynchronous operations are performed within the same implicit or explicit
  32. strand.
  33. @par Example
  34. To use this template with a @ref tcp_stream, you would write:
  35. @code
  36. net::io_context ioc;
  37. net::ssl::context ctx{net::ssl::context::tlsv12};
  38. beast::ssl_stream<beast::tcp_stream> sock{ioc, ctx};
  39. @endcode
  40. In addition to providing an interface identical to `net::ssl::stream`,
  41. the wrapper has the following additional properties:
  42. @li Satisfies @b MoveConstructible
  43. @li Satisfies @b MoveAssignable
  44. @li Constructible from a moved socket.
  45. @li Uses @ref flat_stream internally, as a performance work-around for a
  46. limitation of `net::ssl::stream` when writing buffer sequences
  47. having length greater than one.
  48. @par Concepts:
  49. @li AsyncReadStream
  50. @li AsyncWriteStream
  51. @li Stream
  52. @li SyncReadStream
  53. @li SyncWriteStream
  54. */
  55. template<class NextLayer>
  56. class ssl_stream
  57. : public net::ssl::stream_base
  58. {
  59. using ssl_stream_type = net::ssl::stream<NextLayer>;
  60. using stream_type = boost::beast::flat_stream<ssl_stream_type>;
  61. std::unique_ptr<stream_type> p_;
  62. public:
  63. /// The native handle type of the SSL stream.
  64. using native_handle_type =
  65. typename ssl_stream_type::native_handle_type;
  66. /// Structure for use with deprecated impl_type.
  67. using impl_struct = typename ssl_stream_type::impl_struct;
  68. /// The type of the next layer.
  69. using next_layer_type = typename ssl_stream_type::next_layer_type;
  70. /// The type of the executor associated with the object.
  71. using executor_type = typename stream_type::executor_type;
  72. /** Construct a stream.
  73. This constructor creates a stream and initialises the underlying stream
  74. object.
  75. @param arg The argument to be passed to initialise the underlying stream.
  76. @param ctx The SSL context to be used for the stream.
  77. */
  78. template<class Arg>
  79. ssl_stream(
  80. Arg&& arg,
  81. net::ssl::context& ctx)
  82. : p_(new stream_type{
  83. std::forward<Arg>(arg), ctx})
  84. {
  85. }
  86. /** Get the executor associated with the object.
  87. This function may be used to obtain the executor object that the stream
  88. uses to dispatch handlers for asynchronous operations.
  89. @return A copy of the executor that stream will use to dispatch handlers.
  90. */
  91. executor_type
  92. get_executor() noexcept
  93. {
  94. return p_->get_executor();
  95. }
  96. /** Get the underlying implementation in the native type.
  97. This function may be used to obtain the underlying implementation of the
  98. context. This is intended to allow access to context functionality that is
  99. not otherwise provided.
  100. @par Example
  101. The native_handle() function returns a pointer of type @c SSL* that is
  102. suitable for passing to functions such as @c SSL_get_verify_result and
  103. @c SSL_get_peer_certificate:
  104. @code
  105. boost::beast::ssl_stream<net::ip::tcp::socket> ss{ioc, ctx};
  106. // ... establish connection and perform handshake ...
  107. if (X509* cert = SSL_get_peer_certificate(ss.native_handle()))
  108. {
  109. if (SSL_get_verify_result(ss.native_handle()) == X509_V_OK)
  110. {
  111. // ...
  112. }
  113. }
  114. @endcode
  115. */
  116. native_handle_type
  117. native_handle() noexcept
  118. {
  119. return p_->next_layer().native_handle();
  120. }
  121. /** Get a reference to the next layer.
  122. This function returns a reference to the next layer in a stack of stream
  123. layers.
  124. @note The next layer is the wrapped stream and not the @ref flat_stream
  125. used in the implementation.
  126. @return A reference to the next layer in the stack of stream layers.
  127. Ownership is not transferred to the caller.
  128. */
  129. next_layer_type const&
  130. next_layer() const noexcept
  131. {
  132. return p_->next_layer().next_layer();
  133. }
  134. /** Get a reference to the next layer.
  135. This function returns a reference to the next layer in a stack of stream
  136. layers.
  137. @note The next layer is the wrapped stream and not the @ref flat_stream
  138. used in the implementation.
  139. @return A reference to the next layer in the stack of stream layers.
  140. Ownership is not transferred to the caller.
  141. */
  142. next_layer_type&
  143. next_layer() noexcept
  144. {
  145. return p_->next_layer().next_layer();
  146. }
  147. /** Set the peer verification mode.
  148. This function may be used to configure the peer verification mode used by
  149. the stream. The new mode will override the mode inherited from the context.
  150. @param v A bitmask of peer verification modes.
  151. @throws boost::system::system_error Thrown on failure.
  152. @note Calls @c SSL_set_verify.
  153. */
  154. void
  155. set_verify_mode(net::ssl::verify_mode v)
  156. {
  157. p_->next_layer().set_verify_mode(v);
  158. }
  159. /** Set the peer verification mode.
  160. This function may be used to configure the peer verification mode used by
  161. the stream. The new mode will override the mode inherited from the context.
  162. @param v A bitmask of peer verification modes. See `verify_mode` for
  163. available values.
  164. @param ec Set to indicate what error occurred, if any.
  165. @note Calls @c SSL_set_verify.
  166. */
  167. void
  168. set_verify_mode(net::ssl::verify_mode v,
  169. boost::system::error_code& ec)
  170. {
  171. p_->next_layer().set_verify_mode(v, ec);
  172. }
  173. /** Set the peer verification depth.
  174. This function may be used to configure the maximum verification depth
  175. allowed by the stream.
  176. @param depth Maximum depth for the certificate chain verification that
  177. shall be allowed.
  178. @throws boost::system::system_error Thrown on failure.
  179. @note Calls @c SSL_set_verify_depth.
  180. */
  181. void
  182. set_verify_depth(int depth)
  183. {
  184. p_->next_layer().set_verify_depth(depth);
  185. }
  186. /** Set the peer verification depth.
  187. This function may be used to configure the maximum verification depth
  188. allowed by the stream.
  189. @param depth Maximum depth for the certificate chain verification that
  190. shall be allowed.
  191. @param ec Set to indicate what error occurred, if any.
  192. @note Calls @c SSL_set_verify_depth.
  193. */
  194. void
  195. set_verify_depth(
  196. int depth, boost::system::error_code& ec)
  197. {
  198. p_->next_layer().set_verify_depth(depth, ec);
  199. }
  200. /** Set the callback used to verify peer certificates.
  201. This function is used to specify a callback function that will be called
  202. by the implementation when it needs to verify a peer certificate.
  203. @param callback The function object to be used for verifying a certificate.
  204. The function signature of the handler must be:
  205. @code bool verify_callback(
  206. bool preverified, // True if the certificate passed pre-verification.
  207. verify_context& ctx // The peer certificate and other context.
  208. ); @endcode
  209. The return value of the callback is true if the certificate has passed
  210. verification, false otherwise.
  211. @throws boost::system::system_error Thrown on failure.
  212. @note Calls @c SSL_set_verify.
  213. */
  214. template<class VerifyCallback>
  215. void
  216. set_verify_callback(VerifyCallback callback)
  217. {
  218. p_->next_layer().set_verify_callback(callback);
  219. }
  220. /** Set the callback used to verify peer certificates.
  221. This function is used to specify a callback function that will be called
  222. by the implementation when it needs to verify a peer certificate.
  223. @param callback The function object to be used for verifying a certificate.
  224. The function signature of the handler must be:
  225. @code bool verify_callback(
  226. bool preverified, // True if the certificate passed pre-verification.
  227. net::verify_context& ctx // The peer certificate and other context.
  228. ); @endcode
  229. The return value of the callback is true if the certificate has passed
  230. verification, false otherwise.
  231. @param ec Set to indicate what error occurred, if any.
  232. @note Calls @c SSL_set_verify.
  233. */
  234. template<class VerifyCallback>
  235. void
  236. set_verify_callback(VerifyCallback callback,
  237. boost::system::error_code& ec)
  238. {
  239. p_->next_layer().set_verify_callback(callback, ec);
  240. }
  241. /** Perform SSL handshaking.
  242. This function is used to perform SSL handshaking on the stream. The
  243. function call will block until handshaking is complete or an error occurs.
  244. @param type The type of handshaking to be performed, i.e. as a client or as
  245. a server.
  246. @throws boost::system::system_error Thrown on failure.
  247. */
  248. void
  249. handshake(handshake_type type)
  250. {
  251. p_->next_layer().handshake(type);
  252. }
  253. /** Perform SSL handshaking.
  254. This function is used to perform SSL handshaking on the stream. The
  255. function call will block until handshaking is complete or an error occurs.
  256. @param type The type of handshaking to be performed, i.e. as a client or as
  257. a server.
  258. @param ec Set to indicate what error occurred, if any.
  259. */
  260. void
  261. handshake(handshake_type type,
  262. boost::system::error_code& ec)
  263. {
  264. p_->next_layer().handshake(type, ec);
  265. }
  266. /** Perform SSL handshaking.
  267. This function is used to perform SSL handshaking on the stream. The
  268. function call will block until handshaking is complete or an error occurs.
  269. @param type The type of handshaking to be performed, i.e. as a client or as
  270. a server.
  271. @param buffers The buffered data to be reused for the handshake.
  272. @throws boost::system::system_error Thrown on failure.
  273. */
  274. template<class ConstBufferSequence>
  275. void
  276. handshake(
  277. handshake_type type, ConstBufferSequence const& buffers)
  278. {
  279. p_->next_layer().handshake(type, buffers);
  280. }
  281. /** Perform SSL handshaking.
  282. This function is used to perform SSL handshaking on the stream. The
  283. function call will block until handshaking is complete or an error occurs.
  284. @param type The type of handshaking to be performed, i.e. as a client or as
  285. a server.
  286. @param buffers The buffered data to be reused for the handshake.
  287. @param ec Set to indicate what error occurred, if any.
  288. */
  289. template<class ConstBufferSequence>
  290. void
  291. handshake(handshake_type type,
  292. ConstBufferSequence const& buffers,
  293. boost::system::error_code& ec)
  294. {
  295. p_->next_layer().handshake(type, buffers, ec);
  296. }
  297. /** Start an asynchronous SSL handshake.
  298. This function is used to asynchronously perform an SSL handshake on the
  299. stream. This function call always returns immediately.
  300. @param type The type of handshaking to be performed, i.e. as a client or as
  301. a server.
  302. @param handler The handler to be called when the handshake operation
  303. completes. Copies will be made of the handler as required. The equivalent
  304. function signature of the handler must be:
  305. @code void handler(
  306. const boost::system::error_code& error // Result of operation.
  307. ); @endcode
  308. */
  309. template<class HandshakeHandler>
  310. BOOST_ASIO_INITFN_RESULT_TYPE(HandshakeHandler, void(boost::system::error_code))
  311. async_handshake(handshake_type type,
  312. BOOST_ASIO_MOVE_ARG(HandshakeHandler) handler)
  313. {
  314. return p_->next_layer().async_handshake(type,
  315. BOOST_ASIO_MOVE_CAST(HandshakeHandler)(handler));
  316. }
  317. /** Start an asynchronous SSL handshake.
  318. This function is used to asynchronously perform an SSL handshake on the
  319. stream. This function call always returns immediately.
  320. @param type The type of handshaking to be performed, i.e. as a client or as
  321. a server.
  322. @param buffers The buffered data to be reused for the handshake. Although
  323. the buffers object may be copied as necessary, ownership of the underlying
  324. buffers is retained by the caller, which must guarantee that they remain
  325. valid until the handler is called.
  326. @param handler The handler to be called when the handshake operation
  327. completes. Copies will be made of the handler as required. The equivalent
  328. function signature of the handler must be:
  329. @code void handler(
  330. const boost::system::error_code& error, // Result of operation.
  331. std::size_t bytes_transferred // Amount of buffers used in handshake.
  332. ); @endcode
  333. */
  334. template<class ConstBufferSequence, class BufferedHandshakeHandler>
  335. BOOST_ASIO_INITFN_RESULT_TYPE(BufferedHandshakeHandler, void(boost::system::error_code, std::size_t))
  336. async_handshake(handshake_type type, ConstBufferSequence const& buffers,
  337. BOOST_ASIO_MOVE_ARG(BufferedHandshakeHandler) handler)
  338. {
  339. return p_->next_layer().async_handshake(type, buffers,
  340. BOOST_ASIO_MOVE_CAST(BufferedHandshakeHandler)(handler));
  341. }
  342. /** Shut down SSL on the stream.
  343. This function is used to shut down SSL on the stream. The function call
  344. will block until SSL has been shut down or an error occurs.
  345. @throws boost::system::system_error Thrown on failure.
  346. */
  347. void
  348. shutdown()
  349. {
  350. p_->next_layer().shutdown();
  351. }
  352. /** Shut down SSL on the stream.
  353. This function is used to shut down SSL on the stream. The function call
  354. will block until SSL has been shut down or an error occurs.
  355. @param ec Set to indicate what error occurred, if any.
  356. */
  357. void
  358. shutdown(boost::system::error_code& ec)
  359. {
  360. p_->next_layer().shutdown(ec);
  361. }
  362. /** Asynchronously shut down SSL on the stream.
  363. This function is used to asynchronously shut down SSL on the stream. This
  364. function call always returns immediately.
  365. @param handler The handler to be called when the handshake operation
  366. completes. Copies will be made of the handler as required. The equivalent
  367. function signature of the handler must be:
  368. @code void handler(
  369. const boost::system::error_code& error // Result of operation.
  370. ); @endcode
  371. */
  372. template<class ShutdownHandler>
  373. BOOST_ASIO_INITFN_RESULT_TYPE(ShutdownHandler, void(boost::system::error_code))
  374. async_shutdown(BOOST_ASIO_MOVE_ARG(ShutdownHandler) handler)
  375. {
  376. return p_->next_layer().async_shutdown(
  377. BOOST_ASIO_MOVE_CAST(ShutdownHandler)(handler));
  378. }
  379. /** Write some data to the stream.
  380. This function is used to write data on the stream. The function call will
  381. block until one or more bytes of data has been written successfully, or
  382. until an error occurs.
  383. @param buffers The data to be written.
  384. @returns The number of bytes written.
  385. @throws boost::system::system_error Thrown on failure.
  386. @note The `write_some` operation may not transmit all of the data to the
  387. peer. Consider using the `net::write` function if you need to
  388. ensure that all data is written before the blocking operation completes.
  389. */
  390. template<class ConstBufferSequence>
  391. std::size_t
  392. write_some(ConstBufferSequence const& buffers)
  393. {
  394. return p_->write_some(buffers);
  395. }
  396. /** Write some data to the stream.
  397. This function is used to write data on the stream. The function call will
  398. block until one or more bytes of data has been written successfully, or
  399. until an error occurs.
  400. @param buffers The data to be written to the stream.
  401. @param ec Set to indicate what error occurred, if any.
  402. @returns The number of bytes written. Returns 0 if an error occurred.
  403. @note The `write_some` operation may not transmit all of the data to the
  404. peer. Consider using the `net::write` function if you need to
  405. ensure that all data is written before the blocking operation completes.
  406. */
  407. template<class ConstBufferSequence>
  408. std::size_t
  409. write_some(ConstBufferSequence const& buffers,
  410. boost::system::error_code& ec)
  411. {
  412. return p_->write_some(buffers, ec);
  413. }
  414. /** Start an asynchronous write.
  415. This function is used to asynchronously write one or more bytes of data to
  416. the stream. The function call always returns immediately.
  417. @param buffers The data to be written to the stream. Although the buffers
  418. object may be copied as necessary, ownership of the underlying buffers is
  419. retained by the caller, which must guarantee that they remain valid until
  420. the handler is called.
  421. @param handler The handler to be called when the write operation completes.
  422. Copies will be made of the handler as required. The equivalent function
  423. signature of the handler must be:
  424. @code void handler(
  425. const boost::system::error_code& error, // Result of operation.
  426. std::size_t bytes_transferred // Number of bytes written.
  427. ); @endcode
  428. @note The `async_write_some` operation may not transmit all of the data to
  429. the peer. Consider using the `net::async_write` function if you
  430. need to ensure that all data is written before the asynchronous operation
  431. completes.
  432. */
  433. template<class ConstBufferSequence, BOOST_BEAST_ASYNC_TPARAM2 WriteHandler>
  434. BOOST_ASIO_INITFN_RESULT_TYPE(WriteHandler, void(boost::system::error_code, std::size_t))
  435. async_write_some(ConstBufferSequence const& buffers,
  436. BOOST_ASIO_MOVE_ARG(WriteHandler) handler)
  437. {
  438. return p_->async_write_some(buffers,
  439. BOOST_ASIO_MOVE_CAST(WriteHandler)(handler));
  440. }
  441. /** Read some data from the stream.
  442. This function is used to read data from the stream. The function call will
  443. block until one or more bytes of data has been read successfully, or until
  444. an error occurs.
  445. @param buffers The buffers into which the data will be read.
  446. @returns The number of bytes read.
  447. @throws boost::system::system_error Thrown on failure.
  448. @note The `read_some` operation may not read all of the requested number of
  449. bytes. Consider using the `net::read` function if you need to ensure
  450. that the requested amount of data is read before the blocking operation
  451. completes.
  452. */
  453. template<class MutableBufferSequence>
  454. std::size_t
  455. read_some(MutableBufferSequence const& buffers)
  456. {
  457. return p_->read_some(buffers);
  458. }
  459. /** Read some data from the stream.
  460. This function is used to read data from the stream. The function call will
  461. block until one or more bytes of data has been read successfully, or until
  462. an error occurs.
  463. @param buffers The buffers into which the data will be read.
  464. @param ec Set to indicate what error occurred, if any.
  465. @returns The number of bytes read. Returns 0 if an error occurred.
  466. @note The `read_some` operation may not read all of the requested number of
  467. bytes. Consider using the `net::read` function if you need to ensure
  468. that the requested amount of data is read before the blocking operation
  469. completes.
  470. */
  471. template<class MutableBufferSequence>
  472. std::size_t
  473. read_some(MutableBufferSequence const& buffers,
  474. boost::system::error_code& ec)
  475. {
  476. return p_->read_some(buffers, ec);
  477. }
  478. /** Start an asynchronous read.
  479. This function is used to asynchronously read one or more bytes of data from
  480. the stream. The function call always returns immediately.
  481. @param buffers The buffers into which the data will be read. Although the
  482. buffers object may be copied as necessary, ownership of the underlying
  483. buffers is retained by the caller, which must guarantee that they remain
  484. valid until the handler is called.
  485. @param handler The handler to be called when the read operation completes.
  486. Copies will be made of the handler as required. The equivalent function
  487. signature of the handler must be:
  488. @code void handler(
  489. const boost::system::error_code& error, // Result of operation.
  490. std::size_t bytes_transferred // Number of bytes read.
  491. ); @endcode
  492. @note The `async_read_some` operation may not read all of the requested
  493. number of bytes. Consider using the `net::async_read` function
  494. if you need to ensure that the requested amount of data is read before
  495. the asynchronous operation completes.
  496. */
  497. template<class MutableBufferSequence, BOOST_BEAST_ASYNC_TPARAM2 ReadHandler>
  498. BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler, void(boost::system::error_code, std::size_t))
  499. async_read_some(MutableBufferSequence const& buffers,
  500. BOOST_ASIO_MOVE_ARG(ReadHandler) handler)
  501. {
  502. return p_->async_read_some(buffers,
  503. BOOST_ASIO_MOVE_CAST(ReadHandler)(handler));
  504. }
  505. // These hooks are used to inform boost::beast::websocket::stream on
  506. // how to tear down the connection as part of the WebSocket
  507. // protocol specifications
  508. #if ! BOOST_BEAST_DOXYGEN
  509. template<class SyncStream>
  510. friend
  511. void
  512. teardown(
  513. boost::beast::role_type role,
  514. ssl_stream<SyncStream>& stream,
  515. boost::system::error_code& ec);
  516. template<class AsyncStream, class TeardownHandler>
  517. friend
  518. void
  519. async_teardown(
  520. boost::beast::role_type role,
  521. ssl_stream<AsyncStream>& stream,
  522. TeardownHandler&& handler);
  523. #endif
  524. };
  525. #if ! BOOST_BEAST_DOXYGEN
  526. template<class SyncStream>
  527. void
  528. teardown(
  529. boost::beast::role_type role,
  530. ssl_stream<SyncStream>& stream,
  531. boost::system::error_code& ec)
  532. {
  533. // Just forward it to the underlying ssl::stream
  534. using boost::beast::websocket::teardown;
  535. teardown(role, *stream.p_, ec);
  536. }
  537. template<class AsyncStream, class TeardownHandler>
  538. void
  539. async_teardown(
  540. boost::beast::role_type role,
  541. ssl_stream<AsyncStream>& stream,
  542. TeardownHandler&& handler)
  543. {
  544. // Just forward it to the underlying ssl::stream
  545. using boost::beast::websocket::async_teardown;
  546. async_teardown(role, *stream.p_,
  547. std::forward<TeardownHandler>(handler));
  548. }
  549. #endif
  550. } // beast
  551. } // boost
  552. #endif