Botan 3.14.1
Crypto and TLS for C&
asio_async_ops.h
Go to the documentation of this file.
1/*
2* Helpers for TLS ASIO Stream
3* (C) 2018-2020 Jack Lloyd
4* 2018-2020 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_ASYNC_OPS_H_
11#define BOTAN_ASIO_ASYNC_OPS_H_
12
13#include <botan/asio_compat.h>
14#if defined(BOTAN_FOUND_COMPATIBLE_BOOST_ASIO_VERSION)
15
16 #include <botan/asio_error.h>
17
18 // We need to define BOOST_ASIO_DISABLE_SERIAL_PORT before any asio imports. Otherwise asio will include <termios.h>,
19 // which interferes with Botan's amalgamation by defining macros like 'B0' and 'FF1'.
20 #define BOOST_ASIO_DISABLE_SERIAL_PORT
21 #include <boost/asio.hpp>
22 #include <boost/asio/yield.hpp>
23 #include <boost/beast/core/bind_handler.hpp>
24
25 #include <optional>
26
27namespace Botan::TLS::detail {
28
29/**
30 * Base class for asynchronous stream operations.
31 *
32 * Asynchronous operations, used for example to implement an interface for boost::asio::async_read_some and
33 * boost::asio::async_write_some, are based on boost::asio::coroutines. Derived operations implement a call
34 * operator and invoke it upon construction. Whenever they need the next layer they `yield` to one of the
35 * steps the stream provides (Stream::async_send_queued() and Stream::async_read_and_process()), which resume
36 * the call operator with their result:
37 *
38 * ```
39 * void operator()(boost::system::error_code ec, bool isContinuation = true)
40 * {
41 * reenter(this)
42 * {
43 * // operation specific logic, repeatedly interacting with the stream and, via the steps, the next layer
44 * yield m_stream.async_read_and_process(std::move(*this));
45 *
46 * // make sure the handler is not invoked from within the initiating function
47 * if(!isContinuation)
48 * {
49 * yield post_resumption(std::move(*this), ec);
50 * }
51 *
52 * // call the completion handler
53 * complete_now(error_code, bytes_transferred);
54 * }
55 * }
56 * ```
57 *
58 * The call operator needs to make sure that the user-provided handler is not called directly from the
59 * initiating function. Once the operation is ready to call the completion handler it checks if it was resumed
60 * at least once using the `isContinuation` parameter. If not, it posts itself to its executor and `yield`s. As
61 * a result, the call operator will be invoked again, this time as a continuation, and will jump to the location
62 * where it yielded before using `reenter`. It is now safe to call the handler function via `complete_now`.
63 *
64 * The operations forward the associations of the user-provided handler (executor, allocator and cancellation
65 * slot) to the operations they start on the next layer. Cancellation requested by the caller therefore reaches
66 * whatever the operation is currently waiting for.
67 *
68 * \tparam Handler Type of the completion handler
69 * \tparam Executor1 Type of the asio executor (usually derived from the lower layer)
70 * \tparam Allocator Type of the allocator to be used
71 */
72template <class Handler, class Executor1, class Allocator>
73class AsyncBase : public boost::asio::coroutine {
74 public:
75 using allocator_type = boost::asio::associated_allocator_t<Handler, Allocator>;
76 using executor_type = boost::asio::associated_executor_t<Handler, Executor1>;
77 using cancellation_slot_type = boost::asio::cancellation_slot;
78
79 allocator_type get_allocator() const noexcept { return boost::asio::get_associated_allocator(m_handler); }
80
81 executor_type get_executor() const noexcept {
82 return boost::asio::get_associated_executor(m_handler, m_work_guard_1.get_executor());
83 }
84
85 cancellation_slot_type get_cancellation_slot() const noexcept { return m_cancellation_state.slot(); }
86
87 /**
88 * Check whether the caller requested cancellation of this operation.
89 *
90 * Operations on the next layer are connected to a child of the handler's
91 * cancellation slot and complete with operation_aborted on their own.
92 * This is for the steps that have no such operation to abort, e.g.
93 * waiting for another write to finish.
94 */
95 bool cancelled() const noexcept {
96 return m_cancellation_state.cancelled() != boost::asio::cancellation_type::none;
97 }
98
99 protected:
100 template <class HandlerT>
101 AsyncBase(HandlerT&& handler, const Executor1& executor) :
102 m_handler(std::forward<HandlerT>(handler)),
103 m_work_guard_1(executor),
104 m_cancellation_state(boost::asio::get_associated_cancellation_slot(m_handler)) {}
105
106 /**
107 * Drop the cancellation handler that the last operation on the next
108 * layer installed in our slot. It refers to that operation's state,
109 * which is gone once the operation completed; a cancellation emitted
110 * later must not reach it. Call this at the start of every continuation.
111 */
112 void reset_cancellation_slot() { m_cancellation_state.slot().clear(); }
113
114 /**
115 * Call the completion handler.
116 *
117 * This function should only be called after an intermediate initiating function has been called.
118 *
119 * @param args Arguments forwarded to the completion handler function.
120 */
121 template <class... Args>
122 void complete_now(Args&&... args) {
123 reset_cancellation_slot();
124 m_work_guard_1.reset();
125 m_handler(std::forward<Args>(args)...);
126 }
127
128 Handler m_handler; // NOLINT(*-non-private-member-variable*)
129 boost::asio::executor_work_guard<Executor1> m_work_guard_1; // NOLINT(*-non-private-member-variable*)
130 boost::asio::cancellation_state m_cancellation_state; // NOLINT(*-non-private-member-variable*)
131};
132
133/**
134 * Resume @p operation with @p ec from its executor, i.e. not from within the initiating function.
135 */
136template <class Operation>
137void post_resumption(Operation&& operation, boost::system::error_code ec) {
138 // The executor must be fetched before the operation is moved into the bound handler
139 const auto executor = operation.get_executor();
140 boost::asio::post(executor, boost::beast::bind_front_handler(std::forward<Operation>(operation), ec));
141}
142
143/**
144 * Base class for the steps an operation performs on the next layer.
145 *
146 * A step holds the operation that started it, forwards the operation's
147 * associations to the next layer meanwhile, and resumes the operation with
148 * its result once done.
149 *
150 * \tparam Operation Type of the operation, derived from AsyncBase
151 */
152template <class Operation>
153class StepBase {
154 public:
155 using allocator_type = typename Operation::allocator_type;
156 using executor_type = typename Operation::executor_type;
157 using cancellation_slot_type = typename Operation::cancellation_slot_type;
158
159 allocator_type get_allocator() const noexcept { return m_operation.get_allocator(); }
160
161 executor_type get_executor() const noexcept { return m_operation.get_executor(); }
162
163 cancellation_slot_type get_cancellation_slot() const noexcept { return m_operation.get_cancellation_slot(); }
164
165 protected:
166 explicit StepBase(Operation operation) : m_operation(std::move(operation)) {}
167
168 /**
169 * Resume the operation with the step's result.
170 *
171 * A cancellation requested in the meantime is reported as
172 * operation_aborted, whether or not it aborted the step's operation on
173 * the next layer.
174 */
175 void resume(boost::system::error_code ec) {
176 if(!ec && m_operation.cancelled()) {
177 ec = boost::asio::error::operation_aborted;
178 }
179
180 auto operation = std::move(m_operation);
181 operation(ec);
182 }
183
184 private:
185 Operation m_operation;
186};
187
188/**
189 * Wait for the write in flight to finish, see Stream::async_send_queued().
190 */
191template <class Operation>
192class WaitForWriteStep : public StepBase<Operation> {
193 public:
194 explicit WaitForWriteStep(Operation operation) : StepBase<Operation>(std::move(operation)) {}
195
196 // The wait is interrupted once the write in flight ends, see Stream::end_write()
197 void operator()(const boost::system::error_code& /* interruption */) { this->resume({}); }
198};
199
200/**
201 * Write the records lent by Stream::begin_write(), see Stream::async_send_queued().
202 */
203template <class Operation, class Stream>
204class WriteQueuedStep : public StepBase<Operation> {
205 public:
206 WriteQueuedStep(Operation operation, Stream& stream) :
207 StepBase<Operation>(std::move(operation)), m_stream(stream) {}
208
209 void operator()(boost::system::error_code ec, std::size_t bytes_transferred) {
210 m_stream.translate_eof(ec);
211 m_stream.end_write(bytes_transferred);
212 this->resume(ec);
213 }
214
215 private:
216 Stream& m_stream;
217};
218
219/**
220 * Hand what was read from the next layer to the TLS implementation, see Stream::async_read_and_process().
221 */
222template <class Operation, class Stream>
223class ReadAndProcessStep : public StepBase<Operation> {
224 public:
225 ReadAndProcessStep(Operation operation, Stream& stream) :
226 StepBase<Operation>(std::move(operation)), m_stream(stream) {}
227
228 void operator()(boost::system::error_code ec, std::size_t bytes_transferred) {
229 m_stream.translate_eof(ec);
230 if(!ec && bytes_transferred > 0) {
231 m_stream.process_encrypted_data(
232 boost::asio::const_buffer(m_stream.input_buffer().data(), bytes_transferred));
233 }
234 this->resume(ec);
235 }
236
237 private:
238 Stream& m_stream;
239};
240
241template <class Handler, class Stream, class MutableBufferSequence, class Allocator = std::allocator<void>>
242class AsyncReadOperation : public AsyncBase<Handler, typename Stream::executor_type, Allocator> {
243 public:
244 /**
245 * Construct and invoke an AsyncReadOperation.
246 *
247 * @param handler Handler function to be called upon completion.
248 * @param stream The stream from which the data will be read
249 * @param buffers The buffers into which the data will be read.
250 * @param ec Optional error code; used to report an error to the handler function.
251 */
252 template <class HandlerT>
253 AsyncReadOperation(HandlerT&& handler,
254 Stream& stream,
255 const MutableBufferSequence& buffers,
256 const boost::system::error_code& ec = {}) :
257 AsyncBase<Handler, typename Stream::executor_type, Allocator>(std::forward<HandlerT>(handler),
258 stream.get_executor()),
259 m_stream(stream),
260 m_buffers(buffers),
261 m_decodedBytes(0) {
262 this->operator()(ec, false);
263 }
264
265 AsyncReadOperation(const AsyncReadOperation& other) = delete;
266 AsyncReadOperation(AsyncReadOperation&& other) = default;
267 AsyncReadOperation& operator=(const AsyncReadOperation& other) = delete;
268 AsyncReadOperation& operator=(AsyncReadOperation&& other) = delete;
269 ~AsyncReadOperation() = default;
270
271 /**
272 * Read and decrypt application data from the peer. Note, that this is
273 * unsuitable to receive initial handshake records! Post-handshake
274 * messages like KeyUpdate will transparently work, though.
275 *
276 * Depending on the situation, this handler will:
277 *
278 * 1. Copy any received application data out to the downstream application
279 * and finalize this operation, or
280 * 2. Make sure the TLS records the TLS implementation generated while
281 * processing the peer's data (e.g. an alert) were written, or
282 * 3. Handle any pending TLS protocol errors and (if none were found) wait
283 * for more data from the peer, expecting to find:
284 * * a complete and decryptable application data record,
285 * * a TLS alert (e.g. close_notify)
286 */
287 void operator()(boost::system::error_code ec, bool isContinuation = true) {
288 this->reset_cancellation_slot();
289
290 reenter(this) {
291 // "Reading" into a zero-byte buffer completes immediately, without
292 // touching the next layer.
293 while(!ec && boost::asio::buffer_size(m_buffers) > 0) {
294 // If the "input buffer" holds successfully decrypted application
295 // data, we copy it to the "output buffers" and finalize the
296 // operation with the number of produced bytes. Records generated
297 // alongside (our close_notify in reply to the peer's, say) stay
298 // queued; the next operation writes them.
299 if(m_stream.has_received_data()) {
300 m_decodedBytes = m_stream.copy_received_data(m_buffers);
301 break;
302 }
303
304 // Whatever is queued for sending (records generated while
305 // processing the peer's data, or left behind by a failed write)
306 // must be on the wire before the condition it announces is
307 // reported and before we consume more input. Another operation
308 // may be sending it already; what matters is that it gets
309 // written.
310 m_stream.mark_output_to_send();
311 if(m_stream.output_pending()) {
312 yield m_stream.async_send_queued(std::move(*this));
313 continue;
314 }
315
316 // Ensure that no TLS protocol error was detected until now.
317 // Otherwise the read operation is aborted with an error code.
318 m_stream.handle_tls_protocol_errors(ec);
319 if(ec) {
320 break;
321 }
322
323 // Wait for more incoming data and hand it to the native handle
324 // for processing. When enough bytes were received to decrypt an
325 // application data record, the "input buffer" will become
326 // non-empty.
327 yield m_stream.async_read_and_process(std::move(*this));
328 }
329
330 if(!isContinuation) {
331 // Make sure the handler is not called from within the initiating function
332 yield post_resumption(std::move(*this), ec);
333 }
334
335 this->complete_now(ec, m_decodedBytes);
336 }
337 }
338
339 private:
340 Stream& m_stream;
341 MutableBufferSequence m_buffers;
342 std::size_t m_decodedBytes;
343};
344
345template <typename Handler, class Stream, class ConstBufferSequence, class Allocator = std::allocator<void>>
346class AsyncWriteOperation : public AsyncBase<Handler, typename Stream::executor_type, Allocator> {
347 public:
348 /**
349 * Construct and invoke an AsyncWriteOperation.
350 *
351 * @param handler Handler function to be called upon completion.
352 * @param stream The stream to which the data will be written
353 * @param plaintext Application data to be encrypted and written, or std::nullopt to shut down the TLS session
354 * instead, i.e. to write a close_notify alert.
355 */
356 template <class HandlerT>
357 AsyncWriteOperation(HandlerT&& handler, Stream& stream, std::optional<ConstBufferSequence> plaintext) :
358 AsyncBase<Handler, typename Stream::executor_type, Allocator>(std::forward<HandlerT>(handler),
359 stream.get_executor()),
360 m_stream(stream),
361 m_plaintext(std::move(plaintext)),
362 m_plainBytesTransferred(0) {
363 this->operator()(boost::system::error_code{}, false);
364 }
365
366 AsyncWriteOperation(const AsyncWriteOperation& other) = delete;
367 AsyncWriteOperation(AsyncWriteOperation&& other) = default;
368 AsyncWriteOperation& operator=(const AsyncWriteOperation& other) = delete;
369 AsyncWriteOperation& operator=(AsyncWriteOperation&& other) = delete;
370 ~AsyncWriteOperation() = default;
371
372 /**
373 * Encrypt the plaintext (or shut down the TLS session) and write the
374 * resulting TLS records from the output queue to the wire.
375 *
376 * Depending on the situation, this handler will:
377 *
378 * 1. Wait for another operation's write to finish, or
379 * 2. Hand the plaintext to the TLS implementation for encryption (or
380 * close the TLS session), or
381 * 3. Send the resulting records to the peer.
382 */
383 void operator()(boost::system::error_code ec, bool isContinuation = true) {
384 this->reset_cancellation_slot();
385
386 reenter(this) {
387 // Writing from a zero-byte buffer completes immediately, without
388 // touching the stream or the next layer.
389 if(!empty_write()) {
390 // Only one operation at a time writes to the next layer. Waiting
391 // for our turn before generating any records ensures that they are
392 // sent by this operation alone, so that a failure to send them is
393 // reported to our handler.
394 while(!ec && m_stream.write_in_progress()) {
395 yield m_stream.async_send_queued(std::move(*this));
396 }
397
398 if(!ec) {
399 if(m_plaintext.has_value()) {
400 // On failure, tls_encrypt() discards whatever records the
401 // TLS implementation generated from the plaintext, so that
402 // nothing of input reported as unprocessed reaches the peer.
403 ec = m_stream.tls_encrypt(*m_plaintext);
404
405 if(!ec) {
406 // The size of the sent TLS records can differ from the size of the payload due to TLS
407 // encryption. We need to tell the handler how many bytes of the original data we processed.
408 m_plainBytesTransferred = boost::asio::buffer_size(*m_plaintext);
409 }
410 } else {
411 ec = m_stream.tls_close();
412 }
413 }
414
415 // Records a concurrent read operation generates in the meantime are
416 // sent as well. That operation waits for them to be written before
417 // it reports whatever they announce, and sends them itself should
418 // our write fail.
419 while(!ec && m_stream.has_data_to_send()) {
420 yield m_stream.async_send_queued(std::move(*this));
421 }
422 }
423
424 if(!isContinuation) {
425 // Make sure the handler is not called from within the initiating function
426 yield post_resumption(std::move(*this), ec);
427 }
428
429 this->complete_now(ec, m_plainBytesTransferred);
430 }
431 }
432
433 private:
434 bool empty_write() const { return m_plaintext.has_value() && boost::asio::buffer_size(*m_plaintext) == 0; }
435
436 Stream& m_stream;
437 std::optional<ConstBufferSequence> m_plaintext;
438 std::size_t m_plainBytesTransferred;
439};
440
441template <class Handler, class Stream, class Allocator = std::allocator<void>>
442class AsyncHandshakeOperation : public AsyncBase<Handler, typename Stream::executor_type, Allocator> {
443 public:
444 /**
445 * Construct and invoke an AsyncHandshakeOperation.
446 *
447 * @param handler Handler function to be called upon completion.
448 * @param stream The stream from which the data will be read
449 * @param ec Optional error code; used to report an error to the handler function.
450 */
451 template <class HandlerT>
452 AsyncHandshakeOperation(HandlerT&& handler, Stream& stream, const boost::system::error_code& ec = {}) :
453 AsyncBase<Handler, typename Stream::executor_type, Allocator>(std::forward<HandlerT>(handler),
454 stream.get_executor()),
455 m_stream(stream) {
456 this->operator()(ec, false);
457 }
458
459 AsyncHandshakeOperation(const AsyncHandshakeOperation& other) = delete;
460 AsyncHandshakeOperation(AsyncHandshakeOperation&& other) = default;
461 AsyncHandshakeOperation& operator=(const AsyncHandshakeOperation& other) = delete;
462 AsyncHandshakeOperation& operator=(AsyncHandshakeOperation&& other) = delete;
463 ~AsyncHandshakeOperation() = default;
464
465 /**
466 * Perform a TLS handshake with the peer.
467 *
468 * Depending on the situation, this handler will:
469 *
470 * 1. Send pending data to the peer, or
471 * 2. Finalize the handshake, or
472 * 3. Handle any pending TLS protocol errors and (if none were found) wait
473 * for more data from the peer and process it, which potentially:
474 * * generates a response (another handshake flight, or an alert) or
475 * * finalizes the handshake.
476 */
477 void operator()(boost::system::error_code ec, bool isContinuation = true) {
478 this->reset_cancellation_slot();
479
480 reenter(this) {
481 while(!ec) {
482 // If we have data to be sent to the peer, we do that now. Note that
483 // this might either be a flight in our handshake, or a TLS alert
484 // record if we decided to abort due to some failure.
485 if(m_stream.has_data_to_send()) {
486 yield m_stream.async_send_queued(std::move(*this));
487 continue;
488 }
489
490 // Once the underlying TLS implementation reports a complete and
491 // successful handshake we're done.
492 if(m_stream.native_handle()->is_handshake_complete()) {
493 break;
494 }
495
496 // Ensure that no TLS protocol error was detected until now.
497 // Otherwise the handshake is aborted with an error code.
498 m_stream.handle_tls_protocol_errors(ec);
499 if(ec) {
500 break;
501 }
502
503 // The handshake is neither finished nor aborted. Wait for more
504 // data from the peer and hand it to the native handle for
505 // processing. This will result in the advancement of the
506 // handshake state and produce data in the output buffer.
507 yield m_stream.async_read_and_process(std::move(*this));
508 }
509
510 if(!isContinuation) {
511 // Make sure the handler is not called from within the initiating function
512 yield post_resumption(std::move(*this), ec);
513 }
514
515 this->complete_now(ec);
516 }
517 }
518
519 private:
520 Stream& m_stream;
521};
522
523} // namespace Botan::TLS::detail
524
525 #include <boost/asio/unyield.hpp>
526
527#endif
528#endif // BOTAN_ASIO_ASYNC_OPS_H_