detect_ssl.hpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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. If the handler has an associated immediate executor,
  238. an immediate completion will be dispatched to it.
  239. Otherwise, the handler will not be invoked from within
  240. this function. Invocation of the handler will be performed in a
  241. manner equivalent to using `net::post`.
  242. */
  243. template<
  244. class AsyncReadStream,
  245. class DynamicBuffer,
  246. class CompletionToken =
  247. net::default_completion_token_t<beast::executor_type<AsyncReadStream>>
  248. >
  249. BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void(error_code, bool))
  250. async_detect_ssl(
  251. AsyncReadStream& stream,
  252. DynamicBuffer& buffer,
  253. CompletionToken&& token = net::default_completion_token_t<
  254. beast::executor_type<AsyncReadStream>>{});
  255. //]
  256. //[example_core_detect_ssl_5
  257. // These implementation details don't need to be public
  258. namespace detail {
  259. // The composed operation object
  260. template<
  261. class DetectHandler,
  262. class AsyncReadStream,
  263. class DynamicBuffer>
  264. class detect_ssl_op;
  265. // This is a function object which `net::async_initiate` can use to launch
  266. // our composed operation. This is a relatively new feature in networking
  267. // which allows the asynchronous operation to be "lazily" executed (meaning
  268. // that it is launched later). Users don't need to worry about this, but
  269. // authors of composed operations need to write it this way to get the
  270. // very best performance, for example when using Coroutines TS (`co_await`).
  271. template <typename AsyncReadStream>
  272. struct run_detect_ssl_op
  273. {
  274. // The implementation of `net::async_initiate` captures the
  275. // arguments of the initiating function, and then calls this
  276. // function object later with the captured arguments in order
  277. // to launch the composed operation. All we need to do here
  278. // is take those arguments and construct our composed operation
  279. // object.
  280. //
  281. // `async_initiate` takes care of transforming the completion
  282. // token into the "real handler" which must have the correct
  283. // signature, in this case `void(error_code, boost::tri_bool)`.
  284. AsyncReadStream* stream;
  285. using executor_type = typename AsyncReadStream::executor_type;
  286. executor_type
  287. get_executor() const noexcept
  288. {
  289. return stream->get_executor();
  290. }
  291. template<
  292. class DetectHandler,
  293. class DynamicBuffer>
  294. void
  295. operator()(
  296. DetectHandler&& h,
  297. DynamicBuffer* b)
  298. {
  299. detect_ssl_op<
  300. typename std::decay<DetectHandler>::type,
  301. AsyncReadStream,
  302. DynamicBuffer>(
  303. std::forward<DetectHandler>(h), *stream, *b);
  304. }
  305. };
  306. } // detail
  307. //]
  308. //[example_core_detect_ssl_6
  309. // Here is the implementation of the asynchronous initiation function
  310. template<
  311. class AsyncReadStream,
  312. class DynamicBuffer,
  313. class CompletionToken>
  314. BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void(error_code, bool))
  315. async_detect_ssl(
  316. AsyncReadStream& stream,
  317. DynamicBuffer& buffer,
  318. CompletionToken&& token)
  319. {
  320. // Make sure arguments meet the type requirements
  321. static_assert(
  322. is_async_read_stream<AsyncReadStream>::value,
  323. "SyncReadStream type requirements not met");
  324. static_assert(
  325. net::is_dynamic_buffer<DynamicBuffer>::value,
  326. "DynamicBuffer type requirements not met");
  327. // The function `net::async_initate` uses customization points
  328. // to allow one asynchronous initiating function to work with
  329. // all sorts of notification systems, such as callbacks but also
  330. // fibers, futures, coroutines, and user-defined types.
  331. //
  332. // It works by capturing all of the arguments using perfect
  333. // forwarding, and then depending on the specialization of
  334. // `net::async_result` for the type of `CompletionToken`,
  335. // the `initiation` object will be invoked with the saved
  336. // parameters and the actual completion handler. Our
  337. // initiating object is `run_detect_ssl_op`.
  338. //
  339. // Non-const references need to be passed as pointers,
  340. // since we don't want a decay-copy.
  341. return net::async_initiate<
  342. CompletionToken,
  343. void(error_code, bool)>(
  344. detail::run_detect_ssl_op<AsyncReadStream>{&stream},
  345. token,
  346. &buffer);
  347. }
  348. //]
  349. //[example_core_detect_ssl_7
  350. namespace detail {
  351. // Read from a stream, calling is_tls_client_hello on the data
  352. // data to determine if the TLS client handshake is present.
  353. //
  354. // This will be implemented using Asio's "stackless coroutines"
  355. // which are based on macros forming a switch statement. The
  356. // operation is derived from `coroutine` for this reason.
  357. //
  358. // The library type `async_base` takes care of all of the
  359. // boilerplate for writing composed operations, including:
  360. //
  361. // * Storing the user's completion handler
  362. // * Maintaining the work guard for the handler's associated executor
  363. // * Propagating the associated allocator of the handler
  364. // * Propagating the associated executor of the handler
  365. // * Deallocating temporary storage before invoking the handler
  366. // * Posting the handler to the executor on an immediate completion
  367. //
  368. // `async_base` needs to know the type of the handler, as well
  369. // as the executor of the I/O object being used. The metafunction
  370. // `executor_type` returns the type of executor used by an
  371. // I/O object.
  372. //
  373. template<
  374. class DetectHandler,
  375. class AsyncReadStream,
  376. class DynamicBuffer>
  377. class detect_ssl_op
  378. : public boost::asio::coroutine
  379. , public async_base<
  380. DetectHandler, executor_type<AsyncReadStream>>
  381. {
  382. // This composed operation has trivial state,
  383. // so it is just kept inside the class and can
  384. // be cheaply copied as needed by the implementation.
  385. AsyncReadStream& stream_;
  386. // The callers buffer is used to hold all received data
  387. DynamicBuffer& buffer_;
  388. // We're going to need this in case we have to post the handler
  389. error_code ec_;
  390. boost::tribool result_ = false;
  391. public:
  392. // Completion handlers must be MoveConstructible.
  393. detect_ssl_op(detect_ssl_op&&) = default;
  394. // Construct the operation. The handler is deduced through
  395. // the template type `DetectHandler_`, this lets the same constructor
  396. // work properly for both lvalues and rvalues.
  397. //
  398. template<class DetectHandler_>
  399. detect_ssl_op(
  400. DetectHandler_&& handler,
  401. AsyncReadStream& stream,
  402. DynamicBuffer& buffer)
  403. : beast::async_base<
  404. DetectHandler,
  405. beast::executor_type<AsyncReadStream>>(
  406. std::forward<DetectHandler_>(handler),
  407. stream.get_executor())
  408. , stream_(stream)
  409. , buffer_(buffer)
  410. {
  411. // This starts the operation. We pass `false` to tell the
  412. // algorithm that it needs to use net::post if it wants to
  413. // complete immediately. This is required by Networking,
  414. // as initiating functions are not allowed to invoke the
  415. // completion handler on the caller's thread before
  416. // returning.
  417. (*this)({}, 0, false);
  418. }
  419. // Our main entry point. This will get called as our
  420. // intermediate operations complete. Definition below.
  421. //
  422. // The parameter `cont` indicates if we are being called subsequently
  423. // from the original invocation
  424. //
  425. void operator()(
  426. error_code ec,
  427. std::size_t bytes_transferred,
  428. bool cont = true);
  429. };
  430. } // detail
  431. //]
  432. //[example_core_detect_ssl_8
  433. namespace detail {
  434. // This example uses the Asio's stackless "fauxroutines", implemented
  435. // using a macro-based solution. It makes the code easier to write and
  436. // easier to read. This include file defines the necessary macros and types.
  437. #include <boost/asio/yield.hpp>
  438. // detect_ssl_op is callable with the signature void(error_code, bytes_transferred),
  439. // allowing `*this` to be used as a ReadHandler
  440. //
  441. template<
  442. class AsyncStream,
  443. class DynamicBuffer,
  444. class Handler>
  445. void
  446. detect_ssl_op<AsyncStream, DynamicBuffer, Handler>::
  447. operator()(error_code ec, std::size_t bytes_transferred, bool cont)
  448. {
  449. namespace beast = boost::beast;
  450. // This introduces the scope of the stackless coroutine
  451. reenter(*this)
  452. {
  453. // Loop until an error occurs or we get a definitive answer
  454. for(;;)
  455. {
  456. // There could already be a hello in the buffer so check first
  457. result_ = is_tls_client_hello(buffer_.data());
  458. // If we got an answer, then the operation is complete
  459. if(! boost::indeterminate(result_))
  460. break;
  461. // Try to fill our buffer by reading from the stream.
  462. // The function read_size calculates a reasonable size for the
  463. // amount to read next, using existing capacity if possible to
  464. // avoid allocating memory, up to the limit of 1536 bytes which
  465. // is the size of a normal TCP frame.
  466. //
  467. // `async_read_some` expects a ReadHandler as the completion
  468. // handler. The signature of a read handler is void(error_code, size_t),
  469. // and this function matches that signature (the `cont` parameter has
  470. // a default of true). We pass `std::move(*this)` as the completion
  471. // handler for the read operation. This transfers ownership of this
  472. // entire state machine back into the `async_read_some` operation.
  473. // Care must be taken with this idiom, to ensure that parameters
  474. // passed to the initiating function which could be invalidated
  475. // by the move, are first moved to the stack before calling the
  476. // initiating function.
  477. yield
  478. {
  479. // This macro facilitates asynchrnous handler tracking and
  480. // debugging when the preprocessor macro
  481. // BOOST_ASIO_CUSTOM_HANDLER_TRACKING is defined.
  482. BOOST_ASIO_HANDLER_LOCATION((
  483. __FILE__, __LINE__,
  484. "async_detect_ssl"));
  485. stream_.async_read_some(buffer_.prepare(
  486. read_size(buffer_, 1536)), std::move(*this));
  487. }
  488. // Commit what we read into the buffer's input area.
  489. buffer_.commit(bytes_transferred);
  490. // Check for an error
  491. if(ec)
  492. break;
  493. }
  494. // If `cont` is true, the handler will be invoked directly.
  495. //
  496. // Otherwise, the handler cannot be invoked directly, because
  497. // initiating functions are not allowed to call the handler
  498. // before returning. Instead, the handler must be posted to
  499. // the I/O context. We issue a zero-byte read using the same
  500. // type of buffers used in the ordinary read above, to prevent
  501. // the compiler from creating an extra instantiation of the
  502. // function template. This reduces compile times and the size
  503. // of the program executable.
  504. if(! cont)
  505. {
  506. // Save the error, otherwise it will be overwritten with
  507. // a successful error code when this read completes
  508. // immediately.
  509. ec_ = ec;
  510. // Zero-byte reads and writes are guaranteed to complete
  511. // immediately with succcess. The type of buffers and the
  512. // type of handler passed here need to exactly match the types
  513. // used in the call to async_read_some above, to avoid
  514. // instantiating another version of the function template.
  515. yield
  516. {
  517. BOOST_ASIO_HANDLER_LOCATION((
  518. __FILE__, __LINE__,
  519. "async_detect_ssl"));
  520. stream_.async_read_some(buffer_.prepare(0), std::move(*this));
  521. }
  522. // Restore the saved error code
  523. BOOST_BEAST_ASSIGN_EC(ec, ec_);
  524. }
  525. // Invoke the final handler.
  526. // At this point, we are guaranteed that the original initiating
  527. // function is no longer on our stack frame.
  528. this->complete_now(ec, static_cast<bool>(result_));
  529. }
  530. }
  531. // Including this file undefines the macros used by the stackless fauxroutines.
  532. #include <boost/asio/unyield.hpp>
  533. } // detail
  534. //]
  535. } // beast
  536. } // boost
  537. #endif