Botan 3.14.1
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 <exception>
36 #include <memory>
37 #include <new>
38 #include <span>
39 #include <stdexcept>
40 #include <type_traits>
41 #include <utility>
42 #include <vector>
43
44namespace Botan::TLS {
45
46template <class SL, class C>
47class Stream;
48
49namespace detail {
50
51/**
52 * @brief The records emitted by the TLS implementation, on their way to the next layer
53 *
54 * Records are written in the order they were emitted, by one write at a time.
55 * The records lent to the next layer by that write are kept apart from the
56 * ones emitted in the meantime, which may reallocate the queue's storage.
57 * Whatever the next layer did not accept stays in flight and goes out first
58 * with the next write, so no record is lost or reordered. Read operations
59 * mark the output emitted so far and wait until it is written, whoever writes
60 * it. Only push() allocates; everything else may run in a completion handler.
61 */
62class OutputQueue {
63 public:
64 //! @brief Append a record; a record that cannot be buffered is refused up front, leaving the queue untouched
65 void push(std::span<const uint8_t> record) {
66 if(record.size() > m_queued.max_size() - m_queued.size()) {
67 throw std::length_error("TLS record does not fit the output queue");
68 }
69 m_queued.insert(m_queued.end(), record.begin(), record.end());
70 }
71
72 //! @brief Check whether a write is lending records to the next layer
73 bool write_in_progress() const { return m_write_in_progress; }
74
75 //! @brief Check if records are waiting to be written (queued, or left behind by the last write)
76 bool has_data() const { return !m_queued.empty() || (!m_write_in_progress && in_flight().size() > 0); }
77
78 /**
79 * @brief Lend the records to write next to the next layer
80 *
81 * Whatever the previous write did not get through goes out first, on its
82 * own. The records queued since are taken (by swapping storage) once the
83 * in-flight buffer is empty.
84 *
85 * @return the records to write
86 */
87 boost::asio::const_buffer begin_write() {
88 if(m_write_in_progress || !has_data()) {
89 throw Botan::Invalid_State("ASIO TLS stream write already in progress or nothing to write");
90 }
91
92 if(in_flight().size() == 0) {
93 m_in_flight.clear();
94 m_in_flight_offset = 0;
95 std::swap(m_in_flight, m_queued);
96 }
97 m_write_in_progress = true;
98 return in_flight();
99 }
100
101 /**
102 * @brief Take back the records lent by begin_write()
103 *
104 * Records the next layer did not accept stay in flight; whoever writes
105 * next continues exactly where this write stopped.
106 *
107 * @param bytes_transferred the number of bytes the next layer accepted
108 */
109 void end_write(std::size_t bytes_transferred) {
110 const auto accepted = std::min(bytes_transferred, in_flight().size());
111 m_in_flight_offset += accepted;
112 m_written += accepted;
113 if(m_in_flight_offset == m_in_flight.size()) {
114 m_in_flight.clear();
115 m_in_flight_offset = 0;
116 }
117 m_write_in_progress = false;
118 }
119
120 //! @brief Have everything emitted so far written before a read operation reports a condition or consumes input
121 void mark_pending() {
122 if(has_data()) {
123 m_pending_mark = position();
124 }
125 }
126
127 //! @brief Check whether records marked by mark_pending() are still waiting to be written
128 bool pending() const { return m_written < m_pending_mark; }
129
130 //! @brief Number of bytes queued but not lent out yet, see truncate()
131 std::size_t queued_size() const { return m_queued.size(); }
132
133 //! @brief Drop the queued records beyond the first @p keep bytes, i.e. those emitted since queued_size() was @p keep
134 void truncate(std::size_t keep) {
135 if(m_queued.size() > keep) {
136 m_queued.resize(keep);
137 // Read operations must not wait for records that no longer exist
138 m_pending_mark = std::min(m_pending_mark, position());
139 }
140 }
141
142 //! @brief Discard everything, for a new connection
143 void clear() {
144 m_queued.clear();
145 m_in_flight.clear();
146 m_in_flight_offset = 0;
147 m_write_in_progress = false;
148 m_written = 0;
149 m_pending_mark = 0;
150 }
151
152 private:
153 //! @brief The records currently lent to the next layer, or left behind by the last write
154 boost::asio::const_buffer in_flight() const {
155 return {m_in_flight.data() + m_in_flight_offset, m_in_flight.size() - m_in_flight_offset};
156 }
157
158 //! @brief Position of the end of the records emitted so far in the stream of output bytes
159 uint64_t position() const { return m_written + in_flight().size() + m_queued.size(); }
160
161 std::vector<uint8_t> m_queued;
162 std::vector<uint8_t> m_in_flight;
163 std::size_t m_in_flight_offset = 0;
164 bool m_write_in_progress = false;
165 uint64_t m_written = 0;
166 uint64_t m_pending_mark = 0;
167};
168
169} // namespace detail
170
171/**
172 * @brief Specialization of TLS::Callbacks for the ASIO Stream
173 *
174 * Applications may decide to derive from this for fine-grained customizations
175 * of the TLS::Stream's behaviour. Examples may be OCSP integration, custom
176 * certificate validation or user-defined key exchange mechanisms.
177 *
178 * By default, this class provides all necessary customizations for the ASIO
179 * integration. The methods required for that are `final` and cannot be
180 * overridden.
181 *
182 * Each instance of TLS::Stream must have their own instance of this class;
183 * constructing a Stream with an instance that is still in use by another
184 * Stream throws Invalid_Argument. A future major version of Botan will
185 * therefor consume instances of this class as a std::unique_ptr. The current
186 * usage of std::shared_ptr is erratic.
187 */
188class StreamCallbacks : public Callbacks {
189 public:
190 StreamCallbacks() = default;
191
192 void tls_emit_data(std::span<const uint8_t> data) final {
193 try {
194 m_output.push(data);
195 } catch(...) {
196 // The TLS implementation swallows this when the record is an alert,
197 // see Stream::call_tls()
198 m_emit_failure = std::current_exception();
199 throw;
200 }
201 }
202
203 void tls_record_received(uint64_t /*record_number*/, std::span<const uint8_t> data) final {
204 m_receive_buffer.commit(boost::asio::buffer_copy(m_receive_buffer.prepare(data.size()),
205 boost::asio::const_buffer(data.data(), data.size())));
206 }
207
208 bool tls_peer_closed_connection() final {
209 // Instruct the TLS implementation to reply with our close_notify to
210 // obtain the same behaviour for TLS 1.2 and TLS 1.3. Currently, this
211 // prevents a downstream application from closing their write-end while
212 // allowing the peer to continue writing.
213 //
214 // When lifting this limitation, please take good note of the "Future
215 // work" remarks in https://github.com/randombit/botan/pull/3801.
216 return true;
217 }
218
219 /**
220 * @param alert a TLS alert sent by the peer
221 */
222 void tls_alert(TLS::Alert alert) final {
223 if(alert.is_fatal() || alert.type() == TLS::AlertType::CloseNotify) {
224 // TLS alerts received from the peer are not passed to the
225 // downstream application immediately. Instead, we retain them here
226 // and the stream invokes `handle_tls_protocol_errors()` in due time
227 // to handle them.
228 m_alert_from_peer = alert;
229 }
230 }
231
232 void tls_verify_cert_chain(const std::vector<X509_Certificate>& cert_chain,
233 const std::vector<std::optional<OCSP::Response>>& ocsp_responses,
234 const std::vector<Certificate_Store*>& trusted_roots,
235 Usage_Type usage,
236 std::string_view hostname,
237 const TLS::Policy& policy) override {
238 const auto ctx = m_context.lock();
239
240 if(ctx && ctx->has_verify_callback()) {
241 ctx->get_verify_callback()(cert_chain, ocsp_responses, trusted_roots, usage, hostname, policy);
242 } else {
243 Callbacks::tls_verify_cert_chain(cert_chain, ocsp_responses, trusted_roots, usage, hostname, policy);
244 }
245 }
246
247 std::string tls_server_choose_app_protocol(const std::vector<std::string>& client_protos) override {
248 if(client_protos.empty()) {
249 return "";
250 }
251 const auto ctx = m_context.lock();
252
253 if(!ctx || ctx->m_app_protocols.empty()) {
254 return "";
255 }
256 // Priority is to the server.
257 for(const auto& server_proto : ctx->m_app_protocols) {
258 for(const auto& client_proto : client_protos) {
259 if(server_proto == client_proto) {
260 return server_proto;
261 }
262 }
263 }
264 // No match.
265 throw TLS_Exception(
266 Alert::NoApplicationProtocol,
267 "Rejecting ALPN request: no overlap between client-offered and server-configured application protocols");
268 }
269
270 private:
271 // The members below are meant for the tightly-coupled Stream class only
272 template <class SL, class C>
273 friend class Stream;
274
275 /**
276 * Bind this instance to a Stream. An instance serves at most one live
277 * Stream at a time; the Stream holds the token for as long as it is alive
278 * and releases it when it is destroyed or assigned over.
279 */
280 void bind_to_stream(const std::shared_ptr<const void>& stream_token, std::weak_ptr<Botan::TLS::Context> context) {
281 if(!m_stream_token.expired()) {
282 throw Invalid_Argument("TLS::StreamCallbacks instance is already in use by another TLS::Stream");
283 }
284
285 m_stream_token = stream_token;
286 m_context = std::move(context);
287
288 // Discard anything left over from a previous connection
289 m_alert_from_peer.reset();
290 m_receive_buffer.clear();
291 m_output.clear();
292 m_emit_failure = nullptr;
293 }
294
295 detail::OutputQueue& output_queue() { return m_output; }
296
297 const detail::OutputQueue& output_queue() const { return m_output; }
298
299 //! @brief Hand out and clear the failure of the last tls_emit_data() call that failed
300 std::exception_ptr take_emit_failure() { return std::exchange(m_emit_failure, nullptr); }
301
302 boost::beast::flat_buffer& receive_buffer() { return m_receive_buffer; }
303
304 const boost::beast::flat_buffer& receive_buffer() const { return m_receive_buffer; }
305
306 bool shutdown_received() const {
307 return m_alert_from_peer && m_alert_from_peer->type() == AlertType::CloseNotify;
308 }
309
310 std::optional<Alert> alert_from_peer() const { return m_alert_from_peer; }
311
312 private:
313 std::optional<Alert> m_alert_from_peer;
314 boost::beast::flat_buffer m_receive_buffer;
315 detail::OutputQueue m_output;
316 std::exception_ptr m_emit_failure;
317
318 std::weak_ptr<TLS::Context> m_context;
319 std::weak_ptr<const void> m_stream_token;
320};
321
322namespace detail {
323
324template <typename T>
325concept basic_completion_token = boost::asio::completion_token_for<T, void(boost::system::error_code)>;
326
327template <typename T>
328concept byte_size_completion_token = boost::asio::completion_token_for<T, void(boost::system::error_code, size_t)>;
329
330} // namespace detail
331
332/**
333 * @brief boost::asio compatible SSL/TLS stream
334 *
335 * Like boost::asio::ssl::stream, the stream allows one read operation and
336 * one write operation (async_write_some or async_shutdown) to be outstanding
337 * at the same time. All asynchronous operations must be performed within the
338 * same implicit or explicit strand. Operations support terminal cancellation
339 * via the completion token's associated cancellation slot.
340 *
341 * Synchronous operations must not be used while an asynchronous write is in
342 * flight; they then fail with boost::asio::error::already_started. A stream
343 * must not be destroyed or moved while an operation is outstanding.
344 *
345 * A failure inside the TLS implementation on an active connection, or a
346 * record it emitted that could not be buffered, may leave its record
347 * sequence out of step with the peer. The stream then discards whatever
348 * the TLS implementation emits afterwards and refuses any further output,
349 * reporting that error again.
350 *
351 * @tparam StreamLayer type of the next layer, usually a network socket
352 * @tparam ChannelT type of the native_handle, defaults to TLS::Channel, only needed for testing purposes
353 */
354template <class StreamLayer, class ChannelT = Channel>
355class Stream {
356 private:
357 using default_completion_token =
358 boost::asio::default_completion_token_t<boost::beast::executor_type<StreamLayer>>;
359
360 public:
361 //! \name construction
362 //! @{
363
364 /**
365 * @brief Construct a new Stream with a customizable instance of Callbacks
366 *
367 * @param context The context parameter is used to set up the underlying native handle.
368 * @param callbacks The callbacks parameter may contain an instance of a derived TLS::Callbacks
369 * class to allow for fine-grained customization of the TLS stream. Note that
370 * applications need to ensure a 1-to-1 relationship between instances of
371 * Callbacks and Streams; passing an instance that is still in use by another
372 * Stream throws Invalid_Argument. A future major version of Botan will use a
373 * unique_ptr here.
374 *
375 * @param args Arguments to be forwarded to the construction of the next layer.
376 */
377 template <typename... Args>
378 explicit Stream(std::shared_ptr<Context> context, std::shared_ptr<StreamCallbacks> callbacks, Args&&... args) :
379 m_context(std::move(context)),
380 m_nextLayer(std::forward<Args>(args)...),
381 m_core(std::move(callbacks)),
382 m_core_token(std::make_shared<int>(0)),
383 m_input_buffer_space(MAX_CIPHERTEXT_SIZE, '\0'),
384 m_pending_write(m_nextLayer.get_executor(), std::chrono::steady_clock::time_point::max()) {
385 if(!m_context || !m_core) {
386 throw Invalid_Argument("TLS::Stream requires a context and a callbacks object");
387 }
388 m_core->bind_to_stream(m_core_token, m_context);
389 }
390
391 /**
392 * @brief Construct a new Stream
393 *
394 * @param context The context parameter is used to set up the underlying native handle.
395 * @param args Arguments to be forwarded to the construction of the next layer.
396 */
397 template <typename... Args>
398 explicit Stream(std::shared_ptr<Context> context, Args&&... args) :
399 Stream(std::move(context), std::make_shared<StreamCallbacks>(), std::forward<Args>(args)...) {}
400
401 /**
402 * @brief Construct a new Stream
403 *
404 * Convenience overload for boost::asio::ssl::stream compatibility.
405 *
406 * @param arg This argument is forwarded to the construction of the next layer.
407 * @param context The context parameter is used to set up the underlying native handle.
408 * @param callbacks The (optional) callbacks object that the stream should use. Note that
409 * applications need to ensure a 1-to-1 relationship between instances of Callbacks
410 * and Streams. A future major version of Botan will use a unique_ptr here.
411 */
412 template <typename Arg>
413 explicit Stream(Arg&& arg,
414 std::shared_ptr<Context> context,
415 std::shared_ptr<StreamCallbacks> callbacks = std::make_shared<StreamCallbacks>()) :
416 Stream(std::move(context), std::move(callbacks), std::forward<Arg>(arg)) {}
417
418 #if defined(BOTAN_HAS_DEFAULT_TLS_CONTEXT)
419 /**
420 * @brief Conveniently construct a new Stream with default settings
421 *
422 * This is typically a good starting point for a basic TLS client. For
423 * much more control and configuration options, consider creating a custom
424 * Context object and pass it to the respective constructor.
425 *
426 * @param server_info Basic information about the host to connect to (SNI)
427 * @param args Arguments to be forwarded to the construction of the next layer.
428 */
429 template <typename... Args>
430 explicit Stream(Server_Information server_info, Args&&... args) :
431 Stream(std::make_shared<Context>(std::move(server_info)), std::forward<Args>(args)...) {}
432 #endif
433
434 virtual ~Stream() = default;
435
436 // Moving throws if moving the next layer does (e.g. boost::beast::test::stream)
437 Stream(Stream&& other) = default; // NOLINT(*-exception-escape)
438 Stream& operator=(Stream&& other) = default; // NOLINT(*-exception-escape)
439
440 Stream(const Stream& other) = delete;
441 Stream& operator=(const Stream& other) = delete;
442
443 //! @}
444 //! \name boost::asio accessor methods
445 //! @{
446
447 using next_layer_type = std::remove_reference_t<StreamLayer>;
448
449 const next_layer_type& next_layer() const { return m_nextLayer; }
450
451 next_layer_type& next_layer() { return m_nextLayer; }
452
453 using lowest_layer_type = typename boost::beast::lowest_layer_type<StreamLayer>;
454
455 lowest_layer_type& lowest_layer() { return boost::beast::get_lowest_layer(m_nextLayer); }
456
457 const lowest_layer_type& lowest_layer() const { return boost::beast::get_lowest_layer(m_nextLayer); }
458
459 using executor_type = typename next_layer_type::executor_type;
460
461 executor_type get_executor() noexcept { return m_nextLayer.get_executor(); }
462
463 using native_handle_type = std::add_pointer_t<ChannelT>;
464
465 native_handle_type native_handle() {
466 if(m_native_handle == nullptr) {
467 throw Botan::Invalid_State("ASIO native handle unexpectedly null");
468 }
469 return m_native_handle.get();
470 }
471
472 //! @}
473 //! \name configuration and callback setters
474 //! @{
475
476 /**
477 * @brief Override the tls_verify_cert_chain callback
478 *
479 * This changes the verify_callback in the stream's TLS::Context, and hence the tls_verify_cert_chain callback
480 * used in the handshake.
481 * Using this function is equivalent to setting the callback via @see Botan::TLS::Context::set_verify_callback
482 *
483 * @note This function should only be called before initiating the TLS handshake
484 */
485 void set_verify_callback(Context::Verify_Callback callback) {
486 m_context->set_verify_callback(std::move(callback));
487 }
488
489 /**
490 * @brief Compatibility overload of @ref set_verify_callback
491 *
492 * @param callback the callback implementation
493 * @param ec This parameter is unused.
494 */
495 void set_verify_callback(Context::Verify_Callback callback, [[maybe_unused]] boost::system::error_code& ec) {
496 m_context->set_verify_callback(std::move(callback));
497 }
498
499 /**
500 * Not Implemented.
501 * @param depth the desired verification depth
502 * @throws Not_Implemented todo
503 */
504 void set_verify_depth([[maybe_unused]] int depth) {
505 throw Not_Implemented("set_verify_depth is not implemented");
506 }
507
508 /**
509 * Not Implemented.
510 * @param depth the desired verification depth
511 * @param ec Will be set to `Botan::ErrorType::NotImplemented`
512 */
513 void set_verify_depth([[maybe_unused]] int depth, boost::system::error_code& ec) {
514 ec = ErrorType::NotImplemented;
515 }
516
517 /**
518 * Not Implemented.
519 * @param v the desired verify mode
520 * @throws Not_Implemented todo
521 */
522 template <typename verify_mode>
523 void set_verify_mode([[maybe_unused]] verify_mode v) {
524 throw Not_Implemented("set_verify_mode is not implemented");
525 }
526
527 /**
528 * Not Implemented.
529 * @param v the desired verify mode
530 * @param ec Will be set to `Botan::ErrorType::NotImplemented`
531 */
532 template <typename verify_mode>
533 void set_verify_mode([[maybe_unused]] verify_mode v, boost::system::error_code& ec) {
534 ec = ErrorType::NotImplemented;
535 }
536
537 //! @}
538 //! \name handshake methods
539 //! @{
540
541 /**
542 * @brief Performs SSL handshaking.
543 *
544 * The function call will block until handshaking is complete or an error occurs.
545 *
546 * @param side The type of handshaking to be performed, i.e. as a client or as a server.
547 * @throws boost::system::system_error if error occurred
548 */
549 void handshake(Connection_Side side) {
550 boost::system::error_code ec;
551 handshake(side, ec);
552 boost::asio::detail::throw_error(ec, "handshake");
553 }
554
555 /**
556 * @brief Performs SSL handshaking.
557 *
558 * The function call will block until handshaking is complete or an error occurs.
559 *
560 * @param side The type of handshaking to be performed, i.e. as a client or as a server.
561 * @param ec Set to indicate what error occurred, if any.
562 */
563 void handshake(Connection_Side side, boost::system::error_code& ec) {
564 ec = {};
565 if(async_write_in_flight(ec)) {
566 return;
567 }
568
569 ec = setup_native_handle(side);
570
571 // We write to the socket if we have data to send and read from it
572 // otherwise, until either some error occurred or we have successfully
573 // performed the handshake.
574 while(!ec) {
575 // Send pending data to the peer and abort the handshake if that
576 // fails with a network error. We do that first, to allow sending
577 // any final message before reporting the handshake as "finished".
578 if(has_data_to_send()) {
579 send_pending_encrypted_data(ec);
580 }
581
582 // Once the underlying TLS implementation reports a complete and
583 // successful handshake we're done.
584 if(native_handle()->is_handshake_complete()) {
585 return;
586 }
587
588 // Handle and report any TLS protocol errors that might have
589 // surfaced in a previous iteration. By postponing their handling we
590 // allow the stream to send a respective TLS alert to the peer before
591 // aborting the handshake.
592 handle_tls_protocol_errors(ec);
593
594 // If we don't have any encrypted data to send we attempt to read
595 // more data from the peer. This reports network errors immediately.
596 // TLS protocol errors result in an internal state change which is
597 // handled by `handle_tls_protocol_errors()` in the next iteration.
598 read_and_process_encrypted_data_from_peer(ec);
599 }
600 }
601
602 /**
603 * @brief Starts an asynchronous SSL handshake.
604 *
605 * This function call always returns immediately.
606 *
607 * @param side The type of handshaking to be performed, i.e. as a client or as a server.
608 * @param completion_token The completion handler to be called when the handshake operation completes.
609 * The completion signature of the handler must be: void(boost::system::error_code).
610 */
611 template <detail::basic_completion_token CompletionToken = default_completion_token>
612 auto async_handshake(Botan::TLS::Connection_Side side,
613 // NOLINTNEXTLINE(*-missing-std-forward)
614 CompletionToken&& completion_token = default_completion_token{}) {
615 return boost::asio::async_initiate<CompletionToken, void(boost::system::error_code)>(
616 [this](auto&& completion_handler, TLS::Connection_Side connection_side) {
617 using completion_handler_t = std::decay_t<decltype(completion_handler)>;
618
619 const detail::AsyncHandshakeOperation<completion_handler_t, Stream> op{
620 std::forward<completion_handler_t>(completion_handler), *this, setup_native_handle(connection_side)};
621 },
622 completion_token,
623 side);
624 }
625
626 /**
627 * Not Implemented.
628 * @throws Not_Implemented todo
629 */
630 template <typename ConstBufferSequence, detail::basic_completion_token BufferedHandshakeHandler>
631 auto async_handshake([[maybe_unused]] Connection_Side side,
632 [[maybe_unused]] const ConstBufferSequence& buffers,
633 [[maybe_unused]] BufferedHandshakeHandler&& handler /* NOLINT(*missing-std-forward) */) {
634 throw Not_Implemented("buffered async handshake is not implemented");
635 }
636
637 //! @}
638 //! \name shutdown methods
639 //! @{
640
641 /**
642 * @brief Shut down SSL on the stream.
643 *
644 * This function is used to shut down SSL on the stream. The function call will block until SSL has been shut down
645 * or an error occurs. Note that this will not close the lowest layer.
646 *
647 * Note that this can be used in reaction of a received shutdown alert from the peer.
648 *
649 * @param ec Set to indicate what error occurred, if any.
650 */
651 void shutdown(boost::system::error_code& ec) {
652 ec = {};
653 if(async_write_in_flight(ec)) {
654 return;
655 }
656
657 ec = tls_close();
658 send_pending_encrypted_data(ec);
659 }
660
661 /**
662 * @brief Shut down SSL on the stream.
663 *
664 * This function is used to shut down SSL on the stream. The function call will block until SSL has been shut down
665 * or an error occurs. Note that this will not close the lowest layer.
666 *
667 * Note that this can be used in reaction of a received shutdown alert from the peer.
668 *
669 * @throws boost::system::system_error if error occurred
670 */
671 void shutdown() {
672 boost::system::error_code ec;
673 shutdown(ec);
674 boost::asio::detail::throw_error(ec, "shutdown");
675 }
676
677 private:
678 /**
679 * @brief Internal wrapper type to adapt the expected signature of `async_shutdown` to the completion handler
680 * signature of `AsyncWriteOperation`.
681 *
682 * This is boilerplate to ignore the `size_t` parameter that is passed to the completion handler of
683 * `AsyncWriteOperation`. Note that it needs to retain the wrapped handler's executor, allocator and
684 * cancellation slot.
685 */
686 template <typename Handler, typename Executor>
687 struct Wrapper {
688 void operator()(boost::system::error_code ec, std::size_t /*unused*/) { handler(ec); }
689
690 using executor_type = boost::asio::associated_executor_t<Handler, Executor>;
691
692 executor_type get_executor() const noexcept {
693 return boost::asio::get_associated_executor(handler, io_executor);
694 }
695
696 using allocator_type = boost::asio::associated_allocator_t<Handler>;
697
698 allocator_type get_allocator() const noexcept { return boost::asio::get_associated_allocator(handler); }
699
700 using cancellation_slot_type = boost::asio::associated_cancellation_slot_t<Handler>;
701
702 cancellation_slot_type get_cancellation_slot() const noexcept {
703 return boost::asio::get_associated_cancellation_slot(handler);
704 }
705
706 Handler handler; // NOLINT(*-non-private-member-variable*)
707 Executor io_executor; // NOLINT(*-non-private-member-variable*)
708 };
709
710 public:
711 /**
712 * @brief Asynchronously shut down SSL on the stream.
713 *
714 * This function call always returns immediately.
715 *
716 * Note that this can be used in reaction of a received shutdown alert from the peer.
717 *
718 * @param completion_token The completion handler to be called when the shutdown operation completes.
719 * The completion signature of the handler must be: void(boost::system::error_code).
720 */
721 template <detail::basic_completion_token CompletionToken = default_completion_token>
722 // NOLINTNEXTLINE(*-missing-std-forward)
723 auto async_shutdown(CompletionToken&& completion_token = default_completion_token{}) {
724 return boost::asio::async_initiate<CompletionToken, void(boost::system::error_code)>(
725 [this](auto&& completion_handler) {
726 using completion_handler_t = std::decay_t<decltype(completion_handler)>;
727 using write_handler_t = Wrapper<completion_handler_t, typename Stream::executor_type>;
728
729 // The operation closes the TLS session once no other write is in flight
730 const TLS::detail::AsyncWriteOperation<write_handler_t, Stream, boost::asio::const_buffer> op{
731 write_handler_t{std::forward<completion_handler_t>(completion_handler), get_executor()},
732 *this,
733 std::nullopt};
734 },
735 completion_token);
736 }
737
738 //! @}
739 //! \name I/O methods
740 //! @{
741
742 /**
743 * @brief Read some data from the stream.
744 *
745 * The function call will block until one or more bytes of data has been read successfully, or until an error
746 * occurs.
747 *
748 * @param buffers The buffers into which the data will be read.
749 * @param ec Set to indicate what error occurred, if any. Specifically, StreamTruncated will be set if the peer
750 * has closed the connection but did not properly shut down the SSL connection.
751 * @return The number of bytes read. Returns 0 if an error occurred.
752 */
753 template <typename MutableBufferSequence>
754 std::size_t read_some(const MutableBufferSequence& buffers, boost::system::error_code& ec) {
755 ec = {};
756
757 // Reading into a zero-byte buffer completes immediately, without
758 // touching the next layer.
759 if(boost::asio::buffer_size(buffers) == 0) {
760 return 0;
761 }
762
763 // Records this read generates could pile up behind that write
764 if(async_write_in_flight(ec) || native_handle_missing(ec)) {
765 return 0;
766 }
767
768 // We read from the socket until either some error occurred or we have
769 // decrypted at least one byte of application data.
770 while(!ec) {
771 // Some previous invocation of process_encrypted_data() generated
772 // application data in the output buffer that can now be returned.
773 // Records generated alongside (our close_notify in reply to the
774 // peer's, say) stay queued; the next operation writes them.
775 if(has_received_data()) {
776 return copy_received_data(buffers);
777 }
778
779 // Records generated while processing the peer's data (an alert, or
780 // our close_notify in reply to the peer's) go out before the
781 // condition they announce is reported and before we wait for more
782 // input.
783 if(has_data_to_send()) {
784 send_pending_encrypted_data(ec);
785 continue;
786 }
787
788 // Handle and report any TLS protocol errors (including a
789 // close_notify) that might have surfaced in a previous iteration
790 // (in `read_and_process_encrypted_data_from_peer()`). This makes
791 // sure that all received application data was handed out to the
792 // caller before reporting an error (e.g. EOF at the end of the
793 // stream).
794 handle_tls_protocol_errors(ec);
795
796 // If we don't have any plaintext application data, yet, we attempt
797 // to read more data from the peer. This reports network errors
798 // immediately. TLS protocol errors result in an internal state
799 // change which is handled by `handle_tls_protocol_errors()` in the
800 // next iteration.
801 read_and_process_encrypted_data_from_peer(ec);
802 }
803
804 return 0;
805 }
806
807 /**
808 * @brief Read some data from the stream.
809 *
810 * The function call will block until one or more bytes of data has been read successfully, or until an error
811 * occurs.
812 *
813 * @param buffers The buffers into which the data will be read.
814 * @return The number of bytes read. Returns 0 if an error occurred.
815 * @throws boost::system::system_error if error occurred
816 */
817 template <typename MutableBufferSequence>
818 std::size_t read_some(const MutableBufferSequence& buffers) {
819 boost::system::error_code ec;
820 const auto n = read_some(buffers, ec);
821 boost::asio::detail::throw_error(ec, "read_some");
822 return n;
823 }
824
825 /**
826 * @brief Write some data to the stream.
827 *
828 * The function call will block until one or more bytes of data has been written successfully, or until an error
829 * occurs.
830 *
831 * @param buffers The data to be written.
832 * @param ec Set to indicate what error occurred, if any.
833 * @return The number of bytes processed from the input buffers.
834 */
835 template <typename ConstBufferSequence>
836 std::size_t write_some(const ConstBufferSequence& buffers, boost::system::error_code& ec) {
837 ec = {};
838
839 // Writing from a zero-byte buffer completes immediately, without
840 // touching the next layer.
841 if(boost::asio::buffer_size(buffers) == 0) {
842 return 0;
843 }
844
845 if(async_write_in_flight(ec)) {
846 return 0;
847 }
848
849 ec = tls_encrypt(buffers);
850 if(ec) {
851 return 0;
852 }
853
854 // The input is processed once it is encrypted. Records the next layer
855 // did not accept stay queued and go out with the next operation.
856 send_pending_encrypted_data(ec);
857 return boost::asio::buffer_size(buffers);
858 }
859
860 /**
861 * @brief Write some data to the stream.
862 *
863 * The function call will block until one or more bytes of data has been written successfully, or until an error
864 * occurs.
865 *
866 * @param buffers The data to be written.
867 * @return The number of bytes written.
868 * @throws boost::system::system_error if error occurred
869 */
870 template <typename ConstBufferSequence>
871 std::size_t write_some(const ConstBufferSequence& buffers) {
872 boost::system::error_code ec;
873 const auto n = write_some(buffers, ec);
874 boost::asio::detail::throw_error(ec, "write_some");
875 return n;
876 }
877
878 /**
879 * @brief Start an asynchronous write. The function call always returns immediately.
880 *
881 * @param buffers The data to be written. Although the buffers object may be copied as necessary, ownership of
882 * the underlying buffers is retained by the caller, which must guarantee that they remain valid
883 * until the handler is called: the data is encrypted only once the operation's turn to write
884 * comes.
885 * @param completion_token The completion handler to be called when the write operation completes. Copies of the
886 * handler will be made as required. The completion signature of the handler must be:
887 * void(boost::system::error_code, std::size_t).
888 */
889 template <typename ConstBufferSequence,
890 detail::byte_size_completion_token CompletionToken = default_completion_token>
891 auto async_write_some(const ConstBufferSequence& buffers,
892 // NOLINTNEXTLINE(*-missing-std-forward)
893 CompletionToken&& completion_token = default_completion_token{}) {
894 return boost::asio::async_initiate<CompletionToken, void(boost::system::error_code, std::size_t)>(
895 [this](auto&& completion_handler, const auto& bufs) {
896 using completion_handler_t = std::decay_t<decltype(completion_handler)>;
897
898 // The operation encrypts the data once no other write is in flight
899 const detail::AsyncWriteOperation<completion_handler_t, Stream, ConstBufferSequence> op{
900 std::forward<completion_handler_t>(completion_handler), *this, bufs};
901 },
902 completion_token,
903 buffers);
904 }
905
906 /**
907 * @brief Start an asynchronous read. The function call always returns immediately.
908 *
909 * @param buffers The buffers into which the data will be read. Although the buffers object may be copied as
910 * necessary, ownership of the underlying buffers is retained by the caller, which must guarantee
911 * that they remain valid until the handler is called.
912 * @param completion_token The completion handler to be called when the read operation completes. The completion
913 * signature of the handler must be: void(boost::system::error_code, std::size_t).
914 */
915 template <typename MutableBufferSequence,
916 detail::byte_size_completion_token CompletionToken = default_completion_token>
917 auto async_read_some(const MutableBufferSequence& buffers,
918 // NOLINTNEXTLINE(*-missing-std-forward)
919 CompletionToken&& completion_token = default_completion_token{}) {
920 return boost::asio::async_initiate<CompletionToken, void(boost::system::error_code, std::size_t)>(
921 [this](auto&& completion_handler, const auto& bufs) {
922 using completion_handler_t = std::decay_t<decltype(completion_handler)>;
923
924 // A zero-byte read completes right away, even before the handshake
925 boost::system::error_code ec;
926 if(boost::asio::buffer_size(bufs) > 0) {
927 native_handle_missing(ec);
928 }
929
930 const detail::AsyncReadOperation<completion_handler_t, Stream, MutableBufferSequence> op{
931 std::forward<completion_handler_t>(completion_handler), *this, bufs, ec};
932 },
933 completion_token,
934 buffers);
935 }
936
937 //! @}
938
939 //! @brief Indicates whether a close_notify alert has been received from the peer.
940 //!
941 //! Note that we cannot m_core.is_closed_for_reading() because this wants to
942 //! explicitly check that the peer sent close_notify.
943 bool shutdown_received() const { return m_core->shutdown_received(); }
944
945 protected:
946 template <class H, class S, class M, class A>
947 friend class detail::AsyncReadOperation;
948 template <class H, class S, class B, class A>
949 friend class detail::AsyncWriteOperation;
950 template <class H, class S, class A>
951 friend class detail::AsyncHandshakeOperation;
952 template <class O, class S>
953 friend class detail::WriteQueuedStep;
954 template <class O, class S>
955 friend class detail::ReadAndProcessStep;
956
957 //! @brief Buffer space to read the peer's records into
958 boost::asio::mutable_buffer input_buffer() { return boost::asio::buffer(m_input_buffer_space); }
959
960 //! @brief Check if some operation is currently writing to the next layer
961 bool write_in_progress() const { return m_core->output_queue().write_in_progress(); }
962
963 //! @brief Synchronous operations must not run while an asynchronous write does; sets @p ec if that is the case
964 bool async_write_in_flight(boost::system::error_code& ec) const {
965 if(write_in_progress()) {
966 ec = boost::asio::error::already_started;
967 }
968 return write_in_progress();
969 }
970
971 //! @brief Nothing but a handshake may be attempted before the native handle exists; sets @p ec if it does not
972 bool native_handle_missing(boost::system::error_code& ec) const {
973 if(m_native_handle == nullptr) {
974 ec = ErrorType::InvalidObjectState;
975 }
976 return m_native_handle == nullptr;
977 }
978
979 //! @brief Lend the records to write next to the next layer, see detail::OutputQueue::begin_write()
980 boost::asio::const_buffer begin_write() { return m_core->output_queue().begin_write(); }
981
982 //! @brief Take back the records lent by begin_write() and wake up operations waiting for their turn to write
983 void end_write(std::size_t bytes_transferred) {
984 m_core->output_queue().end_write(bytes_transferred);
985 m_pending_write.cancel();
986 }
987
988 /**
989 * @brief Have read operations send whatever is queued before they report a condition or consume more input
990 *
991 * This covers the records generated while processing the peer's data (an alert, or our close_notify in
992 * reply to the peer's), but also records left behind by a failed write.
993 */
994 void mark_output_to_send() { m_core->output_queue().mark_pending(); }
995
996 //! @brief Check whether records marked by mark_output_to_send() are still waiting to be written
997 bool output_pending() const { return m_core->output_queue().pending(); }
998
999 /**
1000 * @brief Make progress on getting the records emitted so far onto the wire
1001 *
1002 * If another operation's write is in flight, waits for it to finish. Otherwise lends the queued
1003 * records to the next layer and writes them. Either way @p operation is resumed with the result
1004 * (operation_aborted if cancellation was requested in the meantime).
1005 */
1006 template <class Operation>
1007 void async_send_queued(Operation operation) {
1008 if(write_in_progress()) {
1009 m_pending_write.async_wait(detail::WaitForWriteStep<Operation>(std::move(operation)));
1010 } else {
1011 boost::asio::async_write(
1012 m_nextLayer, begin_write(), detail::WriteQueuedStep<Operation, Stream>(std::move(operation), *this));
1013 }
1014 }
1015
1016 /**
1017 * @brief Read from the next layer and hand the data to the TLS implementation
1018 *
1019 * @p operation is resumed with the result; TLS protocol errors are retained, see process_encrypted_data().
1020 */
1021 template <class Operation>
1022 void async_read_and_process(Operation operation) {
1023 m_nextLayer.async_read_some(input_buffer(),
1024 detail::ReadAndProcessStep<Operation, Stream>(std::move(operation), *this));
1025 }
1026
1027 //! @brief An EOF from the next layer without a prior close_notify from the peer means the stream was truncated
1028 void translate_eof(boost::system::error_code& ec) const {
1029 if(ec == boost::asio::error::eof && !shutdown_received()) {
1030 ec = StreamError::StreamTruncated;
1031 }
1032 }
1033
1034 //! @brief Check if decrypted data is available in the receive buffer
1035 bool has_received_data() const { return m_core->receive_buffer().size() > 0; }
1036
1037 //! @brief Copy decrypted data into the user-provided buffer
1038 template <typename MutableBufferSequence>
1039 std::size_t copy_received_data(MutableBufferSequence buffers) {
1040 // Note: It would be nice to avoid this buffer copy. This could be achieved by equipping the CallbacksT with
1041 // the user's desired target buffer once a read is started, and reading directly into that buffer in tls_record
1042 // received. However, we need to deal with the case that the receive buffer provided by the caller is smaller
1043 // than the decrypted record, so this optimization might not be worth the additional complexity.
1044 const auto copiedBytes = boost::asio::buffer_copy(buffers, m_core->receive_buffer().data());
1045 m_core->receive_buffer().consume(copiedBytes);
1046 return copiedBytes;
1047 }
1048
1049 //! @brief Check if records are waiting to be written (queued, or left behind by the last write)
1050 bool has_data_to_send() const { return m_core->output_queue().has_data(); }
1051
1052 /**
1053 * @brief Create the native handle.
1054 *
1055 * Depending on the desired connection side, this function will create a TLS::Client or a
1056 * TLS::Server.
1057 *
1058 * @param side The desired connection side (client or server)
1059 * @return the error that occurred, if any
1060 */
1061 boost::system::error_code setup_native_handle(Connection_Side side) {
1062 // Do not attempt to instantiate the native_handle when a custom (mocked) channel type template parameter has
1063 // been specified. This allows mocking the native_handle in test code.
1064 if constexpr(std::is_same_v<ChannelT, Channel>) {
1065 // A handshake was performed (or at least attempted) already
1066 if(m_native_handle != nullptr) {
1067 return ErrorType::InvalidObjectState;
1068 }
1069
1070 // Constructing the client emits the ClientHello. Nothing of a
1071 // failed attempt may be left behind for a retry.
1072 return call_tls_discarding_output([&] {
1073 if(side == Connection_Side::Client) {
1074 m_native_handle = std::unique_ptr<Client>(
1075 new Client(m_core,
1076 m_context->m_session_manager,
1077 m_context->m_credentials_manager,
1078 m_context->m_policy,
1079 m_context->m_rng,
1080 m_context->m_server_info,
1081 m_context->m_policy->latest_supported_version(false /* no DTLS */),
1082 m_context->m_app_protocols));
1083 } else {
1084 m_native_handle = std::unique_ptr<Server>(new Server(m_core,
1085 m_context->m_session_manager,
1086 m_context->m_credentials_manager,
1087 m_context->m_policy,
1088 m_context->m_rng,
1089 false /* no DTLS */));
1090 }
1091 });
1092 } else {
1093 return {};
1094 }
1095 }
1096
1097 /**
1098 * The `Stream` has to distinguish from network-related issues (that are
1099 * reported immediately) from TLS protocol errors, that must be retained
1100 * and emitted once all legal application traffic received before is
1101 * pushed to the downstream application.
1102 *
1103 * See also `process_encrypted_data()` and `StreamCallbacks::tls_alert()`
1104 * where those TLS protocol errors are detected and retained for eventual
1105 * handling in this method.
1106 *
1107 * See also https://github.com/randombit/botan/pull/3801 for a detailed
1108 * description of the ASIO stream's state management.
1109 *
1110 * @param ec this error code is set if we previously detected a TLS
1111 * protocol error.
1112 */
1113 void handle_tls_protocol_errors(boost::system::error_code& ec) {
1114 if(ec) {
1115 return;
1116 }
1117
1118 // If we had raised an error while processing TLS records received from
1119 // the peer, we expose that error here.
1120 //
1121 // See also `process_encrypted_data()`.
1122 else if(const auto error = error_from_us()) {
1123 ec = error;
1124 }
1125
1126 // If we had received a TLS alert from the peer, we expose that error
1127 // here. See also `StreamCallbacks::tls_alert()` where such alerts
1128 // would be detected and retained initially.
1129 //
1130 // Note that a close_notify is always a legal way for the peer to end a
1131 // TLS session. When received during the handshake it typically means
1132 // that the peer wanted to cancel the handshake for some reason not
1133 // related to the TLS protocol.
1134 else if(auto alert = alert_from_peer()) {
1135 if(alert->type() == AlertType::CloseNotify) {
1136 ec = boost::asio::error::eof;
1137 } else {
1138 ec = alert->type();
1139 }
1140 }
1141 }
1142
1143 /**
1144 * Reads TLS record data from the peer and forwards it to the native
1145 * handle for processing. Note that @p ec will reflect network errors
1146 * only. Any detected or received TLS protocol errors will be retained and
1147 * must be handled by the downstream operation in due time by invoking
1148 * `handle_tls_protocol_errors()`.
1149 *
1150 * @param ec this error code might be populated with network-related errors
1151 */
1152 void read_and_process_encrypted_data_from_peer(boost::system::error_code& ec) {
1153 if(ec) {
1154 return;
1155 }
1156
1157 // If we have received application data in a previous invocation, this
1158 // data needs to be passed to the application first. Otherwise, it
1159 // might get overwritten.
1160 if(has_received_data()) {
1161 throw Botan::Invalid_State("ASIO receive buffer not empty");
1162 }
1163
1164 if(error_from_us() || alert_from_peer()) {
1165 throw Botan::Invalid_State("ASIO TLS session no longer healthy");
1166 }
1167
1168 // If there's no existing error condition, read and process data from
1169 // the peer and report any sort of network error. TLS related errors do
1170 // not immediately cause an abort, they are checked in the invocation
1171 // via `error_from_us()`.
1172 const boost::asio::const_buffer read_buffer{input_buffer().data(), m_nextLayer.read_some(input_buffer(), ec)};
1173 translate_eof(ec);
1174 if(!ec) {
1175 process_encrypted_data(read_buffer);
1176 }
1177 }
1178
1179 /** @brief Synchronously write the records waiting to be written to the next layer.
1180 *
1181 * If this function is called with an error code other than 'Success', it will do nothing.
1182 *
1183 * @param ec Set to indicate what error occurred, if any. Specifically, StreamTruncated will be set if the peer
1184 * has closed the connection but did not properly shut down the SSL connection.
1185 */
1186 void send_pending_encrypted_data(boost::system::error_code& ec) {
1187 if(ec || async_write_in_flight(ec)) {
1188 return;
1189 }
1190
1191 // Records that could not be written stay in flight for the next attempt
1192 while(!ec && has_data_to_send()) {
1193 const auto written = boost::asio::write(m_nextLayer, begin_write(), ec);
1194 end_write(written);
1195 translate_eof(ec);
1196 }
1197 }
1198
1199 /**
1200 * @brief Close the TLS session, queueing a close_notify alert for sending
1201 *
1202 * @return the error that occurred, if any
1203 */
1204 boost::system::error_code tls_close() {
1205 boost::system::error_code ec;
1206 if(native_handle_missing(ec)) {
1207 return ec;
1208 }
1209
1210 return call_tls_discarding_output([&] { native_handle()->close(); });
1211 }
1212
1213 /**
1214 * @brief Pass plaintext data to the native handle for processing.
1215 *
1216 * The native handle will then create TLS records and hand them back to the Stream via the tls_emit_data callback.
1217 *
1218 * @return the error that occurred, if any
1219 */
1220 template <typename ConstBufferSequence>
1221 boost::system::error_code tls_encrypt(const ConstBufferSequence& buffers) {
1222 boost::system::error_code ec;
1223 if(native_handle_missing(ec) || output_failed(ec)) {
1224 return ec;
1225 }
1226
1227 // TODO: Once the TLS::Channel can deal with buffer sequences we can
1228 // save this copy. Until then we optimize for the smallest amount
1229 // of TLS records and flatten the boost buffer sequence.
1230 std::vector<uint8_t> copy_buffer;
1231 auto unpack = [&copy_buffer](const auto& bufs) -> std::span<const uint8_t> {
1232 const auto buffers_in_sequence =
1233 std::distance(boost::asio::buffer_sequence_begin(bufs), boost::asio::buffer_sequence_end(bufs));
1234
1235 if(buffers_in_sequence == 0) {
1236 return {};
1237 } else if(buffers_in_sequence == 1) {
1238 const boost::asio::const_buffer buf = *boost::asio::buffer_sequence_begin(bufs);
1239 return {static_cast<const uint8_t*>(buf.data()), buf.size()};
1240 } else {
1241 copy_buffer.resize(boost::asio::buffer_size(bufs));
1242 boost::asio::buffer_copy(boost::asio::buffer(copy_buffer), bufs);
1243 return copy_buffer;
1244 }
1245 };
1246
1247 // Flattening may fail to allocate, which leaves the TLS implementation untouched
1248 std::span<const uint8_t> plaintext;
1249 ec = try_with_error_code([&] { plaintext = unpack(buffers); });
1250 if(ec) {
1251 return ec;
1252 }
1253
1254 // NOTE: This is not asynchronous: it encrypts the data synchronously.
1255 // The data encrypted by native_handle()->send() is synchronously queued
1256 // in m_core, but is not actually written to the wire, yet.
1257 return call_tls_discarding_output([&] { native_handle()->send(plaintext); });
1258 }
1259
1260 /**
1261 * Pass encrypted data received from the peer to the native handle for
1262 * processing. If the @p read_buffer contains coalesced TLS records, this
1263 * might result in multiple TLS protocol state changes.
1264 *
1265 * To allow the ASIO stream wrapper to disentangle those state changes
1266 * properly, any TLS protocol errors are retained and must be handled by
1267 * calling `handle_tls_protocol_errors()` in due time.
1268 *
1269 * @param read_buffer Input buffer containing the encrypted data.
1270 */
1271 void process_encrypted_data(const boost::asio::const_buffer& read_buffer) {
1272 if(alert_from_peer() || error_from_us()) {
1273 throw Botan::Invalid_State("ASIO TLS session no longer healthy");
1274 }
1275
1276 // If the local TLS implementation generates an alert, we are notified
1277 // with an exception that is caught in call_tls(). The error code is
1278 // retained and not handled directly. Stream operations will have to
1279 // invoke `handle_tls_protocol_errors()` to handle them later. The
1280 // alert itself stays queued and is written before that.
1281 m_ec_from_last_read = call_tls_keeping_output([&] {
1282 native_handle()->received_data({static_cast<const uint8_t*>(read_buffer.data()), read_buffer.size()});
1283 });
1284
1285 // Whatever the TLS implementation generated in response (an alert, or
1286 // our close_notify in reply to the peer's) must be written before the
1287 // condition it announces is reported.
1288 mark_output_to_send();
1289 }
1290
1291 //! @brief Run @p f, turning an exception into the error code returned
1292 template <typename Fun>
1293 static boost::system::error_code try_with_error_code(Fun f) {
1294 try {
1295 f();
1296 } catch(const TLS_Exception& e) {
1297 return e.type();
1298 } catch(const Exception& e) {
1299 return e.error_type();
1300 } catch(const std::bad_alloc&) {
1301 return ErrorType::OutOfMemory;
1302 } catch(const std::exception&) {
1303 return ErrorType::Unknown;
1304 }
1305 return {};
1306 }
1307
1308 /**
1309 * @brief Call into the TLS implementation to process the peer's data
1310 *
1311 * The records emitted stay queued even if the call fails: the TLS
1312 * implementation sends a fatal alert before it reports a failure, and
1313 * that alert must reach the peer. They are discarded only once output
1314 * failed beyond repair, see call_tls().
1315 *
1316 * @return the error that occurred, if any
1317 */
1318 template <typename Fun>
1319 boost::system::error_code call_tls_keeping_output(Fun f) {
1320 return call_tls(f, false);
1321 }
1322
1323 /**
1324 * @brief Call into the TLS implementation to produce output
1325 *
1326 * Refused once output failed before. The records emitted by a failed
1327 * call are discarded: the TLS implementation emits one record at a time,
1328 * and nothing of input reported as unprocessed may reach the peer.
1329 *
1330 * @return the error that occurred, if any
1331 */
1332 template <typename Fun>
1333 boost::system::error_code call_tls_discarding_output(Fun f) {
1334 boost::system::error_code ec;
1335 if(output_failed(ec)) {
1336 return ec;
1337 }
1338
1339 return call_tls(f, true);
1340 }
1341
1342 //! @brief Sets @p ec if the TLS implementation must not produce further output, see call_tls()
1343 bool output_failed(boost::system::error_code& ec) const {
1344 if(m_ec_from_failed_output) {
1345 ec = m_ec_from_failed_output;
1346 }
1347 return static_cast<bool>(m_ec_from_failed_output);
1348 }
1349
1350 /**
1351 * @brief Call into the TLS implementation, which may emit records.
1352 *
1353 * The TLS implementation advances its record sequence number before it
1354 * emits a record. Once a call failed on an active connection, or a
1355 * record could not be buffered (which the TLS implementation swallows
1356 * for alerts), the peer could not authenticate anything emitted
1357 * afterwards: that failure is retained, the records of that call and of
1358 * any later one are discarded, and output is refused from then on, see
1359 * call_tls_discarding_output().
1360 *
1361 * @param f the call
1362 * @param discard_output_on_failure whether to drop the records a failed call emitted
1363 * @return the error that occurred, if any
1364 */
1365 template <typename Fun>
1366 boost::system::error_code call_tls(Fun f, bool discard_output_on_failure) {
1367 auto& output = m_core->output_queue();
1368 const auto queued_before = output.queued_size();
1369
1370 auto ec = try_with_error_code(f);
1371 const auto emit_failure = m_core->take_emit_failure();
1372 if(emit_failure && !ec) {
1373 ec = try_with_error_code([&] { std::rethrow_exception(emit_failure); });
1374 }
1375
1376 // A failure before the connection is active leaves no state behind,
1377 // unless a record went missing (the TLS implementation then considers
1378 // itself closed after a close_notify it never emitted, for instance)
1379 if(ec && !m_ec_from_failed_output && m_native_handle != nullptr &&
1380 (emit_failure || m_native_handle->is_active())) {
1381 m_ec_from_failed_output = ec;
1382 }
1383
1384 if(m_ec_from_failed_output || (ec && discard_output_on_failure)) {
1385 output.truncate(queued_before);
1386 }
1387
1388 return ec;
1389 }
1390
1391 private:
1392 /**
1393 * Returns any alert previously received from the peer. This may include
1394 * close_notify. Once the peer has sent any alert, no more data must be
1395 * read from the stream.
1396 */
1397 std::optional<Alert> alert_from_peer() const { return m_core->alert_from_peer(); }
1398
1399 /**
1400 * Returns any error code produced by the local TLS implementation. This
1401 * will _not_ include close_notify. Once our TLS stack has reported an
1402 * error, no more data must be written to the stream. The peer will receive
1403 * the error as a TLS alert.
1404 */
1405 boost::system::error_code error_from_us() const { return m_ec_from_last_read; }
1406
1407 protected:
1408 using timer_type = boost::asio::basic_waitable_timer<std::chrono::steady_clock,
1409 boost::asio::wait_traits<std::chrono::steady_clock>,
1410 executor_type>;
1411
1412 std::shared_ptr<Context> m_context; // NOLINT(*-non-private-member-variable*)
1413 StreamLayer m_nextLayer; // NOLINT(*-non-private-member-variable*)
1414
1415 std::shared_ptr<StreamCallbacks> m_core; // NOLINT(*-non-private-member-variable*)
1416 // Marks m_core as in use by this stream, see StreamCallbacks::bind_to_stream()
1417 std::shared_ptr<const void> m_core_token; // NOLINT(*-non-private-member-variable*)
1418 std::unique_ptr<ChannelT> m_native_handle; // NOLINT(*-non-private-member-variable*)
1419 boost::system::error_code m_ec_from_last_read; // NOLINT(*-non-private-member-variable*)
1420 // Retained once the TLS implementation failed on an active connection, see call_tls()
1421 boost::system::error_code m_ec_from_failed_output; // NOLINT(*-non-private-member-variable*)
1422
1423 // Buffer space used to read input intended for the core
1424 std::vector<uint8_t> m_input_buffer_space; // NOLINT(*-non-private-member-variable*)
1425
1426 // Never expires; operations wait on it for the write in flight to finish, see async_send_queued()
1427 timer_type m_pending_write; // NOLINT(*-non-private-member-variable*)
1428};
1429
1430// deduction guides for convenient construction from an existing
1431// underlying transport stream T
1432template <typename T>
1433Stream(Server_Information, T) -> Stream<T>;
1434template <typename T>
1435Stream(std::shared_ptr<Context>, std::shared_ptr<StreamCallbacks>, T) -> Stream<T>;
1436template <typename T>
1437Stream(std::shared_ptr<Context>, T) -> Stream<T>;
1438template <typename T>
1439Stream(T, std::shared_ptr<Context>) -> Stream<T>;
1440
1441} // namespace Botan::TLS
1442
1443#endif
1444#endif // BOTAN_ASIO_STREAM_H_
constexpr void unpack(Polynomial< PolyTrait, D > &p, ByteSourceT &byte_source, UnmapFnT unmap)
@ MAX_CIPHERTEXT_SIZE
Definition tls_magic.h:40