Botan 3.4.0
Crypto and TLS for C&
asio_stream.h
Go to the documentation of this file.
1/*
2* TLS ASIO Stream
3* (C) 2018-2021 Jack Lloyd
4* 2018-2021 Hannes Rantzsch, Tim Oesterreich, Rene Meusel
5* 2023 Fabian Albert, René Meusel - Rohde & Schwarz Cybersecurity
6*
7* Botan is released under the Simplified BSD License (see license.txt)
8*/
9
10#ifndef BOTAN_ASIO_STREAM_H_
11#define BOTAN_ASIO_STREAM_H_
12
13#include <botan/asio_compat.h>
14#if !defined(BOTAN_FOUND_COMPATIBLE_BOOST_ASIO_VERSION)
15 #error Available boost headers are too old for the boost asio stream.
16#else
17
18 #include <botan/asio_async_ops.h>
19 #include <botan/asio_context.h>
20 #include <botan/asio_error.h>
21
22 #include <botan/tls_callbacks.h>
23 #include <botan/tls_channel.h>
24 #include <botan/tls_client.h>
25 #include <botan/tls_magic.h>
26 #include <botan/tls_server.h>
27
28 // We need to define BOOST_ASIO_DISABLE_SERIAL_PORT before any asio imports. Otherwise asio will include <termios.h>,
29 // which interferes with Botan's amalgamation by defining macros like 'B0' and 'FF1'.
30 #define BOOST_ASIO_DISABLE_SERIAL_PORT
31 #include <boost/asio.hpp>
32 #include <boost/beast/core.hpp>
33
34 #include <algorithm>
35 #include <memory>
36 #include <type_traits>
37
38namespace Botan::TLS {
39
40template <class SL, class C>
41class Stream;
42
43/**
44 * @brief Specialization of TLS::Callbacks for the ASIO Stream
45 *
46 * Applications may decide to derive from this for fine-grained customizations
47 * of the TLS::Stream's behaviour. Examples may be OCSP integration, custom
48 * certificate validation or user-defined key exchange mechanisms.
49 *
50 * By default, this class provides all necessary customizations for the ASIO
51 * integration. The methods required for that are `final` and cannot be
52 * overridden.
53 *
54 * Each instance of TLS::Stream must have their own instance of this class. A
55 * future major version of Botan will therefor consume instances of this class
56 * as a std::unique_ptr. The current usage of std::shared_ptr is erratic.
57 */
58class StreamCallbacks : public Callbacks {
59 public:
60 StreamCallbacks() {}
61
62 void tls_emit_data(std::span<const uint8_t> data) final {
63 m_send_buffer.commit(boost::asio::buffer_copy(m_send_buffer.prepare(data.size()),
64 boost::asio::buffer(data.data(), data.size())));
65 }
66
67 void tls_record_received(uint64_t, std::span<const uint8_t> data) final {
68 m_receive_buffer.commit(boost::asio::buffer_copy(m_receive_buffer.prepare(data.size()),
69 boost::asio::const_buffer(data.data(), data.size())));
70 }
71
72 bool tls_peer_closed_connection() final {
73 // Instruct the TLS implementation to reply with our close_notify to
74 // obtain the same behaviour for TLS 1.2 and TLS 1.3. Currently, this
75 // prevents a downstream application from closing their write-end while
76 // allowing the peer to continue writing.
77 //
78 // When lifting this limitation, please take good note of the "Future
79 // work" remarks in https://github.com/randombit/botan/pull/3801.
80 return true;
81 }
82
83 /**
84 * @param alert a TLS alert sent by the peer
85 */
86 void tls_alert(TLS::Alert alert) final {
87 if(alert.is_fatal() || alert.type() == TLS::AlertType::CloseNotify) {
88 // TLS alerts received from the peer are not passed to the
89 // downstream application immediately. Instead, we retain them here
90 // and the stream invokes `handle_tls_protocol_errors()` in due time
91 // to handle them.
92 m_alert_from_peer = alert;
93 }
94 }
95
96 void tls_verify_cert_chain(const std::vector<X509_Certificate>& cert_chain,
97 const std::vector<std::optional<OCSP::Response>>& ocsp_responses,
98 const std::vector<Certificate_Store*>& trusted_roots,
99 Usage_Type usage,
100 std::string_view hostname,
101 const TLS::Policy& policy) override {
102 auto ctx = m_context.lock();
103
104 if(ctx && ctx->has_verify_callback()) {
105 ctx->get_verify_callback()(cert_chain, ocsp_responses, trusted_roots, usage, hostname, policy);
106 } else {
107 Callbacks::tls_verify_cert_chain(cert_chain, ocsp_responses, trusted_roots, usage, hostname, policy);
108 }
109 }
110
111 private:
112 // The members below are meant for the tightly-coupled Stream class only
113 template <class SL, class C>
114 friend class Stream;
115
116 void set_context(std::weak_ptr<Botan::TLS::Context> context) { m_context = std::move(context); }
117
118 void consume_send_buffer() { m_send_buffer.consume(m_send_buffer.size()); }
119
120 boost::beast::flat_buffer& send_buffer() { return m_send_buffer; }
121
122 const boost::beast::flat_buffer& send_buffer() const { return m_send_buffer; }
123
124 boost::beast::flat_buffer& receive_buffer() { return m_receive_buffer; }
125
126 const boost::beast::flat_buffer& receive_buffer() const { return m_receive_buffer; }
127
128 bool shutdown_received() const {
129 return m_alert_from_peer && m_alert_from_peer->type() == AlertType::CloseNotify;
130 }
131
132 std::optional<Alert> alert_from_peer() const { return m_alert_from_peer; }
133
134 private:
135 std::optional<Alert> m_alert_from_peer;
136 boost::beast::flat_buffer m_receive_buffer;
137 boost::beast::flat_buffer m_send_buffer;
138
139 std::weak_ptr<TLS::Context> m_context;
140};
141
142namespace detail {
143
144template <typename T>
145concept basic_completion_token = boost::asio::completion_token_for<T, void(boost::system::error_code)>;
146
147template <typename T>
148concept byte_size_completion_token = boost::asio::completion_token_for<T, void(boost::system::error_code, size_t)>;
149
150} // namespace detail
151
152/**
153 * @brief boost::asio compatible SSL/TLS stream
154 *
155 * @tparam StreamLayer type of the next layer, usually a network socket
156 * @tparam ChannelT type of the native_handle, defaults to TLS::Channel, only needed for testing purposes
157 */
158template <class StreamLayer, class ChannelT = Channel>
159class Stream {
160 private:
161 using default_completion_token =
162 boost::asio::default_completion_token_t<boost::beast::executor_type<StreamLayer>>;
163
164 public:
165 //! \name construction
166 //! @{
167
168 /**
169 * @brief Construct a new Stream with a customizable instance of Callbacks
170 *
171 * @param context The context parameter is used to set up the underlying native handle.
172 * @param callbacks The callbacks parameter may contain an instance of a derived TLS::Callbacks
173 * class to allow for fine-grained customization of the TLS stream. Note that
174 * applications need to ensure a 1-to-1 relationship between instances of
175 * Callbacks and Streams. A future major version of Botan will use a unique_ptr
176 * here.
177 *
178 * @param args Arguments to be forwarded to the construction of the next layer.
179 */
180 template <typename... Args>
181 explicit Stream(std::shared_ptr<Context> context, std::shared_ptr<StreamCallbacks> callbacks, Args&&... args) :
182 m_context(std::move(context)),
183 m_nextLayer(std::forward<Args>(args)...),
184 m_core(std::move(callbacks)),
185 m_input_buffer_space(MAX_CIPHERTEXT_SIZE, '\0'),
186 m_input_buffer(m_input_buffer_space.data(), m_input_buffer_space.size()) {
187 m_core->set_context(m_context);
188 }
189
190 /**
191 * @brief Construct a new Stream
192 *
193 * @param context The context parameter is used to set up the underlying native handle.
194 * @param args Arguments to be forwarded to the construction of the next layer.
195 */
196 template <typename... Args>
197 explicit Stream(std::shared_ptr<Context> context, Args&&... args) :
198 Stream(std::move(context), std::make_shared<StreamCallbacks>(), std::forward<Args>(args)...) {}
199
200 /**
201 * @brief Construct a new Stream
202 *
203 * Convenience overload for boost::asio::ssl::stream compatibility.
204 *
205 * @param arg This argument is forwarded to the construction of the next layer.
206 * @param context The context parameter is used to set up the underlying native handle.
207 * @param callbacks The (optional) callbacks object that the stream should use. Note that
208 * applications need to ensure a 1-to-1 relationship between instances of Callbacks
209 * and Streams. A future major version of Botan will use a unique_ptr here.
210 */
211 template <typename Arg>
212 explicit Stream(Arg&& arg,
213 std::shared_ptr<Context> context,
214 std::shared_ptr<StreamCallbacks> callbacks = std::make_shared<StreamCallbacks>()) :
215 Stream(std::move(context), std::move(callbacks), std::forward<Arg>(arg)) {}
216
217 virtual ~Stream() = default;
218
219 Stream(Stream&& other) = default;
220 Stream& operator=(Stream&& other) = default;
221
222 Stream(const Stream& other) = delete;
223 Stream& operator=(const Stream& other) = delete;
224
225 //! @}
226 //! \name boost::asio accessor methods
227 //! @{
228
229 using next_layer_type = typename std::remove_reference<StreamLayer>::type;
230
231 const next_layer_type& next_layer() const { return m_nextLayer; }
232
233 next_layer_type& next_layer() { return m_nextLayer; }
234
235 using lowest_layer_type = typename boost::beast::lowest_layer_type<StreamLayer>;
236
237 lowest_layer_type& lowest_layer() { return boost::beast::get_lowest_layer(m_nextLayer); }
238
239 const lowest_layer_type& lowest_layer() const { return boost::beast::get_lowest_layer(m_nextLayer); }
240
241 using executor_type = typename next_layer_type::executor_type;
242
243 executor_type get_executor() noexcept { return m_nextLayer.get_executor(); }
244
245 using native_handle_type = typename std::add_pointer<ChannelT>::type;
246
247 native_handle_type native_handle() {
248 BOTAN_STATE_CHECK(m_native_handle != nullptr);
249 return m_native_handle.get();
250 }
251
252 //! @}
253 //! \name configuration and callback setters
254 //! @{
255
256 /**
257 * @brief Override the tls_verify_cert_chain callback
258 *
259 * This changes the verify_callback in the stream's TLS::Context, and hence the tls_verify_cert_chain callback
260 * used in the handshake.
261 * Using this function is equivalent to setting the callback via @see Botan::TLS::Context::set_verify_callback
262 *
263 * @note This function should only be called before initiating the TLS handshake
264 */
265 void set_verify_callback(Context::Verify_Callback callback) {
266 m_context->set_verify_callback(std::move(callback));
267 }
268
269 /**
270 * @brief Compatibility overload of @ref set_verify_callback
271 *
272 * @param callback the callback implementation
273 * @param ec This parameter is unused.
274 */
275 void set_verify_callback(Context::Verify_Callback callback, boost::system::error_code& ec) {
276 BOTAN_UNUSED(ec);
277 m_context->set_verify_callback(std::move(callback));
278 }
279
280 //! @throws Not_Implemented
281 void set_verify_depth(int depth) {
282 BOTAN_UNUSED(depth);
283 throw Not_Implemented("set_verify_depth is not implemented");
284 }
285
286 /**
287 * Not Implemented.
288 * @param depth the desired verification depth
289 * @param ec Will be set to `Botan::ErrorType::NotImplemented`
290 */
291 void set_verify_depth(int depth, boost::system::error_code& ec) {
292 BOTAN_UNUSED(depth);
293 ec = ErrorType::NotImplemented;
294 }
295
296 //! @throws Not_Implemented
297 template <typename verify_mode>
298 void set_verify_mode(verify_mode v) {
299 BOTAN_UNUSED(v);
300 throw Not_Implemented("set_verify_mode is not implemented");
301 }
302
303 /**
304 * Not Implemented.
305 * @param v the desired verify mode
306 * @param ec Will be set to `Botan::ErrorType::NotImplemented`
307 */
308 template <typename verify_mode>
309 void set_verify_mode(verify_mode v, boost::system::error_code& ec) {
310 BOTAN_UNUSED(v);
311 ec = ErrorType::NotImplemented;
312 }
313
314 //! @}
315 //! \name handshake methods
316 //! @{
317
318 /**
319 * @brief Performs SSL handshaking.
320 *
321 * The function call will block until handshaking is complete or an error occurs.
322 *
323 * @param side The type of handshaking to be performed, i.e. as a client or as a server.
324 * @throws boost::system::system_error if error occured
325 */
326 void handshake(Connection_Side side) {
327 boost::system::error_code ec;
328 handshake(side, ec);
329 boost::asio::detail::throw_error(ec, "handshake");
330 }
331
332 /**
333 * @brief Performs SSL handshaking.
334 *
335 * The function call will block until handshaking is complete or an error occurs.
336 *
337 * @param side The type of handshaking to be performed, i.e. as a client or as a server.
338 * @param ec Set to indicate what error occurred, if any.
339 */
340 void handshake(Connection_Side side, boost::system::error_code& ec) {
341 setup_native_handle(side, ec);
342
343 // We write to the socket if we have data to send and read from it
344 // otherwise, until either some error occured or we have successfully
345 // performed the handshake.
346 while(!ec) {
347 // Send pending data to the peer and abort the handshake if that
348 // fails with a network error. We do that first, to allow sending
349 // any final message before reporting the handshake as "finished".
350 if(has_data_to_send()) {
351 send_pending_encrypted_data(ec);
352 }
353
354 // Once the underlying TLS implementation reports a complete and
355 // successful handshake we're done.
356 if(native_handle()->is_handshake_complete()) {
357 return;
358 }
359
360 // Handle and report any TLS protocol errors that might have
361 // surfaced in a previous iteration. By postponing their handling we
362 // allow the stream to send a respective TLS alert to the peer before
363 // aborting the handshake.
364 handle_tls_protocol_errors(ec);
365
366 // If we don't have any encrypted data to send we attempt to read
367 // more data from the peer. This reports network errors immediately.
368 // TLS protocol errors result in an internal state change which is
369 // handled by `handle_tls_protocol_errors()` in the next iteration.
370 read_and_process_encrypted_data_from_peer(ec);
371 }
372
373 BOTAN_ASSERT_NOMSG(ec.failed());
374 }
375
376 /**
377 * @brief Starts an asynchronous SSL handshake.
378 *
379 * This function call always returns immediately.
380 *
381 * @param side The type of handshaking to be performed, i.e. as a client or as a server.
382 * @param completion_token The completion handler to be called when the handshake operation completes.
383 * The completion signature of the handler must be: void(boost::system::error_code).
384 */
385 template <detail::basic_completion_token CompletionToken = default_completion_token>
386 auto async_handshake(Botan::TLS::Connection_Side side,
387 CompletionToken&& completion_token = default_completion_token{}) {
388 return boost::asio::async_initiate<CompletionToken, void(boost::system::error_code)>(
389 [this](auto&& completion_handler, TLS::Connection_Side connection_side) {
390 using completion_handler_t = std::decay_t<decltype(completion_handler)>;
391
392 boost::system::error_code ec;
393 setup_native_handle(connection_side, ec);
394
395 detail::AsyncHandshakeOperation<completion_handler_t, Stream> op{
396 std::forward<completion_handler_t>(completion_handler), *this, ec};
397 },
398 completion_token,
399 side);
400 }
401
402 //! @throws Not_Implemented
403 template <typename ConstBufferSequence, detail::basic_completion_token BufferedHandshakeHandler>
404 auto async_handshake(Connection_Side side,
405 const ConstBufferSequence& buffers,
406 BufferedHandshakeHandler&& handler) {
407 BOTAN_UNUSED(side, buffers, handler);
408 throw Not_Implemented("buffered async handshake is not implemented");
409 }
410
411 //! @}
412 //! \name shutdown methods
413 //! @{
414
415 /**
416 * @brief Shut down SSL on the stream.
417 *
418 * This function is used to shut down SSL on the stream. The function call will block until SSL has been shut down
419 * or an error occurs. Note that this will not close the lowest layer.
420 *
421 * Note that this can be used in reaction of a received shutdown alert from the peer.
422 *
423 * @param ec Set to indicate what error occured, if any.
424 */
425 void shutdown(boost::system::error_code& ec) {
426 try_with_error_code([&] { native_handle()->close(); }, ec);
427
428 send_pending_encrypted_data(ec);
429 }
430
431 /**
432 * @brief Shut down SSL on the stream.
433 *
434 * This function is used to shut down SSL on the stream. The function call will block until SSL has been shut down
435 * or an error occurs. Note that this will not close the lowest layer.
436 *
437 * Note that this can be used in reaction of a received shutdown alert from the peer.
438 *
439 * @throws boost::system::system_error if error occured
440 */
441 void shutdown() {
442 boost::system::error_code ec;
443 shutdown(ec);
444 boost::asio::detail::throw_error(ec, "shutdown");
445 }
446
447 private:
448 /**
449 * @brief Internal wrapper type to adapt the expected signature of `async_shutdown` to the completion handler
450 * signature of `AsyncWriteOperation`.
451 *
452 * This is boilerplate to ignore the `size_t` parameter that is passed to the completion handler of
453 * `AsyncWriteOperation`. Note that it needs to retain the wrapped handler's executor.
454 */
455 template <typename Handler, typename Executor>
456 struct Wrapper {
457 void operator()(boost::system::error_code ec, std::size_t) { handler(ec); }
458
459 using executor_type = boost::asio::associated_executor_t<Handler, Executor>;
460
461 executor_type get_executor() const noexcept {
462 return boost::asio::get_associated_executor(handler, io_executor);
463 }
464
465 using allocator_type = boost::asio::associated_allocator_t<Handler>;
466
467 allocator_type get_allocator() const noexcept { return boost::asio::get_associated_allocator(handler); }
468
469 Handler handler;
470 Executor io_executor;
471 };
472
473 public:
474 /**
475 * @brief Asynchronously shut down SSL on the stream.
476 *
477 * This function call always returns immediately.
478 *
479 * Note that this can be used in reaction of a received shutdown alert from the peer.
480 *
481 * @param completion_token The completion handler to be called when the shutdown operation completes.
482 * The completion signature of the handler must be: void(boost::system::error_code).
483 */
484 template <detail::basic_completion_token CompletionToken = default_completion_token>
485 auto async_shutdown(CompletionToken&& completion_token = default_completion_token{}) {
486 return boost::asio::async_initiate<CompletionToken, void(boost::system::error_code)>(
487 [this](auto&& completion_handler) {
488 using completion_handler_t = std::decay_t<decltype(completion_handler)>;
489
490 boost::system::error_code ec;
491 try_with_error_code([&] { native_handle()->close(); }, ec);
492
493 using write_handler_t = Wrapper<completion_handler_t, typename Stream::executor_type>;
494
495 TLS::detail::AsyncWriteOperation<write_handler_t, Stream> op{
496 write_handler_t{std::forward<completion_handler_t>(completion_handler), get_executor()},
497 *this,
498 boost::asio::buffer_size(send_buffer()),
499 ec};
500 },
501 completion_token);
502 }
503
504 //! @}
505 //! \name I/O methods
506 //! @{
507
508 /**
509 * @brief Read some data from the stream.
510 *
511 * The function call will block until one or more bytes of data has been read successfully, or until an error
512 * occurs.
513 *
514 * @param buffers The buffers into which the data will be read.
515 * @param ec Set to indicate what error occurred, if any. Specifically, StreamTruncated will be set if the peer
516 * has closed the connection but did not properly shut down the SSL connection.
517 * @return The number of bytes read. Returns 0 if an error occurred.
518 */
519 template <typename MutableBufferSequence>
520 std::size_t read_some(const MutableBufferSequence& buffers, boost::system::error_code& ec) {
521 // We read from the socket until either some error occured or we have
522 // decrypted at least one byte of application data.
523 while(!ec) {
524 // Some previous invocation of process_encrypted_data() generated
525 // application data in the output buffer that can now be returned.
526 if(has_received_data()) {
527 return copy_received_data(buffers);
528 }
529
530 // Handle and report any TLS protocol errors (including a
531 // close_notify) that might have surfaced in a previous iteration
532 // (in `read_and_process_encrypted_data_from_peer()`). This makes
533 // sure that all received application data was handed out to the
534 // caller before reporting an error (e.g. EOF at the end of the
535 // stream).
536 handle_tls_protocol_errors(ec);
537
538 // If we don't have any plaintext application data, yet, we attempt
539 // to read more data from the peer. This reports network errors
540 // immediately. TLS protocol errors result in an internal state
541 // change which is handled by `handle_tls_protocol_errors()` in the
542 // next iteration.
543 read_and_process_encrypted_data_from_peer(ec);
544 }
545
546 BOTAN_ASSERT_NOMSG(ec.failed());
547 return 0;
548 }
549
550 /**
551 * @brief Read some data from the stream.
552 *
553 * The function call will block until one or more bytes of data has been read successfully, or until an error
554 * occurs.
555 *
556 * @param buffers The buffers into which the data will be read.
557 * @return The number of bytes read. Returns 0 if an error occurred.
558 * @throws boost::system::system_error if error occured
559 */
560 template <typename MutableBufferSequence>
561 std::size_t read_some(const MutableBufferSequence& buffers) {
562 boost::system::error_code ec;
563 const auto n = read_some(buffers, ec);
564 boost::asio::detail::throw_error(ec, "read_some");
565 return n;
566 }
567
568 /**
569 * @brief Write some data to the stream.
570 *
571 * The function call will block until one or more bytes of data has been written successfully, or until an error
572 * occurs.
573 *
574 * @param buffers The data to be written.
575 * @param ec Set to indicate what error occurred, if any.
576 * @return The number of bytes processed from the input buffers.
577 */
578 template <typename ConstBufferSequence>
579 std::size_t write_some(const ConstBufferSequence& buffers, boost::system::error_code& ec) {
580 tls_encrypt(buffers, ec);
581 send_pending_encrypted_data(ec);
582 return !ec ? boost::asio::buffer_size(buffers) : 0;
583 }
584
585 /**
586 * @brief Write some data to the stream.
587 *
588 * The function call will block until one or more bytes of data has been written successfully, or until an error
589 * occurs.
590 *
591 * @param buffers The data to be written.
592 * @return The number of bytes written.
593 * @throws boost::system::system_error if error occured
594 */
595 template <typename ConstBufferSequence>
596 std::size_t write_some(const ConstBufferSequence& buffers) {
597 boost::system::error_code ec;
598 const auto n = write_some(buffers, ec);
599 boost::asio::detail::throw_error(ec, "write_some");
600 return n;
601 }
602
603 /**
604 * @brief Start an asynchronous write. The function call always returns immediately.
605 *
606 * @param buffers The data to be written.
607 * @param completion_token The completion handler to be called when the write operation completes. Copies of the
608 * handler will be made as required. The completion signature of the handler must be:
609 * void(boost::system::error_code, std::size_t).
610 */
611 template <typename ConstBufferSequence,
612 detail::byte_size_completion_token CompletionToken = default_completion_token>
613 auto async_write_some(const ConstBufferSequence& buffers,
614 CompletionToken&& completion_token = default_completion_token{}) {
615 return boost::asio::async_initiate<CompletionToken, void(boost::system::error_code, std::size_t)>(
616 [this](auto&& completion_handler, const auto& bufs) {
617 using completion_handler_t = std::decay_t<decltype(completion_handler)>;
618
619 boost::system::error_code ec;
620 tls_encrypt(bufs, ec);
621
622 if(ec) {
623 // we cannot be sure how many bytes were committed here so clear the send_buffer and let the
624 // AsyncWriteOperation call the handler with the error_code set
625 m_core->send_buffer().consume(m_core->send_buffer().size());
626 }
627
628 detail::AsyncWriteOperation<completion_handler_t, Stream> op{
629 std::forward<completion_handler_t>(completion_handler),
630 *this,
631 ec ? 0 : boost::asio::buffer_size(bufs),
632 ec};
633 },
634 completion_token,
635 buffers);
636 }
637
638 /**
639 * @brief Start an asynchronous read. The function call always returns immediately.
640 *
641 * @param buffers The buffers into which the data will be read. Although the buffers object may be copied as
642 * necessary, ownership of the underlying buffers is retained by the caller, which must guarantee
643 * that they remain valid until the handler is called.
644 * @param completion_token The completion handler to be called when the read operation completes. The completion
645 * signature of the handler must be: void(boost::system::error_code, std::size_t).
646 */
647 template <typename MutableBufferSequence,
648 detail::byte_size_completion_token CompletionToken = default_completion_token>
649 auto async_read_some(const MutableBufferSequence& buffers,
650 CompletionToken&& completion_token = default_completion_token{}) {
651 return boost::asio::async_initiate<CompletionToken, void(boost::system::error_code, std::size_t)>(
652 [this](auto&& completion_handler, const auto& bufs) {
653 using completion_handler_t = std::decay_t<decltype(completion_handler)>;
654
655 detail::AsyncReadOperation<completion_handler_t, Stream, MutableBufferSequence> op{
656 std::forward<completion_handler_t>(completion_handler), *this, bufs};
657 },
658 completion_token,
659 buffers);
660 }
661
662 //! @}
663
664 //! @brief Indicates whether a close_notify alert has been received from the peer.
665 //!
666 //! Note that we cannot m_core.is_closed_for_reading() because this wants to
667 //! explicitly check that the peer sent close_notify.
668 bool shutdown_received() const { return m_core->shutdown_received(); }
669
670 protected:
671 template <class H, class S, class M, class A>
672 friend class detail::AsyncReadOperation;
673 template <class H, class S, class A>
674 friend class detail::AsyncWriteOperation;
675 template <class H, class S, class A>
676 friend class detail::AsyncHandshakeOperation;
677
678 const boost::asio::mutable_buffer& input_buffer() { return m_input_buffer; }
679
680 boost::asio::const_buffer send_buffer() const { return m_core->send_buffer().data(); }
681
682 //! @brief Check if decrypted data is available in the receive buffer
683 bool has_received_data() const { return m_core->receive_buffer().size() > 0; }
684
685 //! @brief Copy decrypted data into the user-provided buffer
686 template <typename MutableBufferSequence>
687 std::size_t copy_received_data(MutableBufferSequence buffers) {
688 // Note: It would be nice to avoid this buffer copy. This could be achieved by equipping the CallbacksT with
689 // the user's desired target buffer once a read is started, and reading directly into that buffer in tls_record
690 // received. However, we need to deal with the case that the receive buffer provided by the caller is smaller
691 // than the decrypted record, so this optimization might not be worth the additional complexity.
692 const auto copiedBytes = boost::asio::buffer_copy(buffers, m_core->receive_buffer().data());
693 m_core->receive_buffer().consume(copiedBytes);
694 return copiedBytes;
695 }
696
697 //! @brief Check if encrypted data is available in the send buffer
698 bool has_data_to_send() const { return m_core->send_buffer().size() > 0; }
699
700 //! @brief Mark bytes in the send buffer as consumed, removing them from the buffer
701 void consume_send_buffer(std::size_t bytesConsumed) { m_core->send_buffer().consume(bytesConsumed); }
702
703 /**
704 * @brief Create the native handle.
705 *
706 * Depending on the desired connection side, this function will create a TLS::Client or a
707 * TLS::Server.
708 *
709 * @param side The desired connection side (client or server)
710 * @param ec Set to indicate what error occurred, if any.
711 */
712 void setup_native_handle(Connection_Side side, boost::system::error_code& ec) {
713 // Do not attempt to instantiate the native_handle when a custom (mocked) channel type template parameter has
714 // been specified. This allows mocking the native_handle in test code.
715 if constexpr(std::is_same<ChannelT, Channel>::value) {
716 BOTAN_STATE_CHECK(m_native_handle == nullptr);
717
718 try_with_error_code(
719 [&] {
720 if(side == Connection_Side::Client) {
721 m_native_handle = std::unique_ptr<Client>(
722 new Client(m_core,
723 m_context->m_session_manager,
724 m_context->m_credentials_manager,
725 m_context->m_policy,
726 m_context->m_rng,
727 m_context->m_server_info,
728 m_context->m_policy->latest_supported_version(false /* no DTLS */)));
729 } else {
730 m_native_handle = std::unique_ptr<Server>(new Server(m_core,
731 m_context->m_session_manager,
732 m_context->m_credentials_manager,
733 m_context->m_policy,
734 m_context->m_rng,
735 false /* no DTLS */));
736 }
737 },
738 ec);
739 }
740 }
741
742 /**
743 * The `Stream` has to distinguish from network-related issues (that are
744 * reported immediately) from TLS protocol errors, that must be retained
745 * and emitted once all legal application traffic received before is
746 * pushed to the downstream application.
747 *
748 * See also `process_encrypted_data()` and `StreamCallbacks::tls_alert()`
749 * where those TLS protocol errors are detected and retained for eventual
750 * handling in this method.
751 *
752 * See also https://github.com/randombit/botan/pull/3801 for a detailed
753 * description of the ASIO stream's state management.
754 *
755 * @param ec this error code is set if we previously detected a TLS
756 * protocol error.
757 */
758 void handle_tls_protocol_errors(boost::system::error_code& ec) {
759 if(ec) {
760 return;
761 }
762
763 // If we had raised an error while processing TLS records received from
764 // the peer, we expose that error here.
765 //
766 // See also `process_encrypted_data()`.
767 else if(auto error = error_from_us()) {
768 ec = error;
769 }
770
771 // If we had received a TLS alert from the peer, we expose that error
772 // here. See also `StreamCallbacks::tls_alert()` where such alerts
773 // would be detected and retained initially.
774 //
775 // Note that a close_notify is always a legal way for the peer to end a
776 // TLS session. When received during the handshake it typically means
777 // that the peer wanted to cancel the handshake for some reason not
778 // related to the TLS protocol.
779 else if(auto alert = alert_from_peer()) {
780 if(alert->type() == AlertType::CloseNotify) {
781 ec = boost::asio::error::eof;
782 } else {
783 ec = alert->type();
784 }
785 }
786 }
787
788 /**
789 * Reads TLS record data from the peer and forwards it to the native
790 * handle for processing. Note that @p ec will reflect network errors
791 * only. Any detected or received TLS protocol errors will be retained and
792 * must be handled by the downstream operation in due time by invoking
793 * `handle_tls_protocol_errors()`.
794 *
795 * @param ec this error code might be populated with network-related errors
796 */
797 void read_and_process_encrypted_data_from_peer(boost::system::error_code& ec) {
798 if(ec) {
799 return;
800 }
801
802 // If we have received application data in a previous invocation, this
803 // data needs to be passed to the application first. Otherwise, it
804 // might get overwritten.
805 BOTAN_ASSERT(!has_received_data(), "receive buffer is empty");
806 BOTAN_ASSERT(!error_from_us() && !alert_from_peer(), "TLS session is healthy");
807
808 // If there's no existing error condition, read and process data from
809 // the peer and report any sort of network error. TLS related errors do
810 // not immediately cause an abort, they are checked in the invocation
811 // via `error_from_us()`.
812 boost::asio::const_buffer read_buffer{input_buffer().data(), m_nextLayer.read_some(input_buffer(), ec)};
813 if(!ec) {
814 process_encrypted_data(read_buffer);
815 } else if(ec == boost::asio::error::eof) {
816 ec = StreamError::StreamTruncated;
817 }
818 }
819
820 /** @brief Synchronously write encrypted data from the send buffer to the next layer.
821 *
822 * If this function is called with an error code other than 'Success', it will do nothing and return 0.
823 *
824 * @param ec Set to indicate what error occurred, if any. Specifically, StreamTruncated will be set if the peer
825 * has closed the connection but did not properly shut down the SSL connection.
826 * @return The number of bytes written.
827 */
828 size_t send_pending_encrypted_data(boost::system::error_code& ec) {
829 if(ec) {
830 return 0;
831 }
832
833 auto writtenBytes = boost::asio::write(m_nextLayer, send_buffer(), ec);
834 consume_send_buffer(writtenBytes);
835
836 if(ec == boost::asio::error::eof && !shutdown_received()) {
837 // transport layer was closed by peer without receiving 'close_notify'
838 ec = StreamError::StreamTruncated;
839 }
840
841 return writtenBytes;
842 }
843
844 /**
845 * @brief Pass plaintext data to the native handle for processing.
846 *
847 * The native handle will then create TLS records and hand them back to the Stream via the tls_emit_data callback.
848 */
849 template <typename ConstBufferSequence>
850 void tls_encrypt(const ConstBufferSequence& buffers, boost::system::error_code& ec) {
851 // TODO: Once the TLS::Channel can deal with buffer sequences we can
852 // save this copy. Until then we optimize for the smallest amount
853 // of TLS records and flatten the boost buffer sequence.
854 std::vector<uint8_t> copy_buffer;
855 auto unpack = [&copy_buffer](const auto& bufs) -> std::span<const uint8_t> {
856 const auto buffers_in_sequence =
857 std::distance(boost::asio::buffer_sequence_begin(bufs), boost::asio::buffer_sequence_end(bufs));
858
859 if(buffers_in_sequence == 0) {
860 return {};
861 } else if(buffers_in_sequence == 1) {
862 const boost::asio::const_buffer buf = *boost::asio::buffer_sequence_begin(bufs);
863 return {static_cast<const uint8_t*>(buf.data()), buf.size()};
864 } else {
865 copy_buffer.resize(boost::asio::buffer_size(bufs));
866 boost::asio::buffer_copy(boost::asio::buffer(copy_buffer), bufs);
867 return copy_buffer;
868 }
869 };
870
871 // NOTE: This is not asynchronous: it encrypts the data synchronously.
872 // The data encrypted by native_handle()->send() is synchronously stored in the send_buffer of m_core,
873 // but is not actually written to the wire, yet.
874 try_with_error_code([&] { native_handle()->send(unpack(buffers)); }, ec);
875 }
876
877 /**
878 * Pass encrypted data received from the peer to the native handle for
879 * processing. If the @p read_buffer contains coalesced TLS records, this
880 * might result in multiple TLS protocol state changes.
881 *
882 * To allow the ASIO stream wrapper to disentangle those state changes
883 * properly, any TLS protocol errors are retained and must be handled by
884 * calling `handle_tls_protocol_errors()` in due time.
885 *
886 * @param read_buffer Input buffer containing the encrypted data.
887 */
888 void process_encrypted_data(const boost::asio::const_buffer& read_buffer) {
889 BOTAN_ASSERT(!alert_from_peer() && !error_from_us(),
890 "no one sent an alert before (no data allowed after that)");
891
892 // If the local TLS implementation generates an alert, we are notified
893 // with an exception that is caught in try_with_error_code(). The error
894 // code is retained and not handled directly. Stream operations will
895 // have to invoke `handle_tls_protocol_errors()` to handle them later.
896 try_with_error_code(
897 [&] {
898 native_handle()->received_data({static_cast<const uint8_t*>(read_buffer.data()), read_buffer.size()});
899 },
900 m_ec_from_last_read);
901 }
902
903 //! @brief Catch exceptions and set an error_code
904 template <typename Fun>
905 void try_with_error_code(Fun f, boost::system::error_code& ec) {
906 try {
907 f();
908 } catch(const TLS_Exception& e) {
909 ec = e.type();
910 } catch(const Exception& e) {
911 ec = e.error_type();
912 } catch(const std::exception&) {
913 ec = ErrorType::Unknown;
914 }
915 }
916
917 private:
918 /**
919 * Returns any alert previously received from the peer. This may include
920 * close_notify. Once the peer has sent any alert, no more data must be
921 * read from the stream.
922 */
923 std::optional<Alert> alert_from_peer() const { return m_core->alert_from_peer(); }
924
925 /**
926 * Returns any error code produced by the local TLS implementation. This
927 * will _not_ include close_notify. Once our TLS stack has reported an
928 * error, no more data must be written to the stream. The peer will receive
929 * the error as a TLS alert.
930 */
931 boost::system::error_code error_from_us() const { return m_ec_from_last_read; }
932
933 protected:
934 std::shared_ptr<Context> m_context;
935 StreamLayer m_nextLayer;
936
937 std::shared_ptr<StreamCallbacks> m_core;
938 std::unique_ptr<ChannelT> m_native_handle;
939 boost::system::error_code m_ec_from_last_read;
940
941 // Buffer space used to read input intended for the core
942 std::vector<uint8_t> m_input_buffer_space;
943 const boost::asio::mutable_buffer m_input_buffer;
944};
945
946// deduction guides for convenient construction from an existing
947// underlying transport stream T
948template <typename T>
949Stream(std::shared_ptr<Context>, std::shared_ptr<StreamCallbacks>, T) -> Stream<T>;
950template <typename T>
951Stream(std::shared_ptr<Context>, T) -> Stream<T>;
952template <typename T>
953Stream(T, std::shared_ptr<Context>) -> Stream<T>;
954
955} // namespace Botan::TLS
956
957#endif
958#endif // BOTAN_ASIO_STREAM_H_
#define BOTAN_UNUSED
Definition assert.h:118
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:59
#define BOTAN_STATE_CHECK(expr)
Definition assert.h:41
#define BOTAN_ASSERT(expr, assertion_made)
Definition assert.h:50
int(* final)(unsigned char *, CTX *)
FE_25519 T
Definition ge.cpp:34
@ MAX_CIPHERTEXT_SIZE
Definition tls_magic.h:33