detect_ssl.hpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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_DETECT_SSL_HPP
  10. #define BOOST_BEAST_CORE_DETECT_SSL_HPP
  11. #include <boost/beast/core/detail/config.hpp>
  12. #include <boost/beast/core/async_base.hpp>
  13. #include <boost/beast/core/error.hpp>
  14. #include <boost/beast/core/read_size.hpp>
  15. #include <boost/beast/core/stream_traits.hpp>
  16. #include <boost/logic/tribool.hpp>
  17. #include <boost/asio/async_result.hpp>
  18. #include <boost/asio/coroutine.hpp>
  19. #include <type_traits>
  20. namespace boost {
  21. namespace beast {
  22. //------------------------------------------------------------------------------
  23. //
  24. // Example: Detect TLS client_hello
  25. //
  26. // This is an example and also a public interface. It implements
  27. // an algorithm for determining if a "TLS client_hello" message
  28. // is received. It can be used to implement a listening port that
  29. // can handle both plain and TLS encrypted connections.
  30. //
  31. //------------------------------------------------------------------------------
  32. //[example_core_detect_ssl_1
  33. // By convention, the "detail" namespace means "not-public."
  34. // Identifiers in a detail namespace are not visible in the documentation,
  35. // and users should not directly use those identifiers in programs, otherwise
  36. // their program may break in the future.
  37. //
  38. // Using a detail namespace gives the library writer the freedom to change
  39. // the interface or behavior later, and maintain backward-compatibility.
  40. namespace detail {
  41. /** Return `true` if the buffer contains a TLS Protocol client_hello message.
  42. This function analyzes the bytes at the beginning of the buffer
  43. and compares it to a valid client_hello message. This is the
  44. message required to be sent by a client at the beginning of
  45. any TLS (encrypted communication) session, including when
  46. resuming a session.
  47. The return value will be:
  48. @li `true` if the contents of the buffer unambiguously define
  49. contain a client_hello message,
  50. @li `false` if the contents of the buffer cannot possibly
  51. be a valid client_hello message, or
  52. @li `boost::indeterminate` if the buffer contains an
  53. insufficient number of bytes to determine the result. In
  54. this case the caller should read more data from the relevant
  55. stream, append it to the buffers, and call this function again.
  56. @param buffers The buffer sequence to inspect.
  57. This type must meet the requirements of <em>ConstBufferSequence</em>.
  58. @return `boost::tribool` indicating whether the buffer contains
  59. a TLS client handshake, does not contain a handshake, or needs
  60. additional bytes to determine an outcome.
  61. @see
  62. <a href="https://tools.ietf.org/html/rfc2246#section-7.4">7.4. Handshake protocol</a>
  63. (RFC2246: The TLS Protocol)
  64. */
  65. template <class ConstBufferSequence>
  66. boost::tribool
  67. is_tls_client_hello (ConstBufferSequence const& buffers);
  68. } // detail
  69. //]
  70. //[example_core_detect_ssl_2
  71. namespace detail {
  72. template <class ConstBufferSequence>
  73. boost::tribool
  74. is_tls_client_hello (ConstBufferSequence const& buffers)
  75. {
  76. // Make sure buffers meets the requirements
  77. static_assert(
  78. net::is_const_buffer_sequence<ConstBufferSequence>::value,
  79. "ConstBufferSequence type requirements not met");
  80. /*
  81. The first message on a TLS connection must be the client_hello,
  82. which is a type of handshake record, and it cannot be compressed
  83. or encrypted. A plaintext record has this format:
  84. 0 byte record_type // 0x16 = handshake
  85. 1 byte major // major protocol version
  86. 2 byte minor // minor protocol version
  87. 3-4 uint16 length // size of the payload
  88. 5 byte handshake_type // 0x01 = client_hello
  89. 6 uint24 length // size of the ClientHello
  90. 9 byte major // major protocol version
  91. 10 byte minor // minor protocol version
  92. 11 uint32 gmt_unix_time
  93. 15 byte random_bytes[28]
  94. ...
  95. */
  96. // Flatten the input buffers into a single contiguous range
  97. // of bytes on the stack to make it easier to work with the data.
  98. unsigned char buf[9];
  99. auto const n = net::buffer_copy(
  100. net::mutable_buffer(buf, sizeof(buf)), buffers);
  101. // Can't do much without any bytes
  102. if(n < 1)
  103. return boost::indeterminate;
  104. // Require the first byte to be 0x16, indicating a TLS handshake record
  105. if(buf[0] != 0x16)
  106. return false;
  107. // We need at least 5 bytes to know the record payload size
  108. if(n < 5)
  109. return boost::indeterminate;
  110. // Calculate the record payload size
  111. std::uint32_t const length = (buf[3] << 8) + buf[4];
  112. // A ClientHello message payload is at least 34 bytes.
  113. // There can be multiple handshake messages in the same record.
  114. if(length < 34)
  115. return false;
  116. // We need at least 6 bytes to know the handshake type
  117. if(n < 6)
  118. return boost::indeterminate;
  119. // The handshake_type must be 0x01 == client_hello
  120. if(buf[5] != 0x01)
  121. return false;
  122. // We need at least 9 bytes to know the payload size
  123. if(n < 9)
  124. return boost::indeterminate;
  125. // Calculate the message payload size
  126. std::uint32_t const size =
  127. (buf[6] << 16) + (buf[7] << 8) + buf[8];
  128. // The message payload can't be bigger than the enclosing record
  129. if(size + 4 > length)
  130. return false;
  131. // This can only be a TLS client_hello message
  132. return true;
  133. }
  134. } // detail
  135. //]
  136. //[example_core_detect_ssl_3
  137. /** Detect a TLS client handshake on a stream.
  138. This function reads from a stream to determine if a client
  139. handshake message is being received.
  140. The call blocks until one of the following is true:
  141. @li A TLS client opening handshake is detected,
  142. @li The received data is invalid for a TLS client handshake, or
  143. @li An error occurs.
  144. The algorithm, known as a <em>composed operation</em>, is implemented
  145. in terms of calls to the next layer's `read_some` function.
  146. Bytes read from the stream will be stored in the passed dynamic
  147. buffer, which may be used to perform the TLS handshake if the
  148. detector returns true, or be otherwise consumed by the caller based
  149. on the expected protocol.
  150. @param stream The stream to read from. This type must meet the
  151. requirements of <em>SyncReadStream</em>.
  152. @param buffer The dynamic buffer to use. This type must meet the
  153. requirements of <em>DynamicBuffer</em>.
  154. @param ec Set to the error if any occurred.
  155. @return `true` if the buffer contains a TLS client handshake and
  156. no error occurred, otherwise `false`.
  157. */
  158. template<
  159. class SyncReadStream,
  160. class DynamicBuffer>
  161. bool
  162. detect_ssl(
  163. SyncReadStream& stream,
  164. DynamicBuffer& buffer,
  165. error_code& ec)
  166. {
  167. namespace beast = boost::beast;
  168. // Make sure arguments meet the requirements
  169. static_assert(
  170. is_sync_read_stream<SyncReadStream>::value,
  171. "SyncReadStream type requirements not met");
  172. static_assert(
  173. net::is_dynamic_buffer<DynamicBuffer>::value,
  174. "DynamicBuffer type requirements not met");
  175. // Loop until an error occurs or we get a definitive answer
  176. for(;;)
  177. {
  178. // There could already be data in the buffer
  179. // so we do this first, before reading from the stream.
  180. auto const result = detail::is_tls_client_hello(buffer.data());
  181. // If we got an answer, return it
  182. if(! boost::indeterminate(result))
  183. {
  184. // A definite answer is a success
  185. ec = {};
  186. return static_cast<bool>(result);
  187. }
  188. // Try to fill our buffer by reading from the stream.
  189. // The function read_size calculates a reasonable size for the
  190. // amount to read next, using existing capacity if possible to
  191. // avoid allocating memory, up to the limit of 1536 bytes which
  192. // is the size of a normal TCP frame.
  193. std::size_t const bytes_transferred = stream.read_some(
  194. buffer.prepare(beast::read_size(buffer, 1536)), ec);
  195. // Commit what we read into the buffer's input area.
  196. buffer.commit(bytes_transferred);
  197. // Check for an error
  198. if(ec)
  199. break;
  200. }
  201. // error
  202. return false;
  203. }
  204. //]
  205. //[example_core_detect_ssl_4
  206. /** Detect a TLS/SSL handshake asynchronously on a stream.
  207. This function reads asynchronously from a stream to determine
  208. if a client handshake message is being received.
  209. This call always returns immediately. The asynchronous operation
  210. will continue until one of the following conditions is true:
  211. @li A TLS client opening handshake is detected,
  212. @li The received data is invalid for a TLS client handshake, or
  213. @li An error occurs.
  214. The algorithm, known as a <em>composed asynchronous operation</em>,
  215. is implemented in terms of calls to the next layer's `async_read_some`
  216. function. The program must ensure that no other calls to
  217. `async_read_some` are performed until this operation completes.
  218. Bytes read from the stream will be stored in the passed dynamic
  219. buffer, which may be used to perform the TLS handshake if the
  220. detector returns true, or be otherwise consumed by the caller based
  221. on the expected protocol.
  222. @param stream The stream to read from. This type must meet the
  223. requirements of <em>AsyncReadStream</em>.
  224. @param buffer The dynamic buffer to use. This type must meet the
  225. requirements of <em>DynamicBuffer</em>.
  226. @param token The completion token used to determine the method
  227. used to provide the result of the asynchronous operation. If
  228. this is a completion handler, the implementation takes ownership
  229. of the handler by performing a decay-copy, and the equivalent
  230. function signature of the handler must be:
  231. @code
  232. void handler(
  233. error_code const& error, // Set to the error, if any
  234. bool result // The result of the detector
  235. );
  236. @endcode
  237. Regardless of whether the asynchronous operation completes
  238. immediately or not, the handler will not be invoked from within
  239. this function. Invocation of the handler will be performed in a
  240. manner equivalent to using `net::post`.
  241. */
  242. template<
  243. class AsyncReadStream,
  244. class DynamicBuffer,
  245. class CompletionToken =
  246. net::default_completion_token_t<beast::executor_type<AsyncReadStream>>
  247. >
  248. #if BOOST_BEAST_DOXYGEN
  249. BOOST_ASIO_INITFN_RESULT_TYPE(CompletionToken, void(error_code, bool))
  250. #else
  251. auto
  252. #endif
  253. async_detect_ssl(
  254. AsyncReadStream& stream,
  255. DynamicBuffer& buffer,
  256. CompletionToken&& token = net::default_completion_token_t<
  257. beast::executor_type<AsyncReadStream>>{}) ->
  258. typename net::async_result<
  259. typename std::decay<CompletionToken>::type, /*< `async_result` customizes the return value based on the completion token >*/
  260. void(error_code, bool)>::return_type; /*< This is the signature for the completion handler >*/
  261. //]
  262. //[example_core_detect_ssl_5
  263. // These implementation details don't need to be public
  264. namespace detail {
  265. // The composed operation object
  266. template<
  267. class DetectHandler,
  268. class AsyncReadStream,
  269. class DynamicBuffer>
  270. class detect_ssl_op;
  271. // This is a function object which `net::async_initiate` can use to launch
  272. // our composed operation. This is a relatively new feature in networking
  273. // which allows the asynchronous operation to be "lazily" executed (meaning
  274. // that it is launched later). Users don't need to worry about this, but
  275. // authors of composed operations need to write it this way to get the
  276. // very best performance, for example when using Coroutines TS (`co_await`).
  277. struct run_detect_ssl_op
  278. {
  279. // The implementation of `net::async_initiate` captures the
  280. // arguments of the initiating function, and then calls this
  281. // function object later with the captured arguments in order
  282. // to launch the composed operation. All we need to do here
  283. // is take those arguments and construct our composed operation
  284. // object.
  285. //
  286. // `async_initiate` takes care of transforming the completion
  287. // token into the "real handler" which must have the correct
  288. // signature, in this case `void(error_code, boost::tri_bool)`.
  289. template<
  290. class DetectHandler,
  291. class AsyncReadStream,
  292. class DynamicBuffer>
  293. void operator()(
  294. DetectHandler&& h,
  295. AsyncReadStream* s, // references are passed as pointers
  296. DynamicBuffer& b)
  297. {
  298. detect_ssl_op<
  299. typename std::decay<DetectHandler>::type,
  300. AsyncReadStream,
  301. DynamicBuffer>(
  302. std::forward<DetectHandler>(h), *s, b);
  303. }
  304. };
  305. } // detail
  306. //]
  307. //[example_core_detect_ssl_6
  308. // Here is the implementation of the asynchronous initiation function
  309. template<
  310. class AsyncReadStream,
  311. class DynamicBuffer,
  312. class CompletionToken>
  313. #if BOOST_BEAST_DOXYGEN
  314. BOOST_ASIO_INITFN_RESULT_TYPE(CompletionToken, void(error_code, bool))
  315. #else
  316. auto
  317. #endif
  318. async_detect_ssl(
  319. AsyncReadStream& stream,
  320. DynamicBuffer& buffer,
  321. CompletionToken&& token)
  322. -> typename net::async_result<
  323. typename std::decay<CompletionToken>::type,
  324. void(error_code, bool)>::return_type
  325. {
  326. // Make sure arguments meet the type requirements
  327. static_assert(
  328. is_async_read_stream<AsyncReadStream>::value,
  329. "SyncReadStream type requirements not met");
  330. static_assert(
  331. net::is_dynamic_buffer<DynamicBuffer>::value,
  332. "DynamicBuffer type requirements not met");
  333. // The function `net::async_initate` uses customization points
  334. // to allow one asynchronous initiating function to work with
  335. // all sorts of notification systems, such as callbacks but also
  336. // fibers, futures, coroutines, and user-defined types.
  337. //
  338. // It works by capturing all of the arguments using perfect
  339. // forwarding, and then depending on the specialization of
  340. // `net::async_result` for the type of `CompletionToken`,
  341. // the `initiation` object will be invoked with the saved
  342. // parameters and the actual completion handler. Our
  343. // initiating object is `run_detect_ssl_op`.
  344. //
  345. // Non-const references need to be passed as pointers,
  346. // since we don't want a decay-copy.
  347. return net::async_initiate<
  348. CompletionToken,
  349. void(error_code, bool)>(
  350. detail::run_detect_ssl_op{},
  351. token,
  352. &stream, // pass the reference by pointer
  353. buffer);
  354. }
  355. //]
  356. //[example_core_detect_ssl_7
  357. namespace detail {
  358. // Read from a stream, calling is_tls_client_hello on the data
  359. // data to determine if the TLS client handshake is present.
  360. //
  361. // This will be implemented using Asio's "stackless coroutines"
  362. // which are based on macros forming a switch statement. The
  363. // operation is derived from `coroutine` for this reason.
  364. //
  365. // The library type `async_base` takes care of all of the
  366. // boilerplate for writing composed operations, including:
  367. //
  368. // * Storing the user's completion handler
  369. // * Maintaining the work guard for the handler's associated executor
  370. // * Propagating the associated allocator of the handler
  371. // * Propagating the associated executor of the handler
  372. // * Deallocating temporary storage before invoking the handler
  373. // * Posting the handler to the executor on an immediate completion
  374. //
  375. // `async_base` needs to know the type of the handler, as well
  376. // as the executor of the I/O object being used. The metafunction
  377. // `executor_type` returns the type of executor used by an
  378. // I/O object.
  379. //
  380. template<
  381. class DetectHandler,
  382. class AsyncReadStream,
  383. class DynamicBuffer>
  384. class detect_ssl_op
  385. : public boost::asio::coroutine
  386. , public async_base<
  387. DetectHandler, executor_type<AsyncReadStream>>
  388. {
  389. // This composed operation has trivial state,
  390. // so it is just kept inside the class and can
  391. // be cheaply copied as needed by the implementation.
  392. AsyncReadStream& stream_;
  393. // The callers buffer is used to hold all received data
  394. DynamicBuffer& buffer_;
  395. // We're going to need this in case we have to post the handler
  396. error_code ec_;
  397. boost::tribool result_ = false;
  398. public:
  399. // Completion handlers must be MoveConstructible.
  400. detect_ssl_op(detect_ssl_op&&) = default;
  401. // Construct the operation. The handler is deduced through
  402. // the template type `DetectHandler_`, this lets the same constructor
  403. // work properly for both lvalues and rvalues.
  404. //
  405. template<class DetectHandler_>
  406. detect_ssl_op(
  407. DetectHandler_&& handler,
  408. AsyncReadStream& stream,
  409. DynamicBuffer& buffer)
  410. : beast::async_base<
  411. DetectHandler,
  412. beast::executor_type<AsyncReadStream>>(
  413. std::forward<DetectHandler_>(handler),
  414. stream.get_executor())
  415. , stream_(stream)
  416. , buffer_(buffer)
  417. {
  418. // This starts the operation. We pass `false` to tell the
  419. // algorithm that it needs to use net::post if it wants to
  420. // complete immediately. This is required by Networking,
  421. // as initiating functions are not allowed to invoke the
  422. // completion handler on the caller's thread before
  423. // returning.
  424. (*this)({}, 0, false);
  425. }
  426. // Our main entry point. This will get called as our
  427. // intermediate operations complete. Definition below.
  428. //
  429. // The parameter `cont` indicates if we are being called subsequently
  430. // from the original invocation
  431. //
  432. void operator()(
  433. error_code ec,
  434. std::size_t bytes_transferred,
  435. bool cont = true);
  436. };
  437. } // detail
  438. //]
  439. //[example_core_detect_ssl_8
  440. namespace detail {
  441. // This example uses the Asio's stackless "fauxroutines", implemented
  442. // using a macro-based solution. It makes the code easier to write and
  443. // easier to read. This include file defines the necessary macros and types.
  444. #include <boost/asio/yield.hpp>
  445. // detect_ssl_op is callable with the signature void(error_code, bytes_transferred),
  446. // allowing `*this` to be used as a ReadHandler
  447. //
  448. template<
  449. class AsyncStream,
  450. class DynamicBuffer,
  451. class Handler>
  452. void
  453. detect_ssl_op<AsyncStream, DynamicBuffer, Handler>::
  454. operator()(error_code ec, std::size_t bytes_transferred, bool cont)
  455. {
  456. namespace beast = boost::beast;
  457. // This introduces the scope of the stackless coroutine
  458. reenter(*this)
  459. {
  460. // Loop until an error occurs or we get a definitive answer
  461. for(;;)
  462. {
  463. // There could already be a hello in the buffer so check first
  464. result_ = is_tls_client_hello(buffer_.data());
  465. // If we got an answer, then the operation is complete
  466. if(! boost::indeterminate(result_))
  467. break;
  468. // Try to fill our buffer by reading from the stream.
  469. // The function read_size calculates a reasonable size for the
  470. // amount to read next, using existing capacity if possible to
  471. // avoid allocating memory, up to the limit of 1536 bytes which
  472. // is the size of a normal TCP frame.
  473. //
  474. // `async_read_some` expects a ReadHandler as the completion
  475. // handler. The signature of a read handler is void(error_code, size_t),
  476. // and this function matches that signature (the `cont` parameter has
  477. // a default of true). We pass `std::move(*this)` as the completion
  478. // handler for the read operation. This transfers ownership of this
  479. // entire state machine back into the `async_read_some` operation.
  480. // Care must be taken with this idiom, to ensure that parameters
  481. // passed to the initiating function which could be invalidated
  482. // by the move, are first moved to the stack before calling the
  483. // initiating function.
  484. yield stream_.async_read_some(buffer_.prepare(
  485. read_size(buffer_, 1536)), std::move(*this));
  486. // Commit what we read into the buffer's input area.
  487. buffer_.commit(bytes_transferred);
  488. // Check for an error
  489. if(ec)
  490. break;
  491. }
  492. // If `cont` is true, the handler will be invoked directly.
  493. //
  494. // Otherwise, the handler cannot be invoked directly, because
  495. // initiating functions are not allowed to call the handler
  496. // before returning. Instead, the handler must be posted to
  497. // the I/O context. We issue a zero-byte read using the same
  498. // type of buffers used in the ordinary read above, to prevent
  499. // the compiler from creating an extra instantiation of the
  500. // function template. This reduces compile times and the size
  501. // of the program executable.
  502. if(! cont)
  503. {
  504. // Save the error, otherwise it will be overwritten with
  505. // a successful error code when this read completes
  506. // immediately.
  507. ec_ = ec;
  508. // Zero-byte reads and writes are guaranteed to complete
  509. // immediately with succcess. The type of buffers and the
  510. // type of handler passed here need to exactly match the types
  511. // used in the call to async_read_some above, to avoid
  512. // instantiating another version of the function template.
  513. yield stream_.async_read_some(buffer_.prepare(0), std::move(*this));
  514. // Restore the saved error code
  515. ec = ec_;
  516. }
  517. // Invoke the final handler.
  518. // At this point, we are guaranteed that the original initiating
  519. // function is no longer on our stack frame.
  520. this->complete_now(ec, static_cast<bool>(result_));
  521. }
  522. }
  523. // Including this file undefines the macros used by the stackless fauxroutines.
  524. #include <boost/asio/unyield.hpp>
  525. } // detail
  526. //]
  527. } // beast
  528. } // boost
  529. #endif