• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

randombit / botan / 19078852043

04 Nov 2025 12:08PM UTC coverage: 90.688% (+0.009%) from 90.679%
19078852043

push

github

web-flow
Merge pull request #5076 from reneme/feature/ascon_aead128

Feature: Ascon-AEAD128

100608 of 110939 relevant lines covered (90.69%)

12613541.58 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

87.53
/src/bogo_shim/bogo_shim.cpp
1
/*
2
* (C) 2019 Jack Lloyd
3
*
4
* Botan is released under the Simplified BSD License (see license.txt)
5
*/
6

7
/*
8
* This is a shim for testing Botan against BoringSSL's test TLS stack (BoGo).
9
*
10
* Instructions on use should go here.
11
*/
12

13
#include <botan/base64.h>
14
#include <botan/chacha_rng.h>
15
#include <botan/data_src.h>
16
#include <botan/hex.h>
17
#include <botan/mem_ops.h>
18
#include <botan/ocsp.h>
19
#include <botan/pkcs8.h>
20
#include <botan/tls_algos.h>
21
#include <botan/tls_client.h>
22
#include <botan/tls_exceptn.h>
23
#include <botan/tls_messages.h>
24
#include <botan/tls_server.h>
25
#include <botan/tls_session_manager_hybrid.h>
26
#include <botan/tls_session_manager_memory.h>
27
#include <botan/internal/fmt.h>
28
#include <botan/internal/loadstor.h>
29
#include <botan/internal/parsing.h>
30
#include <botan/internal/stl_util.h>
31
#include <botan/internal/target_info.h>
32

33
#include <cstring>
34
#include <ctime>
35
#include <fstream>
36
#include <iomanip>
37
#include <iostream>
38
#include <map>
39
#include <memory>
40
#include <set>
41
#include <string>
42
#include <unordered_map>
43
#include <vector>
44

45
#if defined(BOTAN_TARGET_OS_HAS_SOCKETS)
46
   #include <errno.h>
47
   #include <fcntl.h>
48
   #include <netdb.h>
49
   #include <netinet/in.h>
50
   #include <string.h>
51
   #include <sys/socket.h>
52
   #include <sys/time.h>
53
   #include <unistd.h>
54
#endif
55

56
namespace {
57

58
int shim_output(const std::string& s, int rc = 0) {
1✔
59
   std::cout << s << "\n";
1✔
60
   return rc;
1✔
61
}
62

63
void shim_log(std::string_view s) {
87,692✔
64
   static const auto log_path = []() -> std::string {
2,107✔
65
      const char* env = ::getenv("BOTAN_BOGO_SHIM_LOG");
2,107✔
66
      if(env == nullptr) {
2,107✔
67
         return {};
2,107✔
68
      }
69

70
      auto log_file_path = std::string(env);
×
71
      if(log_file_path.empty() || log_file_path == "1") {
×
72
         return "/tmp/bogo_shim.log";
×
73
      }
74
      return env;
×
75
   }();
87,692✔
76

77
   if(!log_path.empty()) {
87,692✔
78
      static std::ofstream g_log(log_path, std::ios::out | std::ios::trunc);
×
79
      if(g_log.is_open() && g_log.good()) {
×
80
         const auto duration = std::chrono::system_clock::now().time_since_epoch();
×
81
         const auto seconds = std::chrono::duration_cast<std::chrono::duration<double>>(duration);
×
82

83
         g_log << std::fixed << std::setprecision(6) << seconds.count() << ": " << s << std::endl;
×
84
      }
85
   }
86
}
87,692✔
87

88
[[noreturn]] void shim_exit_with_error(const std::string& s, int rc = 1) noexcept {
823✔
89
   shim_log("Exiting with " + s);
823✔
90
   std::cerr << s << "\n";
823✔
91
   std::exit(rc);
823✔
92
}
93

94
std::string map_to_bogo_error(const std::string& e) noexcept {
804✔
95
   shim_log("Original error " + e);
804✔
96

97
   static const std::unordered_map<std::string, std::string> err_map{
804✔
98
      {"Application data before handshake done", ":APPLICATION_DATA_INSTEAD_OF_HANDSHAKE:"},
99
      {"Bad Hello_Request, has non-zero size", ":BAD_HELLO_REQUEST:"},
100
      {"Bad code for TLS alert level", ":UNKNOWN_ALERT_TYPE:"},
101
      {"Bad encoding on signature algorithms extension", ":DECODE_ERROR:"},
102
      {"Bad extension size", ":DECODE_ERROR:"},
103
      {"Bad length in hello verify request", ":DECODE_ERROR:"},
104
      {"Bad lengths in DTLS header", ":BAD_HANDSHAKE_RECORD:"},
105
      {"Bad signature on server key exchange", ":BAD_SIGNATURE:"},
106
      {"Server certificate verification failed", ":BAD_SIGNATURE:"},
107
      {"compression is not supported in TLS 1.3", ":DECODE_ERROR:"},
108
      {"Cookie length must be at least 1 byte", ":DECODE_ERROR:"},
109
      {"Bad size (1) for TLS alert message", ":BAD_ALERT:"},
110
      {"Bad size (4) for TLS alert message", ":BAD_ALERT:"},
111
      {"CERTIFICATE decoding failed with PEM: No PEM header found", ":CANNOT_PARSE_LEAF_CERT:"},
112
      {"Certificate usage constraints do not allow signing", ":KEY_USAGE_BIT_INCORRECT:"},
113
      {"Can't agree on a ciphersuite with client", ":NO_SHARED_CIPHER:"},
114
      {"Can't interleave application and handshake data", ":UNEXPECTED_RECORD:"},
115
      {"Certificate chain exceeds policy specified maximum size", ":EXCESSIVE_MESSAGE_SIZE:"},
116
      {"Certificate key type did not match ciphersuite", ":WRONG_CERTIFICATE_TYPE:"},
117
      {"Certificate usage constraints do not allow this ciphersuite", ":KEY_USAGE_BIT_INCORRECT:"},
118
      {"Certificate: Message malformed", ":DECODE_ERROR:"},
119
      {"Certificate_Request context must be empty in the main handshake", ":DECODE_ERROR:"},
120
      {"Certificate_Request message did not provide a signature_algorithms extension", ":DECODE_ERROR:"},
121
      {"Channel_Impl_12::key_material_export cannot export during renegotiation", "failed to export keying material"},
122
      {"Client cert verify failed", ":BAD_SIGNATURE:"},
123
      {"Client certificate does not support signing", ":KEY_USAGE_BIT_INCORRECT:"},
124
      {"Client certificate verification failed", ":BAD_SIGNATURE:"},
125
      {"Client did not comply with the requested key exchange group", ":WRONG_CURVE:"},
126
      {"Client did not offer NULL compression", ":INVALID_COMPRESSION_LIST:"},
127
      {"Client did not comply with the requested key exchange group", ":WRONG_CURVE:"},
128
      {"Client Hello must either contain both key_share and supported_groups extensions or neither",
129
       ":MISSING_KEY_SHARE:"},
130
      {"Client Hello offered a PSK without a psk_key_exchange_modes extension", ":MISSING_EXTENSION:"},
131
      {"Client offered DTLS version with major version 0xFF", ":UNSUPPORTED_PROTOCOL:"},
132
      {"Client offered SSLv3 which is not supported", ":UNSUPPORTED_PROTOCOL:"},
133
      {"Client offered TLS version with major version under 3", ":UNSUPPORTED_PROTOCOL:"},
134
      {"Expected server hello of (D)TLS 1.2 or lower", ":UNSUPPORTED_PROTOCOL:"},
135
      {"Protocol version was not offered", ":UNSUPPORTED_PROTOCOL:"},
136
      {"Client policy prohibits insecure renegotiation", ":RENEGOTIATION_MISMATCH:"},
137
      {"Client policy prohibits renegotiation", ":NO_RENEGOTIATION:"},
138
      {"Client resumed extended ms session without sending extension", ":RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION:"},
139
      {"Client sent plaintext HTTP proxy CONNECT request instead of TLS handshake", ":HTTPS_PROXY_REQUEST:"},
140
      {"Client sent plaintext HTTP request instead of TLS handshake", ":HTTP_REQUEST:"},
141
      {"Client signalled fallback SCSV, possible attack", ":INAPPROPRIATE_FALLBACK:"},
142
      {"Client version TLS v1.1 is unacceptable by policy", ":UNSUPPORTED_PROTOCOL:"},
143
      {"Concatenated public values have an unexpected length", ":BAD_ECPOINT:"},
144
      {"No shared TLS version based on supported versions extension", ":UNSUPPORTED_PROTOCOL:"},
145
      {"Client: No certificates sent by server", ":DECODE_ERROR:"},
146
      {"Decoded polynomial coefficients out of range", ":BAD_ECPOINT:"},
147
      {"Non-PSK Client Hello did not contain supported_groups and signature_algorithms extensions",
148
       ":NO_SHARED_GROUP:"},
149
      {"No certificates sent by server", ":PEER_DID_NOT_RETURN_A_CERTIFICATE:"},
150
      {"Not enough data to read another KeyShareEntry", ":DECODE_ERROR:"},
151
      {"Not enough PSK binders", ":PSK_IDENTITY_BINDER_COUNT_MISMATCH:"},
152
      {"Counterparty sent inconsistent key and sig types", ":WRONG_SIGNATURE_TYPE:"},
153
      {"Downgrade attack detected", ":TLS13_DOWNGRADE:"},
154
      {"Empty ALPN protocol not allowed", ":PARSE_TLSEXT:"},
155
      {"Empty PSK binders list", ":DECODE_ERROR: "},
156
      {"Encoding error: Cannot encode PSS string, output length too small", ":NO_COMMON_SIGNATURE_ALGORITHMS:"},
157
      {"Expected TLS but got a record with DTLS version", ":WRONG_VERSION_NUMBER:"},
158
      {"Extension removed in updated Client Hello", ":INCONSISTENT_CLIENT_HELLO:"},
159
      {"Failed to agree on a signature algorithm", ":NO_COMMON_SIGNATURE_ALGORITHMS:"},
160
      {"Failed to agree on any signature algorithm", ":NO_COMMON_SIGNATURE_ALGORITHMS:"},
161
      {"Failed to deserialize elliptic curve point", ":BAD_ECPOINT:"},
162
      {"Failed to negotiate a common signature algorithm for client authentication",
163
       ":NO_COMMON_SIGNATURE_ALGORITHMS:"},
164
      {"PSK extension was not at the very end of the Client Hello", ":PRE_SHARED_KEY_MUST_BE_LAST:"},
165
      {"Finished message didn't verify", ":DIGEST_CHECK_FAILED:"},
166
      {"Have data remaining in buffer after ClientHello", ":EXCESS_HANDSHAKE_DATA:"},
167
      {"Have data remaining in buffer after Finished", ":EXCESS_HANDSHAKE_DATA:"},
168
      {"Have data remaining in buffer after ServerHelloDone", ":EXCESS_HANDSHAKE_DATA:"},
169
      {"Hello Retry Request does not request any changes to Client Hello", ":EMPTY_HELLO_RETRY_REQUEST:"},
170
      {"Unexpected additional handshake message data found in record", ":EXCESS_HANDSHAKE_DATA:"},
171
      {"Inconsistent length in certificate request", ":DECODE_ERROR:"},
172
      {"unexpected key_update parameter", ":DECODE_ERROR:"},
173
      {"Inconsistent values in fragmented DTLS handshake header", ":FRAGMENT_MISMATCH:"},
174
      {"Invalid CertificateRequest: Length field outside parameters", ":DECODE_ERROR:"},
175
      {"Invalid ServerHello: Length field outside parameters", ":DECODE_ERROR:"},
176
      {"Invalid CertificateVerify: Extra bytes at end of message", ":DECODE_ERROR:"},
177
      {"Invalid Certificate_Status: invalid length field", ":DECODE_ERROR:"},
178
      {"Invalid ChangeCipherSpec", ":BAD_CHANGE_CIPHER_SPEC:"},
179
      {"Invalid ClientHello: Length field outside parameters", ":DECODE_ERROR:"},
180
      {"Invalid ClientKeyExchange: Extra bytes at end of message", ":DECODE_ERROR:"},
181
      {"Invalid ServerKeyExchange: Extra bytes at end of message", ":DECODE_ERROR:"},
182
      {"Invalid SessionTicket: Extra bytes at end of message", ":DECODE_ERROR:"},
183
      {"Invalid authentication tag: ChaCha20Poly1305 tag check failed", ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:"},
184
      {"Invalid authentication tag: GCM tag check failed", ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:"},
185
      {"Invalid encapsulated key length", ":BAD_ECPOINT:"},
186
      {"Invalid hybrid KEM ciphertext", ":BAD_ECPOINT:"},
187
      {"Invalid size 31 for X25519 public key", ":BAD_ECPOINT:"},
188
      {"Invalid size 33 for X25519 public key", ":BAD_ECPOINT:"},
189
      {"Message authentication failure", ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:"},
190
      {"No content type found in encrypted record", ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:"},
191
      {"No shared DTLS version", ":UNSUPPORTED_PROTOCOL:"},
192
      {"No shared TLS version", ":UNSUPPORTED_PROTOCOL:"},
193
      {"OS2ECP: Unknown format type 251", ":BAD_ECPOINT:"},
194
      {"Peer sent signature algorithm that is not suitable for TLS 1.3", ":WRONG_SIGNATURE_TYPE:"},
195
      {"Policy forbids all available DTLS version", ":NO_SUPPORTED_VERSIONS_ENABLED:"},
196
      {"Policy forbids all available TLS version", ":NO_SUPPORTED_VERSIONS_ENABLED:"},
197
      {"Policy refuses to accept signing with any hash supported by peer", ":NO_COMMON_SIGNATURE_ALGORITHMS:"},
198
      {"Policy requires client send a certificate, but it did not", ":PEER_DID_NOT_RETURN_A_CERTIFICATE:"},
199
      {"PSK binder does not check out", ":DIGEST_CHECK_FAILED:"},
200
      {"PSK identity selected by server is out of bounds", ":PSK_IDENTITY_NOT_FOUND:"},
201
      {"PSK and ciphersuite selected by server are not compatible", ":OLD_SESSION_PRF_HASH_MISMATCH:"},
202
      {"Received a record that exceeds maximum size", ":ENCRYPTED_LENGTH_TOO_LONG:"},
203
      {"Received an encrypted record that exceeds maximum size", ":ENCRYPTED_LENGTH_TOO_LONG:"},
204
      {"received an illegal handshake message", ":UNEXPECTED_MESSAGE:"},
205
      {"Received a legacy Client Hello", ":UNSUPPORTED_PROTOCOL:"},
206
      {"Received an unexpected legacy Server Hello", ":UNSUPPORTED_PROTOCOL:"},
207
      {"Received application data after connection closure", ":APPLICATION_DATA_ON_SHUTDOWN:"},
208
      {"Received handshake data after connection closure", ":NO_RENEGOTIATION:"},
209
      {"Received multiple key share entries for the same group", ":DUPLICATE_KEY_SHARE:"},
210
      {"Received unexpected record version in initial record", ":WRONG_VERSION_NUMBER:"},
211
      {"Received unexpected record version", ":WRONG_VERSION_NUMBER:"},
212
      {"Rejecting ALPN request with alert", ":NO_APPLICATION_PROTOCOL:"},
213
      {"RSA signatures must use an RSASSA-PSS algorithm", ":WRONG_SIGNATURE_TYPE:"},
214
      {"Server attempting to negotiate SSLv3 which is not supported", ":UNSUPPORTED_PROTOCOL:"},
215
      {"Server certificate changed during renegotiation", ":SERVER_CERT_CHANGED:"},
216
      {"Server changed its mind about extended master secret", ":RENEGOTIATION_EMS_MISMATCH:"},
217
      {"Server changed its mind about secure renegotiation", ":RENEGOTIATION_MISMATCH:"},
218
      {"Server changed version after renegotiation", ":WRONG_SSL_VERSION:"},
219
      {"Server policy prohibits renegotiation", ":NO_RENEGOTIATION:"},
220
      {"Server replied using a ciphersuite not allowed in version it offered", ":WRONG_CIPHER_RETURNED:"},
221
      {"Server replied with an invalid version", ":UNSUPPORTED_PROTOCOL:"},
222
      {"server changed its chosen ciphersuite", ":WRONG_CIPHER_RETURNED:"},
223
      {"Server replied with DTLS-SRTP alg we did not send", ":BAD_SRTP_PROTECTION_PROFILE_LIST:"},
224
      {"Server replied with ciphersuite we didn't send", ":WRONG_CIPHER_RETURNED:"},
225
      {"Server replied with an invalid version", ":UNSUPPORTED_PROTOCOL:"},  // bogus version from "ServerBogusVersion"
226
      {"Server version SSL v3 is unacceptable by policy", ":UNSUPPORTED_PROTOCOL:"},  // "NoSSL3-Client-Unsolicited"
227
      {"legacy_version 'TLS v1.4' is not allowed", ":DECODE_ERROR:"},
228
      {"legacy_version 'Unknown 18.52' is not allowed", ":UNSUPPORTED_PROTOCOL:"},
229
      {"Server replied with non-null compression method", ":UNSUPPORTED_COMPRESSION_ALGORITHM:"},
230
      {"Server replied with some unknown ciphersuite", ":UNKNOWN_CIPHER_RETURNED:"},
231
      {"Server replied with unsupported extensions: 0", ":UNEXPECTED_EXTENSION:"},
232
      {"Server replied with unsupported extensions: 1234", ":UNEXPECTED_EXTENSION:"},
233
      {"Server replied with unsupported extensions: 16", ":UNEXPECTED_EXTENSION:"},
234
      {"Server replied with unsupported extensions: 43", ":UNEXPECTED_EXTENSION:"},
235
      {"Server replied with unsupported extensions: 5", ":UNEXPECTED_EXTENSION:"},
236
      {"Server resumed session and removed extended master secret", ":RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION:"},
237
      {"Server resumed session but added extended master secret", ":RESUMED_NON_EMS_SESSION_WITH_EMS_EXTENSION:"},
238
      {"Server resumed session but with wrong version", ":OLD_SESSION_VERSION_NOT_RETURNED:"},
239
      {"Server selected a group that is not compatible with the negotiated ciphersuite", ":WRONG_CURVE:"},
240
      {"Server sent ECC curve prohibited by policy", ":WRONG_CURVE:"},
241
      {"group was not advertised as supported", ":WRONG_CURVE:"},
242
      {"group was already offered", ":WRONG_CURVE:"},
243
      {"Server selected a key exchange group we didn't offer.", ":WRONG_CURVE:"},
244
      {"TLS 1.3 Server Hello selected a different version", ":SECOND_SERVERHELLO_VERSION_MISMATCH:"},
245
      {"Version downgrade received after Hello Retry", ":SECOND_SERVERHELLO_VERSION_MISMATCH:"},
246
      {"protected change cipher spec received", ":UNEXPECTED_RECORD:"},
247
      {"Server sent an unsupported extension", ":UNEXPECTED_EXTENSION:"},
248
      {"Unsupported extension found in Server Hello", ":UNEXPECTED_EXTENSION:"},
249
      {"Unexpected extension received", ":UNEXPECTED_EXTENSION:"},
250
      {"server hello must contain key exchange information", ":MISSING_KEY_SHARE:"},
251
      {"Peer sent duplicated extensions", ":DUPLICATE_EXTENSION:"},
252
      {"Policy does not accept any hash function supported by client", ":NO_SHARED_CIPHER:"},
253
      {"Server sent bad values for secure renegotiation", ":RENEGOTIATION_MISMATCH:"},
254
      {"Server version DTLS v1.0 is unacceptable by policy", ":UNSUPPORTED_PROTOCOL:"},
255
      {"Server version TLS v1.0 is unacceptable by policy", ":UNSUPPORTED_PROTOCOL:"},
256
      {"Server version TLS v1.1 is unacceptable by policy", ":UNSUPPORTED_PROTOCOL:"},
257
      {"Server_Hello_Done: Must be empty, and is not", ":DECODE_ERROR:"},
258
      {"Simulated OCSP callback failure", ":OCSP_CB_ERROR:"},
259
      {"Simulating cert verify callback failure", ":CERT_CB_ERROR:"},
260
      {"Simulating failure from OCSP response callback", ":OCSP_CB_ERROR:"},
261
      {"TLS plaintext record is larger than allowed maximum", ":DATA_LENGTH_TOO_LONG:"},
262
      {"Received an encrypted record that exceeds maximum plaintext size", ":DATA_LENGTH_TOO_LONG:"},
263
      {"TLS record type had unexpected value", ":UNEXPECTED_RECORD:"},
264
      {"TLS record version had unexpected value", ":WRONG_VERSION_NUMBER:"},
265
      {"Test requires rejecting cert", ":CERTIFICATE_VERIFY_FAILED:"},
266
      {"Too many PSK binders", ":PSK_IDENTITY_BINDER_COUNT_MISMATCH:"},
267
      {"Unexpected ALPN protocol", ":INVALID_ALPN_PROTOCOL:"},
268
      {"Unexpected record type 42 from counterparty", ":UNEXPECTED_RECORD:"},
269
      {"Unexpected state transition in handshake got a certificate_request expected server_hello_done seen server_hello+server_key_exchange",
270
       ":UNEXPECTED_MESSAGE:"},
271
      {"Unexpected state transition in handshake got a certificate_request expected server_key_exchange|server_hello_done seen server_hello",
272
       ":UNEXPECTED_MESSAGE:"},
273
      {"Unexpected state transition in handshake got a certificate_status expected certificate seen server_hello",
274
       ":UNEXPECTED_MESSAGE:"},
275
      {"Unexpected state transition in handshake got a change_cipher_spec expected certificate_verify seen client_hello+certificate+client_key_exchange",
276
       ":UNEXPECTED_RECORD:"},
277
      {"Unexpected state transition in handshake got a change_cipher_spec expected client_key_exchange seen client_hello",
278
       ":UNEXPECTED_RECORD:"},
279
      {"Unexpected state transition in handshake got a change_cipher_spec expected new_session_ticket seen server_hello+certificate+server_key_exchange+server_hello_done",
280
       ":UNEXPECTED_RECORD:"},
281
      {"Unexpected state transition in handshake got a client_key_exchange expected certificate seen client_hello",
282
       ":UNEXPECTED_MESSAGE:"},
283
      {"Unexpected state transition in handshake got a finished expected certificate_verify seen client_hello+certificate",
284
       ":UNEXPECTED_MESSAGE:"},
285
      {"Unexpected state transition in handshake got a finished expected certificate seen client_hello",
286
       ":UNEXPECTED_MESSAGE:"},
287
      {"Unexpected state transition in handshake got a finished expected change_cipher_spec seen client_hello",
288
       ":UNEXPECTED_RECORD:"},
289
      {"Unexpected state transition in handshake got a finished expected change_cipher_spec seen client_hello+client_key_exchange",
290
       ":UNEXPECTED_RECORD:"},
291
      {"Unexpected state transition in handshake got a finished expected change_cipher_spec seen server_hello",
292
       ":UNEXPECTED_RECORD:"},
293
      {"Unexpected state transition in handshake got a finished expected change_cipher_spec seen server_hello+certificate+server_key_exchange+server_hello_done+new_session_ticket",
294
       ":UNEXPECTED_RECORD:"},
295
      {"Unexpected state transition in handshake got a hello_request expected server_hello", ":UNEXPECTED_MESSAGE:"},
296
      {"Unexpected state transition in handshake got a server_hello_done expected server_key_exchange seen server_hello+certificate+certificate_status",
297
       ":UNEXPECTED_MESSAGE:"},
298
      {"Unexpected state transition in handshake got a server_key_exchange expected certificate_request|server_hello_done seen server_hello+certificate+certificate_status",
299
       ":UNEXPECTED_MESSAGE:"},
300
      {"Unexpected state transition in handshake got a server_hello_done expected server_key_exchange seen server_hello+certificate",
301
       ":UNEXPECTED_MESSAGE:"},
302
      {"Unexpected state transition in handshake got a server_key_exchange expected certificate seen server_hello",
303
       ":UNEXPECTED_MESSAGE:"},
304
      {"Unexpected state transition in handshake got a server_key_exchange expected certificate_request|server_hello_done seen server_hello+certificate",
305
       ":UNEXPECTED_MESSAGE:"},
306
      {"Unexpected state transition in handshake got a hello_retry_request expected server_hello",
307
       ":UNEXPECTED_MESSAGE:"},
308
      {"Unexpected state transition in handshake got a server_key_exchange not expecting messages",
309
       ":BAD_HELLO_REQUEST:"},
310
      {"Unexpected state transition in handshake got a finished expected certificate_verify seen server_hello+certificate+encrypted_extensions",
311
       ":BAD_HELLO_REQUEST:"},
312
      {"Unknown TLS handshake message type 43", ":UNEXPECTED_MESSAGE:"},
313
      {"Unknown TLS handshake message type 44", ":UNEXPECTED_MESSAGE:"},
314
      {"Unknown TLS handshake message type 45", ":UNEXPECTED_MESSAGE:"},
315
      {"Unknown TLS handshake message type 46", ":UNEXPECTED_MESSAGE:"},
316
      {"Unknown TLS handshake message type 53", ":UNEXPECTED_MESSAGE:"},
317
      {"Unknown TLS handshake message type 54", ":UNEXPECTED_MESSAGE:"},
318
      {"Unknown TLS handshake message type 55", ":UNEXPECTED_MESSAGE:"},
319
      {"Unknown TLS handshake message type 56", ":UNEXPECTED_MESSAGE:"},
320
      {"Unknown TLS handshake message type 57", ":UNEXPECTED_MESSAGE:"},
321
      {"Unknown TLS handshake message type 58", ":UNEXPECTED_MESSAGE:"},
322
      {"Unknown TLS handshake message type 6", ":UNEXPECTED_MESSAGE:"},
323
      {"Unknown TLS handshake message type 62", ":UNEXPECTED_MESSAGE:"},
324
      {"Unknown TLS handshake message type 64", ":UNEXPECTED_MESSAGE:"},
325
      {"Unknown handshake message received", ":UNEXPECTED_MESSAGE:"},
326
      {"Unknown post-handshake message received", ":UNEXPECTED_MESSAGE:"},
327
      {"signature_algorithm_of_scheme: Unknown signature algorithm enum", ":WRONG_SIGNATURE_TYPE:"},
328
      {"Unexpected session ID during downgrade", ":SERVER_ECHOED_INVALID_SESSION_ID:"},
329
      {"Encrypted Extensions contained an extension that is not allowed", ":ERROR_PARSING_EXTENSION:"},
330
      {"Encrypted Extensions contained an extension that was not offered", ":UNEXPECTED_EXTENSION:"},
331
      {"Certificate Entry contained an extension that is not allowed", ":UNEXPECTED_EXTENSION:"},
332
      {"Certificate Entry contained an extension that was not offered", ":UNEXPECTED_EXTENSION:"},
333
      {"Server Hello contained an extension that is not allowed", ":UNEXPECTED_EXTENSION:"},
334
      {"Hello Retry Request contained an extension that is not allowed", ":UNEXPECTED_EXTENSION:"},
335
      {"Signature algorithm does not match certificate's public key", ":WRONG_SIGNATURE_TYPE:"},
336
      {"unprotected record received where protected traffic was expected", ":INVALID_OUTER_RECORD_TYPE:"},
337
      {"Error alert not marked fatal", ":BAD_ALERT:"},
338
      {"Peer sent unknown signature scheme", ":WRONG_SIGNATURE_TYPE:"},
339
      {"We did not offer the usage of RSA_PSS_SHA256 as a signature scheme", ":WRONG_SIGNATURE_TYPE:"},
340
      {"X25519 public point appears to be of low order", ":BAD_ECPOINT:"},
341
   };
177,684✔
342

343
   auto err_map_i = err_map.find(e);
804✔
344
   if(err_map_i != err_map.end()) {
804✔
345
      return err_map_i->second;
800✔
346
   }
347

348
   return "Unmapped error: '" + e + "'";
8✔
349
}
804✔
350

351
class Shim_Exception final : public std::exception {
352
   public:
353
      explicit Shim_Exception(std::string_view msg, int rc = 1) : m_msg(msg), m_rc(rc) {}
2✔
354

355
      const char* what() const noexcept override { return m_msg.c_str(); }
2✔
356

357
      int rc() const { return m_rc; }
1✔
358

359
   private:
360
      const std::string m_msg;
361
      int m_rc;
362
};
363

364
#if defined(BOTAN_TARGET_OS_HAS_SOCKETS)
365

366
class Shim_Socket final {
367
   private:
368
      typedef int socket_type;
369
      typedef ssize_t socket_op_ret_type;
370

371
      static void close_socket(socket_type s) { ::close(s); }
372

373
      static std::string get_last_socket_error() { return ::strerror(errno); }
374

375
      using unique_addrinfo_t = std::unique_ptr<addrinfo, decltype(&::freeaddrinfo)>;
376

377
   public:
378
      Shim_Socket(const std::string& hostname, int port, const bool ipv6) : m_socket(-1) {
2,715✔
379
         addrinfo hints{};
2,715✔
380
         std::memset(&hints, 0, sizeof(hints));
2,715✔
381
         hints.ai_family = AF_UNSPEC;
2,715✔
382
         hints.ai_socktype = SOCK_STREAM;
2,715✔
383
         hints.ai_flags = AI_NUMERICSERV;
2,715✔
384

385
         const std::string service = std::to_string(port);
2,715✔
386

387
         // TODO: C++23 will introduce std::out_ptr() that should replace the
388
         //       temporary variable for the call to ::getaddrinfo() and
389
         //       std::unique_ptr<>::reset().
390
         unique_addrinfo_t::pointer res_tmp = nullptr;
2,715✔
391
         int rc = ::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res_tmp);
2,715✔
392
         unique_addrinfo_t res(res_tmp, &::freeaddrinfo);
2,715✔
393

394
         shim_log("Connecting " + hostname + ":" + service);
10,860✔
395

396
         if(rc != 0) {
2,715✔
397
            throw Shim_Exception("Name resolution failed for " + hostname);
×
398
         }
399

400
         for(addrinfo* rp = res.get(); (m_socket == -1) && (rp != nullptr); rp = rp->ai_next) {
5,430✔
401
            if((!ipv6 && rp->ai_family != AF_INET) || (ipv6 && rp->ai_family != AF_INET6)) {
2,715✔
402
               continue;
×
403
            }
404

405
            m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
2,715✔
406

407
            if(m_socket == -1) {
2,715✔
408
               // unsupported socket type?
409
               continue;
×
410
            }
411

412
            int err = ::connect(m_socket, rp->ai_addr, rp->ai_addrlen);
2,715✔
413

414
            if(err != 0) {
2,715✔
415
               ::close(m_socket);
×
416
               m_socket = -1;
×
417
            }
418
         }
419

420
         if(m_socket < 0) {
2,715✔
421
            throw Shim_Exception("Failed to connect to host");
×
422
         }
423
      }
2,715✔
424

425
      Shim_Socket(const Shim_Socket&) = delete;
426
      Shim_Socket& operator=(const Shim_Socket&) = delete;
427

428
      Shim_Socket(Shim_Socket&&) = delete;
429
      Shim_Socket& operator=(Shim_Socket&&) = delete;
430

431
      ~Shim_Socket() {
2,697✔
432
         ::close(m_socket);
2,697✔
433
         m_socket = -1;
2,697✔
434
      }
2,697✔
435

436
      void write(const uint8_t buf[], size_t len) const {
19,056✔
437
         if(m_socket < 0) {
19,056✔
438
            throw Shim_Exception("Socket was bad on write");
×
439
         }
440
         size_t sent_so_far = 0;
441
         while(sent_so_far != len) {
38,106✔
442
            const size_t left = len - sent_so_far;
19,056✔
443
            socket_op_ret_type sent =
19,056✔
444
               ::send(m_socket, Botan::cast_uint8_ptr_to_char(&buf[sent_so_far]), left, MSG_NOSIGNAL);
19,056✔
445
            if(sent < 0) {
19,056✔
446
               if(errno == EPIPE) {
6✔
447
                  return;
448
               } else {
449
                  throw Shim_Exception("Socket write failed", errno);
×
450
               }
451
            } else {
452
               sent_so_far += static_cast<size_t>(sent);
19,050✔
453
            }
454
         }
455
      }
456

457
      size_t read(uint8_t buf[], size_t len) const {
203,970✔
458
         if(m_socket < 0) {
203,970✔
459
            throw Shim_Exception("Socket was bad on read");
×
460
         }
461
         socket_op_ret_type got = ::read(m_socket, Botan::cast_uint8_ptr_to_char(buf), len);
203,970✔
462

463
         if(got < 0) {
203,970✔
464
            if(errno == ECONNRESET) {
337✔
465
               return 0;
466
            }
467
            throw Shim_Exception("Socket read failed: " + std::string(strerror(errno)));
×
468
         }
469

470
         return static_cast<size_t>(got);
203,633✔
471
      }
472

473
      void read_exactly(uint8_t buf[], size_t len) const {
367,892✔
474
         if(m_socket < 0) {
367,892✔
475
            throw Shim_Exception("Socket was bad on read");
×
476
         }
477

478
         while(len > 0) {
735,784✔
479
            socket_op_ret_type got = ::read(m_socket, Botan::cast_uint8_ptr_to_char(buf), len);
367,892✔
480

481
            if(got == 0) {
367,892✔
482
               throw Shim_Exception("Socket read EOF");
×
483
            } else if(got < 0) {
367,892✔
484
               throw Shim_Exception("Socket read failed: " + std::string(strerror(errno)));
×
485
            }
486

487
            buf += static_cast<size_t>(got);
367,892✔
488
            len -= static_cast<size_t>(got);
367,892✔
489
         }
490
      }
367,892✔
491

492
   private:
493
      socket_type m_socket;
494
};
495

496
#endif
497

498
std::set<std::string> combine_options(const std::set<std::string>& a,
2,107✔
499
                                      const std::set<std::string>& b,
500
                                      const std::set<std::string>& c,
501
                                      const std::set<std::string>& d) {
502
   std::set<std::string> combined;
2,107✔
503

504
   for(const auto& i : a) {
54,782✔
505
      combined.insert(i);
52,675✔
506
   }
507
   for(const auto& i : b) {
8,428✔
508
      combined.insert(i);
6,321✔
509
   }
510
   for(const auto& i : c) {
46,354✔
511
      combined.insert(i);
44,247✔
512
   }
513
   for(const auto& i : d) {
10,535✔
514
      combined.insert(i);
8,428✔
515
   }
516

517
   return combined;
2,107✔
518
}
×
519

520
class Shim_Arguments final {
521
   public:
522
      Shim_Arguments(const std::set<std::string>& flags,
2,107✔
523
                     const std::set<std::string>& string_opts,
524
                     const std::set<std::string>& base64_opts,
525
                     const std::set<std::string>& int_opts,
526
                     const std::set<std::string>& int_vec_opts) :
2,107✔
527
            m_flags(flags),
2,107✔
528
            m_string_opts(string_opts),
2,107✔
529
            m_base64_opts(base64_opts),
2,107✔
530
            m_int_opts(int_opts),
2,107✔
531
            m_int_vec_opts(int_vec_opts),
2,107✔
532
            m_all_options(combine_options(string_opts, base64_opts, int_opts, int_vec_opts)) {}
2,107✔
533

534
      void parse_args(char* argv[]);
535

536
      bool flag_set(const std::string& flag) const {
118,307✔
537
         if(!m_flags.contains(flag)) {
118,307✔
538
            throw Shim_Exception("Unknown bool flag " + flag);
×
539
         }
540

541
         return m_parsed_flags.contains(flag);
118,307✔
542
      }
543

544
      std::string test_name() const { return get_string_opt("test-name"); }
8,438✔
545

546
      std::string get_string_opt(const std::string& key) const {
9,631✔
547
         if(!m_string_opts.contains(key)) {
9,631✔
548
            throw Shim_Exception("Unknown string key " + key);
×
549
         }
550
         return get_opt(key);
9,631✔
551
      }
552

553
      std::string get_string_opt_or_else(const std::string& key, const std::string& def) const {
222,724✔
554
         if(!m_string_opts.contains(key)) {
222,724✔
555
            throw Shim_Exception("Unknown string key " + key);
×
556
         }
557
         if(!option_used(key)) {
222,724✔
558
            return def;
221,479✔
559
         }
560
         return get_opt(key);
1,245✔
561
      }
562

563
      std::vector<uint8_t> get_b64_opt(const std::string& key) const {
73✔
564
         if(!m_base64_opts.contains(key)) {
73✔
565
            throw Shim_Exception("Unknown base64 key " + key);
×
566
         }
567
         return Botan::unlock(Botan::base64_decode(get_opt(key)));
219✔
568
      }
569

570
      size_t get_int_opt(const std::string& key) const {
7,769✔
571
         if(!m_int_opts.contains(key)) {
7,769✔
572
            throw Shim_Exception("Unknown int key " + key);
×
573
         }
574
         return Botan::to_u32bit(get_opt(key));
7,769✔
575
      }
576

577
      size_t get_int_opt_or_else(const std::string& key, size_t def) const {
8,315✔
578
         if(!m_int_opts.contains(key)) {
8,315✔
579
            throw Shim_Exception("Unknown int key " + key);
×
580
         }
581
         if(!option_used(key)) {
8,315✔
582
            return def;
583
         }
584

585
         return Botan::to_u32bit(get_opt(key));
894✔
586
      }
587

588
      std::vector<size_t> get_int_vec_opt(const std::string& key) const {
826✔
589
         if(!m_int_vec_opts.contains(key)) {
826✔
590
            throw Shim_Exception("Unknown int vec key " + key);
×
591
         }
592

593
         auto i = m_parsed_int_vec_opts.find(key);
826✔
594
         if(i == m_parsed_int_vec_opts.end()) {
826✔
595
            return std::vector<size_t>();
×
596
         } else {
597
            return i->second;
826✔
598
         }
599
      }
600

601
      std::vector<std::string> get_alpn_string_vec_opt(const std::string& option) const {
1,503✔
602
         // hack used for alpn list (relies on all ALPNs being 3 chars long...)
603
         char delim = 0x03;
1,503✔
604

605
         if(option_used(option)) {
1,503✔
606
            return Botan::split_on(get_string_opt(option), delim);
58✔
607
         } else {
608
            return std::vector<std::string>();
1,474✔
609
         }
610
      }
611

612
      bool option_used(const std::string& key) const {
362,976✔
613
         if(!m_all_options.contains(key)) {
362,976✔
614
            throw Shim_Exception("Invalid option " + key);
×
615
         }
616
         if(m_parsed_opts.contains(key)) {
362,976✔
617
            return true;
618
         }
619
         if(m_parsed_int_vec_opts.contains(key)) {
356,875✔
620
            return true;
621
         }
622
         return false;
623
      }
624

625
   private:
626
      std::string get_opt(const std::string& key) const {
19,612✔
627
         auto i = m_parsed_opts.find(key);
19,612✔
628
         if(i == m_parsed_opts.end()) {
19,612✔
629
            throw Shim_Exception("Option " + key + " was not provided");
×
630
         }
631
         return i->second;
19,612✔
632
      }
633

634
      const std::set<std::string> m_flags;
635
      const std::set<std::string> m_string_opts;
636
      const std::set<std::string> m_base64_opts;
637
      const std::set<std::string> m_int_opts;
638
      const std::set<std::string> m_int_vec_opts;
639
      const std::set<std::string> m_all_options;
640

641
      std::set<std::string> m_parsed_flags;
642
      std::map<std::string, std::string> m_parsed_opts;
643
      std::map<std::string, std::vector<size_t>> m_parsed_int_vec_opts;
644
};
645

646
void Shim_Arguments::parse_args(char* argv[]) {
2,107✔
647
   int i = 1;  // skip argv[0]
2,107✔
648

649
   while(argv[i] != nullptr) {
20,246✔
650
      const std::string param(argv[i]);
18,139✔
651

652
      if(param.starts_with("-")) {
18,139✔
653
         const std::string flag_name = param.substr(1, std::string::npos);
18,139✔
654

655
         if(m_flags.contains(flag_name)) {
18,139✔
656
            shim_log("flag " + flag_name);
5,963✔
657
            m_parsed_flags.insert(flag_name);
5,963✔
658
            i += 1;
5,963✔
659
         } else if(m_all_options.contains(flag_name)) {
12,176✔
660
            if(argv[i + 1] == nullptr) {
12,176✔
661
               throw Shim_Exception("Expected argument following " + param);
×
662
            }
663
            std::string val(argv[i + 1]);
12,176✔
664
            shim_log(Botan::fmt("param {}={}", flag_name, val));
12,176✔
665

666
            if(m_int_vec_opts.contains(flag_name)) {
12,176✔
667
               const size_t v = Botan::to_u32bit(val);
837✔
668
               m_parsed_int_vec_opts[flag_name].push_back(v);
837✔
669
            } else {
670
               m_parsed_opts[flag_name] = val;
11,339✔
671
            }
672
            i += 2;
12,176✔
673
         } else {
12,176✔
674
            shim_log("Unknown option " + param);
×
675
            throw Shim_Exception("Unknown option " + param, 89);
×
676
         }
677
      } else {
18,139✔
678
         shim_log("Unknown option " + param);
×
679
         throw Shim_Exception("Unknown option " + param, 89);
×
680
      }
681
   }
18,139✔
682
}
8,070✔
683

684
std::unique_ptr<Shim_Arguments> parse_options(char* argv[]) {
2,107✔
685
   const std::set<std::string> bogo_shim_flags = {
2,107✔
686
      "allow-false-start-without-alpn",
687
      "allow-unknown-alpn-protos",
688
      "async",
689
      "cbc-record-splitting",
690
      "check-close-notify",
691
      "decline-alpn",
692
      "decline-ocsp-callback",
693
      "dtls",
694
      "enable-all-curves",
695
      "enable-channel-id",
696
      "enable-early-data",
697
      "enable-ed25519",
698
      "enable-grease",
699
      "enable-ocsp-stapling",
700
      "enable-signed-cert-timestamps",
701
      "enforce-rsa-key-usage",
702
      //"expect-accept-early-data",
703
      "expect-extended-master-secret",
704
      "expect-no-offer-early-data",
705
      "expect-no-secure-renegotiation",
706
      "expect-no-session",
707
      "expect-no-session-id",
708
      //"expect-reject-early-data",
709
      "expect-secure-renegotiation",
710
      "expect-session-id",
711
      "expect-session-miss",
712
      "expect-sha256-client-cert",
713
      "expect-ticket-renewal",
714
      "expect-ticket-supports-early-data",
715
      //"expect-tls13-downgrade",
716
      "expect-verify-result",
717
      "expect-no-hrr",
718
      "expect-hrr",
719
      //"export-traffic-secrets",
720
      "fail-cert-callback",
721
      //"fail-ddos-callback",
722
      //"fail-early-callback",
723
      "fail-ocsp-callback",
724
      "fallback-scsv",
725
      //"false-start",
726
      "forbid-renegotiation-after-handshake",
727
      "handoff",
728
      "handshake-never-done",
729
      "handshake-twice",
730
      "handshaker-resume",
731
      //"ignore-tls13-downgrade",
732
      "implicit-handshake",
733
      "install-cert-compression-algs",
734
      "install-ddos-callback",
735
      "ipv6",
736
      "is-handshaker-supported",
737
      //"jdk11-workaround",
738
      "key-update",
739
      "no-check-client-certificate-type",
740
      "no-check-ecdsa-curve",
741
      "no-op-extra-handshake",
742
      "no-rsa-pss-rsae-certs",
743
      "no-ticket",
744
      "no-tls1",
745
      "no-tls11",
746
      "no-tls12",
747
      "no-tls13",
748
      "on-resume-no-ticket",
749
      //"on-resume-verify-fail",
750
      //"partial-write",
751
      //"peek-then-read",
752
      //"read-with-unfinished-write",
753
      "reject-alpn",
754
      "renegotiate-freely",
755
      "renegotiate-ignore",
756
      "renegotiate-once",
757
      //"renew-ticket",
758
      "require-any-client-certificate",
759
      "retain-only-sha256-client-cert",
760
      //"reverify-on-resume",
761
      "select-empty-alpn",
762
      "send-alert",
763
      "server",
764
      "server-preference",
765
      "set-ocsp-in-callback",
766
      "shim-shuts-down",
767
      "shim-writes-first",
768
      //"tls-unique",
769
      "use-custom-verify-callback",
770
      "use-early-callback",
771
      "use-export-context",
772
      "use-exporter-between-reads",
773
      "use-ocsp-callback",
774
      //"use-old-client-cert-callback",
775
      //"use-ticket-callback",
776
      "verify-fail",
777
      "verify-peer",
778
      //"verify-peer-if-no-obc",
779
      "wait-for-debugger",
780
      "write-different-record-sizes",
781
   };
2,107✔
782

783
   const std::set<std::string> bogo_shim_string_opts = {
2,107✔
784
      "advertise-alpn",
785
      //"advertise-npn",
786
      "cert-file",
787
      "cipher",
788
      //"delegated-credential",
789
      "expect-advertised-alpn",
790
      "expect-alpn",
791
      "expect-client-ca-list",
792
      "expect-early-data-reason",
793
      "expect-late-alpn",
794
      "expect-msg-callback",
795
      //"expect-next-proto",
796
      "expect-peer-cert-file",
797
      "expect-server-name",
798
      "export-context",
799
      "export-label",
800
      "handshaker-path",
801
      "host-name",
802
      "key-file",
803
      "psk",
804
      "psk-identity",
805
      "select-alpn",
806
      "select-next-proto",
807
      "srtp-profiles",
808
      "test-name",
809
      "trust-cert",
810
      "use-client-ca-list",
811
      //"send-channel-id",
812
      "write-settings",
813
   };
2,107✔
814

815
   const std::set<std::string> bogo_shim_base64_opts = {
2,107✔
816
      "expect-certificate-types",
817
      //"expect-channel-id",
818
      "expect-ocsp-response",
819
      //"expect-quic-transport-params",
820
      //"expect-signed-cert-timestamps",
821
      "ocsp-response",
822
      //"quic-transport-params",
823
      //"signed-cert-timestamps",
824
      //"ticket-key", /* we use a different ticket format from Boring */
825
      //"token-binding-params",
826
   };
2,107✔
827

828
   const std::set<std::string> bogo_shim_int_opts{
2,107✔
829
      "expect-cipher-aes",
830
      "expect-cipher-no-aes",
831
      "expect-curve-id",
832
      "expect-peer-signature-algorithm",
833
      "expect-ticket-age-skew",
834
      "expect-token-binding-param",
835
      "expect-total-renegotiations",
836
      "expect-version",
837
      //"export-early-keying-material",
838
      "export-keying-material",
839
      "initial-timeout-duration-ms",
840
      "max-cert-list",
841
      //"max-send-fragment",
842
      "max-version",
843
      "min-version",
844
      "mtu",
845
      "on-initial-expect-curve-id",
846
      "on-resume-expect-curve-id",
847
      "port",
848
      "read-size",
849
      "resume-count",
850
      "resumption-delay",
851
      "shim-id",
852
   };
48,461✔
853

854
   const std::set<std::string> bogo_shim_int_vec_opts{
2,107✔
855
      "curves",
856
      "expect-peer-verify-pref",
857
      "signing-prefs",
858
      "verify-prefs",
859
   };
12,642✔
860

861
   std::unique_ptr<Shim_Arguments> args(new Shim_Arguments(
2,107✔
862
      bogo_shim_flags, bogo_shim_string_opts, bogo_shim_base64_opts, bogo_shim_int_opts, bogo_shim_int_vec_opts));
2,107✔
863

864
   // may throw:
865
   args->parse_args(argv);
2,107✔
866

867
   return args;
2,107✔
868
}
8,428✔
869

870
class Shim_Policy final : public Botan::TLS::Policy {
2,697✔
871
   public:
872
      explicit Shim_Policy(const Shim_Arguments& args) : m_args(args), m_sessions(0) {}
2,715✔
873

874
      void incr_session_established() { m_sessions += 1; }
2,025✔
875

876
      std::vector<std::string> allowed_ciphers() const override {
211,481✔
877
         std::vector<std::string> allowed_without_aes = {
211,481✔
878
            "ChaCha20Poly1305",
879
            "Camellia-256/GCM",
880
            "Camellia-128/GCM",
881
            "ARIA-256/GCM",
882
            "ARIA-128/GCM",
883
            "Camellia-256",
884
            "Camellia-128",
885
            "SEED",
886
         };
211,481✔
887

888
         std::vector<std::string> allowed_just_aes = {
211,481✔
889
            "AES-256/OCB(12)",
890
            "AES-128/OCB(12)",
891
            "AES-256/GCM",
892
            "AES-128/GCM",
893
            "AES-256/CCM",
894
            "AES-128/CCM",
895
            "AES-256/CCM(8)",
896
            "AES-128/CCM(8)",
897
            "AES-256",
898
            "AES-128",
899
         };
211,481✔
900

901
         // 3DES is not supported by default anymore, only if the test runner
902
         // explicitly enables it via -cipher=
903
         const std::string cipher_limit = m_args.get_string_opt_or_else("cipher", "");
422,962✔
904
         if(cipher_limit == "3DES") {
211,481✔
905
            return {"3DES"};
987✔
906
         } else if(cipher_limit == "DEFAULT:!AES") {
210,494✔
907
            return allowed_without_aes;
102✔
908
         } else {
909
            // ignore this very specific config (handled in the overload of ciphersuite_list)
910
            if(!cipher_limit.empty() &&
210,392✔
911
               cipher_limit !=
912
                  "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:[TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384|TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256|TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA]:TLS_RSA_WITH_AES_128_GCM_SHA256:TLS_RSA_WITH_AES_128_CBC_SHA:[TLS_RSA_WITH_AES_256_GCM_SHA384|TLS_RSA_WITH_AES_256_CBC_SHA]") {
×
913
               shim_exit_with_error("Unknown cipher limit " + cipher_limit);
×
914
            }
915
         }
916

917
         return Botan::concat(allowed_without_aes, allowed_just_aes);
211,481✔
918
      }
211,481✔
919

920
      std::vector<std::string> allowed_signature_hashes() const override {
29,677✔
921
         if(m_args.option_used("signing-prefs")) {
29,677✔
922
            std::vector<std::string> pref_hash;
107✔
923
            for(size_t pref : m_args.get_int_vec_opt("signing-prefs")) {
217✔
924
               const Botan::TLS::Signature_Scheme scheme(pref);
110✔
925
               if(!scheme.is_available()) {
110✔
926
                  shim_log("skipping inavailable but preferred signature scheme: " + std::to_string(pref));
6✔
927
                  continue;
2✔
928
               }
929
               pref_hash.push_back(scheme.hash_function_name());
108✔
930
            }
107✔
931

932
            if(m_args.flag_set("server")) {
107✔
933
               pref_hash.push_back("SHA-256");
168✔
934
            }
935
            return pref_hash;
107✔
936
         } else {
107✔
937
            return {"SHA-512", "SHA-384", "SHA-256", "SHA-1"};
29,570✔
938
         }
939
      }
940

941
      //std::vector<std::string> allowed_macs() const override;
942

943
      std::vector<std::string> allowed_signature_methods() const override {
27,871✔
944
         return {
27,871✔
945
            "ECDSA",
946
            "RSA",
947
            "IMPLICIT",
948
         };
27,871✔
949
      }
950

951
      std::vector<Botan::TLS::Signature_Scheme> acceptable_signature_schemes() const override {
1,814✔
952
         if(m_args.option_used("verify-prefs")) {
1,814✔
953
            std::vector<Botan::TLS::Signature_Scheme> schemes;
93✔
954
            for(size_t pref : m_args.get_int_vec_opt("verify-prefs")) {
186✔
955
               schemes.emplace_back(static_cast<uint16_t>(pref));
93✔
956
            }
93✔
957

958
            return schemes;
93✔
959
         }
93✔
960

961
         return Botan::TLS::Policy::acceptable_signature_schemes();
1,721✔
962
      }
963

964
      std::vector<Botan::TLS::Signature_Scheme> allowed_signature_schemes() const override {
3,098✔
965
         if(m_args.option_used("signing-prefs")) {
3,098✔
966
            std::vector<Botan::TLS::Signature_Scheme> schemes;
133✔
967
            for(size_t pref : m_args.get_int_vec_opt("signing-prefs")) {
270✔
968
               schemes.emplace_back(static_cast<uint16_t>(pref));
137✔
969
            }
133✔
970

971
            // The relevant tests (*-Sign-Negotiate-*) want to configure a preference
972
            // for the scheme of our signing operation (-signing-prefs). However, this
973
            // policy method (`allowed_signature_schemes`) also restricts the peer's
974
            // signing operation. If we weren't to add a few 'common' algorithms, initial
975
            // security parameter negotiation would fail.
976
            // By placing the BoGo-configured scheme first we make sure our implementation
977
            // meets BoGo's expectation when it is our turn to sign.
978
            if(!m_args.flag_set("server")) {
133✔
979
               schemes.emplace_back(Botan::TLS::Signature_Scheme::RSA_PKCS1_SHA256);
77✔
980
               schemes.emplace_back(Botan::TLS::Signature_Scheme::RSA_PSS_SHA256);
77✔
981
               schemes.emplace_back(Botan::TLS::Signature_Scheme::ECDSA_SHA256);
77✔
982
            }
983

984
            return schemes;
133✔
985
         }
133✔
986

987
         return Botan::TLS::Policy::allowed_signature_schemes();
2,965✔
988
      }
989

990
      //size_t minimum_signature_strength() const override;
991

992
      bool require_cert_revocation_info() const override { return false; }
6✔
993

994
      std::vector<Botan::TLS::Group_Params> key_exchange_groups() const override {
7,377✔
995
         if(m_args.option_used("curves")) {
7,377✔
996
            std::vector<Botan::TLS::Group_Params> groups;
493✔
997

998
            // upcall to base class to find the groups actually supported by
999
            // this Botan build
1000
            const auto supported_groups = Botan::TLS::Policy::key_exchange_groups();
493✔
1001

1002
            for(size_t pref : m_args.get_int_vec_opt("curves")) {
2,728✔
1003
               const auto group = static_cast<Botan::TLS::Group_Params>(pref);
2,235✔
1004
               if(std::find(supported_groups.cbegin(), supported_groups.cend(), group) != supported_groups.end()) {
2,235✔
1005
                  groups.push_back(group);
1,665✔
1006
               }
1007
            }
493✔
1008

1009
            return groups;
493✔
1010
         }
493✔
1011

1012
         return Botan::TLS::Policy::key_exchange_groups();
6,884✔
1013
      }
1014

1015
      bool use_ecc_point_compression() const override { return false; }  // BoGo expects this
2,246✔
1016

1017
      Botan::TLS::Group_Params choose_key_exchange_group(
2,662✔
1018
         const std::vector<Botan::TLS::Group_Params>& supported_by_peer,
1019
         const std::vector<Botan::TLS::Group_Params>& offered_by_peer) const override {
1020
         BOTAN_UNUSED(offered_by_peer);
2,662✔
1021

1022
         // always insist on our most preferred group regardless of the peer's
1023
         // pre-offers (BoGo expects it like that)
1024
         const auto our_groups = key_exchange_groups();
2,662✔
1025
         for(auto g : our_groups) {
10,177✔
1026
            if(Botan::value_exists(supported_by_peer, g)) {
19,156✔
1027
               return g;
2,063✔
1028
            }
1029
         }
1030

1031
         return Botan::TLS::Group_Params::NONE;
599✔
1032
      }
2,662✔
1033

1034
      bool require_client_certificate_authentication() const override {
538✔
1035
         return m_args.flag_set("require-any-client-certificate");
538✔
1036
      }
1037

1038
      bool request_client_certificate_authentication() const override {
539✔
1039
         return m_args.flag_set("verify-peer") || m_args.flag_set("fail-cert-callback") ||
1,560✔
1040
                require_client_certificate_authentication();
1,049✔
1041
      }
1042

1043
      bool allow_insecure_renegotiation() const override { return m_args.flag_set("expect-no-secure-renegotiation"); }
1,158✔
1044

1045
      //bool include_time_in_hello_random() const override;
1046

1047
      bool allow_client_initiated_renegotiation() const override {
40✔
1048
         if(m_args.flag_set("renegotiate-freely")) {
40✔
1049
            return true;
1050
         }
1051

1052
         if(m_args.flag_set("renegotiate-once") && m_sessions <= 1) {
16✔
1053
            return true;
1054
         }
1055

1056
         return false;
1057
      }
1058

1059
      bool allow_server_initiated_renegotiation() const override {
39✔
1060
         return allow_client_initiated_renegotiation();  // same logic
39✔
1061
      }
1062

1063
      bool allow_version(Botan::TLS::Protocol_Version version) const {
18,486✔
1064
         if(m_args.option_used("min-version")) {
18,486✔
1065
            const uint16_t min_version_16 = static_cast<uint16_t>(m_args.get_int_opt("min-version"));
65✔
1066
            Botan::TLS::Protocol_Version min_version(min_version_16 >> 8, min_version_16 & 0xFF);
65✔
1067
            if(min_version > version) {
65✔
1068
               return false;
15✔
1069
            }
1070
         }
1071

1072
         if(m_args.option_used("max-version")) {
18,471✔
1073
            const uint16_t max_version_16 = static_cast<uint16_t>(m_args.get_int_opt("max-version"));
76✔
1074
            Botan::TLS::Protocol_Version max_version(max_version_16 >> 8, max_version_16 & 0xFF);
76✔
1075
            if(version > max_version) {
76✔
1076
               return false;
13✔
1077
            }
1078
         }
1079

1080
         return version.known_version();
18,458✔
1081
      }
1082

1083
      bool allow_tls12() const override {
10,824✔
1084
         return !m_args.flag_set("dtls") && !m_args.flag_set("no-tls12") &&
21,648✔
1085
                allow_version(Botan::TLS::Protocol_Version::TLS_V12);
21,648✔
1086
      }
1087

1088
      bool allow_tls13() const override {
4,925✔
1089
         return !m_args.flag_set("dtls") && !m_args.flag_set("no-tls13") &&
9,850✔
1090
                allow_version(Botan::TLS::Protocol_Version::TLS_V13);
9,850✔
1091
      }
1092

1093
      bool allow_dtls12() const override {
4,048✔
1094
         return m_args.flag_set("dtls") && !m_args.flag_set("no-tls12") &&
8,096✔
1095
                allow_version(Botan::TLS::Protocol_Version::DTLS_V12);
8,096✔
1096
      }
1097

1098
      //Botan::TLS::Group_Params default_dh_group() const override;
1099

1100
      //size_t minimum_dh_group_size() const override;
1101

1102
      size_t minimum_ecdsa_group_size() const override { return 224; }
131✔
1103

1104
      size_t minimum_ecdh_group_size() const override { return 224; }
1,786✔
1105

1106
      //size_t minimum_rsa_bits() const override;
1107

1108
      //size_t minimum_dsa_group_size() const override;
1109

1110
      //void check_peer_key_acceptable(const Botan::Public_Key& public_key) const override;
1111

1112
      //bool hide_unknown_users() const override;
1113

1114
      //std::chrono::seconds session_ticket_lifetime() const override;
1115

1116
      size_t new_session_tickets_upon_handshake_success() const override {
264✔
1117
         return m_args.flag_set("no-ticket") ? 0 : 1;
527✔
1118
      }
1119

1120
      std::vector<uint16_t> srtp_profiles() const override {
566✔
1121
         if(m_args.option_used("srtp-profiles")) {
566✔
1122
            std::string srtp = m_args.get_string_opt("srtp-profiles");
4✔
1123

1124
            if(srtp == "SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32") {
4✔
1125
               return {1, 2};
3✔
1126
            } else if(srtp == "SRTP_AES128_CM_SHA1_80") {
1✔
1127
               return {1};
1✔
1128
            } else {
1129
               shim_exit_with_error("unknown srtp-profiles");
×
1130
            }
1131
         } else {
4✔
1132
            return {};
562✔
1133
         }
1134
      }
1135

1136
      bool only_resume_with_exact_version() const override { return false; }
198✔
1137

1138
      //bool server_uses_own_ciphersuite_preferences() const override;
1139

1140
      //bool negotiate_encrypt_then_mac() const override;
1141

1142
      bool support_cert_status_message() const override {
2,105✔
1143
         if(m_args.flag_set("server")) {
2,105✔
1144
            if(!m_args.option_used("ocsp-response")) {
581✔
1145
               return false;
1146
            }
1147
            if(m_args.flag_set("decline-ocsp-callback")) {
72✔
1148
               return false;
1149
            }
1150
         } else if(!m_args.flag_set("enable-ocsp-stapling")) {
1,524✔
1151
            return false;
1152
         }
1153

1154
         return true;
1155
      }
1156

1157
      std::vector<uint16_t> ciphersuite_list(Botan::TLS::Protocol_Version version) const override;
1158

1159
      size_t dtls_default_mtu() const override { return m_args.get_int_opt_or_else("mtu", 1500); }
756✔
1160

1161
      //size_t dtls_initial_timeout() const override;
1162

1163
      //size_t dtls_maximum_timeout() const override;
1164

1165
      bool abort_connection_on_undesired_renegotiation() const override {
6✔
1166
         return !m_args.flag_set("renegotiate-ignore");
6✔
1167
      }
1168

1169
      size_t maximum_certificate_chain_size() const override { return m_args.get_int_opt_or_else("max-cert-list", 0); }
1,351✔
1170

1171
      bool tls_13_middlebox_compatibility_mode() const override {
2,728✔
1172
         // These tests expect the client to send an alert in return of a malformed TLS 1.2 server hello.
1173
         // However, our TLS 1.3 implementation produces an alert without downgrading to TLS 1.2 first.
1174
         // In compatibility mode this prepends a CCS, which BoGo does not expect to read.
1175
         const std::vector<std::string> alert_after_server_hello = {
2,728✔
1176
            "DuplicateExtensionClient-TLS-TLS12",
1177
            "WrongMessageType-ServerHello-TLS",
1178
            "SendServerHelloAsHelloRetryRequest",
1179
            "TrailingMessageData-ServerHello-TLS",
1180
            "NoSSL3-Client-Unsolicited",
1181
            "Client-TooLongSessionID",
1182
            "MinimumVersion-Client-TLS13-TLS12-TLS",
1183
            "MinimumVersion-Client2-TLS13-TLS12-TLS",
1184
         };
2,728✔
1185
         return !Botan::value_exists(alert_after_server_hello, m_args.test_name());
5,456✔
1186
      }
2,728✔
1187

1188
   private:
1189
      const Shim_Arguments& m_args;
1190
      size_t m_sessions;
1191
};
1192

1193
std::vector<uint16_t> Shim_Policy::ciphersuite_list(Botan::TLS::Protocol_Version version) const {
3,456✔
1194
   std::vector<uint16_t> ciphersuite_codes;
3,456✔
1195

1196
   const std::string cipher_limit = m_args.get_string_opt_or_else("cipher", "");
6,912✔
1197
   if(cipher_limit ==
3,456✔
1198
      "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:[TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384|TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256|TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA]:TLS_RSA_WITH_AES_128_GCM_SHA256:TLS_RSA_WITH_AES_128_CBC_SHA:[TLS_RSA_WITH_AES_256_GCM_SHA384|TLS_RSA_WITH_AES_256_CBC_SHA]") {
1199
      std::vector<std::string> suites = {
5✔
1200
         "ECDHE_RSA_WITH_AES_128_GCM_SHA256",
1201
         "ECDHE_RSA_WITH_AES_256_GCM_SHA384",
1202
         "ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
1203
         "ECDHE_RSA_WITH_AES_256_CBC_SHA",
1204
         "RSA_WITH_AES_256_GCM_SHA384",
1205
         "RSA_WITH_AES_256_CBC_SHA",
1206
      };
5✔
1207

1208
      for(const auto& suite_name : suites) {
35✔
1209
         const auto suite = Botan::TLS::Ciphersuite::from_name(suite_name);
30✔
1210
         if(!suite || !suite->valid()) {
30✔
1211
            shim_exit_with_error("Bad ciphersuite name " + suite_name);
×
1212
         }
1213
         ciphersuite_codes.push_back(suite->ciphersuite_code());
30✔
1214
      }
1215
   } else {
5✔
1216
      // Hack: go in reverse order to avoid preferring 3DES
1217
      auto ciphersuites = Botan::TLS::Ciphersuite::all_known_ciphersuites();
3,451✔
1218
      // TODO(Botan4) use std::ranges::reverse_view here once available (need newer Clang)
1219
      // NOLINTNEXTLINE(modernize-loop-convert)
1220
      for(auto i = ciphersuites.rbegin(); i != ciphersuites.rend(); ++i) {
355,453✔
1221
         const auto suite = *i;
352,002✔
1222

1223
         const bool usable = suite.valid() && suite.usable_in_version(version) &&
352,002✔
1224
                             Botan::value_exists(allowed_ciphers(), suite.cipher_algo());
563,285✔
1225

1226
         if(usable) {
352,002✔
1227
            ciphersuite_codes.push_back(suite.ciphersuite_code());
180,910✔
1228
         }
1229
      }
1230
   }
3,451✔
1231

1232
   return ciphersuite_codes;
3,456✔
1233
}
3,456✔
1234

1235
class Shim_Credentials final : public Botan::Credentials_Manager {
1236
   public:
1237
      explicit Shim_Credentials(const Shim_Arguments& args) : m_args(args) {
2,106✔
1238
         const auto psk_identity = m_args.get_string_opt_or_else("psk-identity", "");
4,212✔
1239
         const auto psk_str = m_args.get_string_opt_or_else("psk", "");
4,212✔
1240

1241
         if(!psk_identity.empty() || !psk_str.empty()) {
2,106✔
1242
            // If the shim received a -psk param but no -psk-identity param,
1243
            // we have to initialize the identity as "empty string".
1244
            m_psk_identity = psk_identity;
77✔
1245
         }
1246

1247
         if(!psk_str.empty()) {
2,106✔
1248
            m_psk = Botan::SymmetricKey(reinterpret_cast<const uint8_t*>(psk_str.data()), psk_str.size());
77✔
1249
         }
1250

1251
         if(m_args.option_used("key-file") && m_args.option_used("cert-file")) {
3,118✔
1252
            Botan::DataSource_Stream key_stream(m_args.get_string_opt("key-file"));
2,024✔
1253
            m_key.reset(Botan::PKCS8::load_key(key_stream).release());
1,012✔
1254

1255
            Botan::DataSource_Stream cert_stream(m_args.get_string_opt("cert-file"));
2,024✔
1256

1257
            while(!cert_stream.end_of_data()) {
3,040✔
1258
               try {
2,028✔
1259
                  m_cert_chain.push_back(Botan::X509_Certificate(cert_stream));
3,044✔
1260
               } catch(...) {}
1,012✔
1261
            }
1262
         }
1,012✔
1263

1264
         if(m_args.option_used("trust-cert") && !m_args.get_string_opt("trust-cert").empty()) {
5,092✔
1265
            Botan::DataSource_Stream cert_stream(m_args.get_string_opt("trust-cert"));
2,974✔
1266
            try {
1,487✔
1267
               m_trust_roots.add_certificate(Botan::X509_Certificate(cert_stream));
1,487✔
1268
            } catch(const std::exception& ex) {
×
1269
               throw Shim_Exception("Failed to load trusted root certificate: " + std::string(ex.what()));
×
1270
            }
×
1271
         }
1,487✔
1272
      }
2,106✔
1273

1274
      std::vector<Botan::Certificate_Store*> trusted_certificate_authorities(const std::string& type,
2,084✔
1275
                                                                             const std::string& context) override {
1276
         if(m_args.flag_set("server") && type != "tls-server") {
4,168✔
1277
            throw Shim_Exception("TLS server implementation asked for unexpected trusted CA type: " + type);
×
1278
         }
1279
         if(!m_args.flag_set("server") && type != "tls-client") {
4,168✔
1280
            throw Shim_Exception("TLS client implementation asked for unexpected trusted CA type: " + type);
×
1281
         }
1282

1283
         const auto expected_hostname = m_args.get_string_opt_or_else("host-name", "none");
4,168✔
1284
         if(expected_hostname != "none" && expected_hostname != context) {
2,084✔
1285
            throw Shim_Exception("Unexpected host name in trusted CA request: " + context);
×
1286
         }
1287

1288
         return {&m_trust_roots};
2,084✔
1289
      }
2,084✔
1290

1291
      std::string psk_identity(const std::string& /*type*/,
48✔
1292
                               const std::string& /*context*/,
1293
                               const std::string& /*identity_hint*/) override {
1294
         return m_psk_identity.value_or("");
48✔
1295
      }
1296

1297
      std::string psk_identity_hint(const std::string& /*type*/, const std::string& /*context*/) override {
27✔
1298
         return m_psk_identity.value_or("");
27✔
1299
      }
1300

1301
      Botan::secure_vector<uint8_t> session_ticket_key() override {
1,764✔
1302
         return Botan::hex_decode_locked("ABCDEF0123456789");
1,764✔
1303
      }
1304

1305
      Botan::secure_vector<uint8_t> dtls_cookie_secret() override {
658✔
1306
         return Botan::hex_decode_locked("F00FB00FD00F100F700F");
658✔
1307
      }
1308

1309
      std::vector<Botan::TLS::ExternalPSK> find_preshared_keys(
1,029✔
1310
         std::string_view host,
1311
         Botan::TLS::Connection_Side whoami,
1312
         const std::vector<std::string>& identities = {},
1313
         const std::optional<std::string>& prf = std::nullopt) override {
1314
         if(!m_psk_identity.has_value()) {
1,029✔
1315
            return Botan::Credentials_Manager::find_preshared_keys(host, whoami, identities, prf);
927✔
1316
         }
1317

1318
         auto id_matches =
102✔
1319
            identities.empty() || std::find(identities.begin(), identities.end(), m_psk_identity) != identities.end();
102✔
1320

1321
         if(!id_matches) {
102✔
1322
            throw Shim_Exception("Unexpected PSK identity");
×
1323
         }
1324

1325
         if(!m_psk.has_value()) {
102✔
1326
            throw Shim_Exception("PSK identified but not set");
×
1327
         }
1328

1329
         std::vector<Botan::TLS::ExternalPSK> psks;
102✔
1330

1331
         // Currently, BoGo tests PSK with TLS 1.2 only. In TLS 1.2 the PRF does not
1332
         // need to be specified for PSKs.
1333
         //
1334
         // TODO: Once BoGo has tests for TLS 1.3 with externally provided PSKs, this
1335
         //       will need to be handled somehow.
1336
         const std::string psk_prf = "SHA-256";
102✔
1337
         psks.emplace_back(m_psk_identity.value(), psk_prf, m_psk->bits_of());
102✔
1338
         return psks;
102✔
1339
      }
102✔
1340

1341
      std::vector<Botan::X509_Certificate> cert_chain(
2,265✔
1342
         const std::vector<std::string>& cert_key_types,
1343
         const std::vector<Botan::AlgorithmIdentifier>& /*cert_signature_schemes*/,
1344
         const std::string& /*type*/,
1345
         const std::string& /*context*/) override {
1346
         if(m_args.flag_set("fail-cert-callback")) {
2,265✔
1347
            throw std::runtime_error("Simulating cert verify callback failure");
4✔
1348
         }
1349

1350
         if(m_key != nullptr && !m_cert_chain.empty()) {
2,261✔
1351
            for(const std::string& t : cert_key_types) {
3,298✔
1352
               if(t == m_key->algo_name()) {
2,161✔
1353
                  return m_cert_chain;
2,261✔
1354
               }
1355
            }
1356
         }
1357

1358
         return {};
1,320✔
1359
      }
1360

1361
      std::shared_ptr<Botan::Private_Key> private_key_for(const Botan::X509_Certificate& /*cert*/,
897✔
1362
                                                          const std::string& /*type*/,
1363
                                                          const std::string& /*context*/) override {
1364
         // assumes cert == m_cert
1365
         return m_key;
897✔
1366
      }
1367

1368
   private:
1369
      const Shim_Arguments& m_args;
1370
      std::optional<Botan::SymmetricKey> m_psk;
1371
      std::optional<std::string> m_psk_identity;
1372
      std::shared_ptr<Botan::Private_Key> m_key;
1373
      std::vector<Botan::X509_Certificate> m_cert_chain;
1374
      Botan::Certificate_Store_In_Memory m_trust_roots;
1375
};
1376

1377
class Shim_Callbacks final : public Botan::TLS::Callbacks {
2,697✔
1378
   public:
1379
      Shim_Callbacks(const Shim_Arguments& args, Shim_Socket& socket, Shim_Policy& policy) :
2,715✔
1380
            m_channel(nullptr),
2,715✔
1381
            m_args(args),
2,715✔
1382
            m_policy(policy),
2,715✔
1383
            m_socket(socket),
2,715✔
1384
            m_is_datagram(args.flag_set("dtls")),
2,715✔
1385
            m_warning_alerts(0),
2,715✔
1386
            m_empty_records(0),
2,715✔
1387
            m_sessions_established(0),
2,715✔
1388
            m_got_close(false),
2,715✔
1389
            m_hello_retry_request(false),
2,715✔
1390
            m_clock_skew(0) {}
5,430✔
1391

1392
      size_t sessions_established() const { return m_sessions_established; }
21✔
1393

1394
      void set_channel(Botan::TLS::Channel* channel) { m_channel = channel; }
2,713✔
1395

1396
      void set_clock_skew(std::chrono::seconds clock_skew) { m_clock_skew = clock_skew; }
3✔
1397

1398
      bool saw_close_notify() const { return m_got_close; }
27✔
1399

1400
      void tls_emit_data(std::span<const uint8_t> data) override {
16,341✔
1401
         shim_log("sending record of len " + std::to_string(data.size()));
49,023✔
1402

1403
         if(m_args.option_used("write-settings")) {
16,341✔
1404
            // TODO: the transcript option should probably be used differently
1405
            std::cout << ">>>" << std::endl << Botan::hex_encode(data) << std::endl << ">>>" << std::endl;
×
1406
         }
1407

1408
         if(m_is_datagram) {
16,341✔
1409
            std::vector<uint8_t> packet(data.size() + 5);
6,030✔
1410

1411
            packet[0] = 'P';
6,030✔
1412
            for(size_t i = 0; i != 4; ++i) {
30,150✔
1413
               packet[i + 1] = static_cast<uint8_t>((data.size() >> (24 - 8 * i)) & 0xFF);
24,120✔
1414
            }
1415
            std::memcpy(packet.data() + 5, data.data(), data.size());
6,030✔
1416

1417
            m_socket.write(packet.data(), packet.size());
6,030✔
1418
         } else {
6,030✔
1419
            m_socket.write(data.data(), data.size());
10,311✔
1420
         }
1421
      }
16,341✔
1422

1423
      std::vector<uint8_t> tls_provide_cert_status(const std::vector<Botan::X509_Certificate>& /*certs*/,
794✔
1424
                                                   const Botan::TLS::Certificate_Status_Request& /*status*/) override {
1425
         if(m_args.flag_set("use-ocsp-callback") && m_args.flag_set("fail-ocsp-callback")) {
874✔
1426
            throw std::runtime_error("Simulating failure from OCSP response callback");
32✔
1427
         }
1428

1429
         if(m_args.flag_set("decline-ocsp-callback")) {
762✔
1430
            return {};
24✔
1431
         }
1432

1433
         if(m_args.option_used("ocsp-response")) {
738✔
1434
            return m_args.get_b64_opt("ocsp-response");
96✔
1435
         }
1436

1437
         return {};
690✔
1438
      }
1439

1440
      void tls_record_received(uint64_t /*seq_no*/, std::span<const uint8_t> data) override {
2,352✔
1441
         if(data.empty()) {
2,352✔
1442
            m_empty_records += 1;
98✔
1443
            if(m_empty_records > 32) {
98✔
1444
               shim_exit_with_error(":TOO_MANY_EMPTY_FRAGMENTS:");
2✔
1445
            }
1446
         } else {
1447
            m_empty_records = 0;
2,254✔
1448
         }
1449

1450
         shim_log("Reflecting application_data len " + std::to_string(data.size()));
7,050✔
1451

1452
         std::vector<uint8_t> buf(data.begin(), data.end());
2,350✔
1453
         for(auto& b : buf) {
1,178,137✔
1454
            b ^= 0xFF;
1,175,787✔
1455
         }
1456

1457
         m_channel->send(buf);
2,350✔
1458
      }
2,350✔
1459

1460
      bool tls_verify_message(const Botan::Public_Key& key,
1,094✔
1461
                              std::string_view padding,
1462
                              Botan::Signature_Format format,
1463
                              const std::vector<uint8_t>& msg,
1464
                              const std::vector<uint8_t>& sig) override {
1465
         if(m_args.option_used("expect-peer-signature-algorithm")) {
1,094✔
1466
            const Botan::TLS::Signature_Scheme scheme(
65✔
1467
               static_cast<uint16_t>(m_args.get_int_opt("expect-peer-signature-algorithm")));
65✔
1468

1469
            if(!scheme.is_available()) {
65✔
1470
               shim_exit_with_error(std::string("Unsupported signature scheme provided by BoGo: ") +
×
1471
                                    scheme.to_string());
×
1472
            }
1473

1474
            const std::string exp_padding = scheme.padding_string();
65✔
1475
            if(padding != exp_padding) {
130✔
1476
               shim_exit_with_error(Botan::fmt("Unexpected signature scheme got {} expected {}", padding, exp_padding));
×
1477
            }
1478
         }
65✔
1479

1480
         return Botan::TLS::Callbacks::tls_verify_message(key, padding, format, msg, sig);
1,094✔
1481
      }
1482

1483
      void tls_verify_cert_chain(const std::vector<Botan::X509_Certificate>& cert_chain,
1,278✔
1484
                                 const std::vector<std::optional<Botan::OCSP::Response>>& ocsp_responses,
1485
                                 const std::vector<Botan::Certificate_Store*>& trusted_roots,
1486
                                 Botan::Usage_Type usage,
1487
                                 std::string_view /* hostname */,
1488
                                 const Botan::TLS::Policy& policy) override {
1489
         if(m_args.flag_set("enable-ocsp-stapling") && m_args.flag_set("use-ocsp-callback") &&
2,679✔
1490
            m_args.flag_set("fail-ocsp-callback")) {
1,374✔
1491
            throw Botan::TLS::TLS_Exception(Botan::TLS::Alert::BadCertificateStatusResponse,
64✔
1492
                                            "Simulated OCSP callback failure");
64✔
1493
         }
1494

1495
         if(m_args.flag_set("verify-fail")) {
1,214✔
1496
            auto alert = Botan::TLS::Alert::HandshakeFailure;
128✔
1497
            if(m_args.flag_set("use-custom-verify-callback")) {
128✔
1498
               alert = Botan::TLS::Alert::CertificateUnknown;
64✔
1499
            }
1500

1501
            throw Botan::TLS::TLS_Exception(alert, "Test requires rejecting cert");
128✔
1502
         }
1503

1504
         if(!cert_chain.empty() && cert_chain.front().is_self_signed()) {
1,086✔
1505
            for(auto* const roots : trusted_roots) {
1,080✔
1506
               if(roots->certificate_known(cert_chain.front())) {
1,080✔
1507
                  shim_log("Trusting self-signed certificate");
1,080✔
1508
                  return;
1,080✔
1509
               }
1510
            }
1511
         }
1512

1513
         shim_log("Establishing trust from a certificate chain");
6✔
1514

1515
         Botan::TLS::Callbacks::tls_verify_cert_chain(
6✔
1516
            cert_chain, ocsp_responses, trusted_roots, usage, "" /* hostname */, policy);
1517
      }
1518

1519
      std::optional<Botan::OCSP::Response> tls_parse_ocsp_response(const std::vector<uint8_t>& raw_response) override {
89✔
1520
         if(m_args.option_used("expect-ocsp-response") && m_args.get_b64_opt("expect-ocsp-response") != raw_response) {
164✔
1521
            shim_exit_with_error("unexpected OCSP response");
×
1522
         }
1523

1524
         // Bogo uses invalid dummy OCSP responses. Don't even bother trying to
1525
         // decode them.
1526
         return std::nullopt;
89✔
1527
      }
1528

1529
      void tls_modify_extensions(Botan::TLS::Extensions& exts,
3,714✔
1530
                                 Botan::TLS::Connection_Side /* side */,
1531
                                 Botan::TLS::Handshake_Type msg_type) override {
1532
         if(msg_type == Botan::TLS::Handshake_Type::CertificateRequest) {
3,714✔
1533
            if(m_args.option_used("use-client-ca-list")) {
95✔
1534
               // The CertificateAuthorities extension is filled with the CA
1535
               // list provided by the credentials manager. The same list is
1536
               // used to later verify the client certificate chain.
1537
               //
1538
               // Hence, we have to use this low-level callback to fulfill the
1539
               // BoGo requirement of sending specific configurations of the CA
1540
               // list in the CertificateRequest message.
1541
               if(m_args.get_string_opt("use-client-ca-list") == "<EMPTY>" ||
4✔
1542
                  m_args.get_string_opt("use-client-ca-list") == "<NULL>") {
4✔
1543
                  exts.remove_extension(Botan::TLS::Extension_Code::CertificateAuthorities);
1✔
1544
               } else {
1545
                  // TODO: -use-client-ca-list might also provide the encoded
1546
                  //       list of DNs. We could render this here, if needed.
1547
               }
1548
            }
1549
         }
1550
      }
3,714✔
1551

1552
      std::string tls_server_choose_app_protocol(const std::vector<std::string>& client_protos) override {
21✔
1553
         if(client_protos.empty()) {
21✔
1554
            return "";  // shouldn't happen?
×
1555
         }
1556

1557
         if(m_args.flag_set("reject-alpn")) {
21✔
1558
            throw Botan::TLS::TLS_Exception(Botan::TLS::Alert::NoApplicationProtocol,
3✔
1559
                                            "Rejecting ALPN request with alert");
3✔
1560
         }
1561

1562
         if(m_args.flag_set("decline-alpn")) {
18✔
1563
            return "";
6✔
1564
         }
1565

1566
         if(m_args.option_used("expect-advertised-alpn")) {
12✔
1567
            const std::vector<std::string> expected = m_args.get_alpn_string_vec_opt("expect-advertised-alpn");
12✔
1568

1569
            if(client_protos != expected) {
12✔
1570
               shim_exit_with_error("Bad ALPN from client");
×
1571
            }
1572
         }
12✔
1573

1574
         if(m_args.option_used("select-alpn")) {
12✔
1575
            return m_args.get_string_opt("select-alpn");
24✔
1576
         }
1577

1578
         return client_protos[0];  // if not configured just pick something
×
1579
      }
1580

1581
      void tls_alert(Botan::TLS::Alert alert) override {
1,911✔
1582
         if(alert.is_fatal()) {
1,911✔
1583
            shim_log("Got a fatal alert " + alert.type_string());
39✔
1584
         } else {
1585
            shim_log("Got a warning alert " + alert.type_string());
5,694✔
1586
         }
1587

1588
         if(alert.type() == Botan::TLS::Alert::RecordOverflow) {
1,911✔
1589
            shim_exit_with_error(":TLSV1_ALERT_RECORD_OVERFLOW:");
4✔
1590
         }
1591

1592
         if(alert.type() == Botan::TLS::Alert::DecompressionFailure) {
1,907✔
1593
            shim_exit_with_error(":SSLV3_ALERT_DECOMPRESSION_FAILURE:");
1✔
1594
         }
1595

1596
         if(!alert.is_fatal()) {
1,906✔
1597
            m_warning_alerts++;
1,898✔
1598
            if(m_warning_alerts > 5) {
1,898✔
1599
               shim_exit_with_error(":TOO_MANY_WARNING_ALERTS:");
3✔
1600
            }
1601
         }
1602

1603
         if(alert.type() == Botan::TLS::Alert::CloseNotify) {
1,903✔
1604
            if(!m_got_close && !m_args.flag_set("shim-shuts-down")) {
3,750✔
1605
               shim_log("Sending return close notify");
1,848✔
1606
               m_channel->send_alert(alert);
1,848✔
1607
            }
1608
            m_got_close = true;
1,866✔
1609
         } else if(alert.is_fatal()) {
37✔
1610
            shim_exit_with_error("Unexpected fatal alert " + alert.type_string());
16✔
1611
         }
1612
      }
1,895✔
1613

1614
      void tls_session_established(const Botan::TLS::Session_Summary& session) override {
2,025✔
1615
         shim_log("Session established: " + Botan::hex_encode(session.session_id().get()) + " version " +
12,150✔
1616
                  session.version().to_string() + " cipher " + session.ciphersuite().to_string() + " " +
12,150✔
1617
                  std::string((session.supports_extended_master_secret() ? "with EMS" : "without EMS")));
2,040✔
1618
         // probably need tests here?
1619

1620
         m_policy.incr_session_established();
2,025✔
1621
         m_sessions_established++;
2,025✔
1622

1623
         if(m_args.flag_set("expect-no-session-id")) {
2,025✔
1624
            // BoGo expects that ticket issuance implies no stateful session...
1625
            if(!m_args.flag_set("server") && !session.session_id().empty()) {
112✔
1626
               shim_exit_with_error("Unexpectedly got a session ID");
×
1627
            }
1628
         } else if(m_args.flag_set("expect-session-id") && session.session_id().empty()) {
3,938✔
1629
            shim_exit_with_error("Unexpectedly got no session ID");
×
1630
         }
1631

1632
         if(m_args.option_used("expect-version")) {
2,025✔
1633
            if(session.version().version_code() != m_args.get_int_opt("expect-version")) {
×
1634
               shim_exit_with_error("Unexpected version");
×
1635
            }
1636
         }
1637

1638
         if(m_args.flag_set("expect-secure-renegotiation")) {
2,025✔
1639
            if(!m_channel->secure_renegotiation_supported()) {
9✔
1640
               shim_exit_with_error("Expected secure renegotiation");
×
1641
            }
1642
         } else if(m_args.flag_set("expect-no-secure-renegotiation")) {
2,016✔
1643
            if(m_channel->secure_renegotiation_supported()) {
2✔
1644
               shim_exit_with_error("Expected no secure renegotiation");
×
1645
            }
1646
         }
1647

1648
         if(m_args.flag_set("expect-extended-master-secret")) {
2,025✔
1649
            if(!session.supports_extended_master_secret()) {
10✔
1650
               shim_exit_with_error("Expected extended maseter secret");
×
1651
            }
1652
         }
1653
      }
2,025✔
1654

1655
      void tls_session_activated() override {
2,012✔
1656
         if(m_args.flag_set("send-alert")) {
2,012✔
1657
            m_channel->send_fatal_alert(Botan::TLS::Alert::DecompressionFailure);
16✔
1658
            return;
16✔
1659
         }
1660

1661
         if(size_t length = m_args.get_int_opt_or_else("export-keying-material", 0)) {
1,996✔
1662
            const std::string label = m_args.get_string_opt("export-label");
176✔
1663
            const std::string context = m_args.get_string_opt("export-context");
176✔
1664
            const auto exported = m_channel->key_material_export(label, context, length);
176✔
1665
            shim_log("Sending " + std::to_string(length) + " bytes of key material");
704✔
1666
            m_channel->send(exported.bits_of());
352✔
1667
         }
176✔
1668

1669
         const std::string alpn = m_channel->application_protocol();
1,996✔
1670

1671
         if(m_args.option_used("expect-alpn")) {
1,996✔
1672
            if(alpn != m_args.get_string_opt("expect-alpn")) {
10✔
1673
               shim_exit_with_error("Got unexpected ALPN");
×
1674
            }
1675
         }
1676

1677
         if(alpn == "baz" && !m_args.flag_set("allow-unknown-alpn-protos")) {
2,005✔
1678
            throw Botan::TLS::TLS_Exception(Botan::TLS::Alert::IllegalParameter, "Unexpected ALPN protocol");
3✔
1679
         }
1680

1681
         if(m_args.flag_set("shim-shuts-down")) {
1,993✔
1682
            shim_log("Shim shutting down");
45✔
1683
            m_channel->close();
45✔
1684
         }
1685

1686
         if(m_args.flag_set("write-different-record-sizes")) {
1,993✔
1687
            static const size_t record_sizes[] = {0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
×
1688

1689
            std::vector<uint8_t> buf(32769, 0x42);
×
1690

1691
            for(size_t sz : record_sizes) {
×
1692
               m_channel->send(buf.data(), sz);
×
1693
            }
1694

1695
            m_channel->close();
×
1696
         }
×
1697

1698
         if(m_args.flag_set("expect-hrr") && !m_hello_retry_request) {
3,986✔
1699
            throw Shim_Exception("Expected Hello Retry Request but didn't see one");
×
1700
         }
1701

1702
         if(m_args.flag_set("expect-no-hrr") && m_hello_retry_request) {
3,986✔
1703
            throw Shim_Exception("Hello Retry Request seen but didn't expect one");
×
1704
         }
1705

1706
         if(m_args.flag_set("key-update")) {
1,993✔
1707
            shim_log("Updating traffic keys without asking for reciprocation");
5✔
1708
            m_channel->update_traffic_keys(false /* don't request reciprocal update */);
2✔
1709
         }
1710
      }
1,993✔
1711

1712
      std::chrono::system_clock::time_point tls_current_timestamp() override {
8,910✔
1713
         // Some tests require precise timings. Hence, the TLS 'now' timestamp
1714
         // is frozen on first access and rounded to the last full second. E.g.
1715
         // storage of sessions does store the timestamp with second-resolution.
1716
         using sec = std::chrono::seconds;
8,910✔
1717
         static auto g_now = std::chrono::floor<sec>(std::chrono::system_clock::now());
8,910✔
1718
         return g_now + m_clock_skew;
8,910✔
1719
      }
1720

1721
      void tls_inspect_handshake_msg(const Botan::TLS::Handshake_Message& msg) override {
21,458✔
1722
         if(msg.type() == Botan::TLS::Handshake_Type::HelloRetryRequest) {
21,458✔
1723
            m_hello_retry_request = true;
82✔
1724
         }
1725
      }
21,458✔
1726

1727
   private:
1728
      Botan::TLS::Channel* m_channel;
1729
      const Shim_Arguments& m_args;
1730
      Shim_Policy& m_policy;
1731
      Shim_Socket& m_socket;
1732
      const bool m_is_datagram;
1733
      size_t m_warning_alerts;
1734
      size_t m_empty_records;
1735
      size_t m_sessions_established;
1736
      bool m_got_close;
1737
      bool m_hello_retry_request;
1738
      std::chrono::seconds m_clock_skew;
1739
};
1740

1741
}  // namespace
1742

1743
int main(int /*argc*/, char* argv[]) {
2,107✔
1744
   try {
2,107✔
1745
      std::unique_ptr<Shim_Arguments> args = parse_options(argv);
2,107✔
1746

1747
      if(args->flag_set("is-handshaker-supported")) {
2,107✔
1748
         return shim_output("No\n");
1✔
1749
      }
1750

1751
      const uint16_t port = static_cast<uint16_t>(args->get_int_opt("port"));
2,106✔
1752
      const size_t resume_count = args->get_int_opt_or_else("resume-count", 0);
2,106✔
1753
      const bool is_server = args->flag_set("server");
2,106✔
1754
      const bool is_datagram = args->flag_set("dtls");
2,106✔
1755
      const size_t buf_size = args->get_int_opt_or_else("read-size", 18 * 1024);
2,106✔
1756

1757
      auto rng = std::make_shared<Botan::ChaCha_RNG>(Botan::secure_vector<uint8_t>(64));
4,212✔
1758
      auto creds = std::make_shared<Shim_Credentials>(*args);
2,106✔
1759
      auto session_manager = [&]() -> std::shared_ptr<Botan::TLS::Session_Manager> {
805✔
1760
         if(args->flag_set("no-ticket") || args->flag_set("on-resume-no-ticket")) {
4,210✔
1761
            // The in-memory session manager stores sessions in volatile memory and
1762
            // hands out Session_IDs (i.e. does not utilize session tickets)
1763
            return std::make_shared<Botan::TLS::Session_Manager_In_Memory>(rng, 1024);
2✔
1764
         } else {
1765
            // The hybrid session manager prefers stateless tickets (when used in
1766
            // servers) but can also fall back to stateful management when tickets
1767
            // are not an option.
1768
            return std::make_shared<Botan::TLS::Session_Manager_Hybrid>(
2,104✔
1769
               std::make_unique<Botan::TLS::Session_Manager_In_Memory>(rng, 1024), creds, rng);
4,208✔
1770
         }
1771
      }();
2,106✔
1772

1773
      if(args->flag_set("wait-for-debugger")) {
2,911✔
1774
         sleep(20);
×
1775
      }
1776

1777
      for(size_t i = 0; i != resume_count + 1; ++i) {
3,998✔
1778
         auto execute_test = [&](const std::string& hostname) {
5,430✔
1779
            Shim_Socket socket(hostname, port, args->flag_set("ipv6"));
2,715✔
1780

1781
            shim_log("Connection " + std::to_string(i + 1) + "/" + std::to_string(resume_count + 1));
10,860✔
1782

1783
            // The ShimID must be written on the socket as a 64-bit little-endian integer
1784
            // *before* any test data is transferred
1785
            // See: https://github.com/google/boringssl/commit/50ee09552cde1c2019bef24520848d041920cfd4
1786
            shim_log("Sending ShimID: " + std::to_string(args->get_int_opt("shim-id")));
8,145✔
1787
            std::array<uint8_t, 8> shim_id{};
2,715✔
1788
            Botan::store_le(static_cast<uint64_t>(args->get_int_opt("shim-id")), shim_id.data());
3,520✔
1789
            socket.write(shim_id.data(), shim_id.size());
2,715✔
1790

1791
            auto policy = std::make_shared<Shim_Policy>(*args);
2,715✔
1792
            auto callbacks = std::make_shared<Shim_Callbacks>(*args, socket, *policy);
2,715✔
1793

1794
            if(args->option_used("resumption-delay") && i > 0) {
5,430✔
1795
               shim_log("skewing the clock by " + std::to_string(args->get_int_opt("resumption-delay")) + " seconds");
12✔
1796
               callbacks->set_clock_skew(std::chrono::seconds(args->get_int_opt("resumption-delay")));
808✔
1797
            }
1798

1799
            std::unique_ptr<Botan::TLS::Channel> chan;
2,715✔
1800

1801
            if(is_server) {
2,715✔
1802
               chan = std::make_unique<Botan::TLS::Server>(callbacks, session_manager, creds, policy, rng, is_datagram);
1,222✔
1803
            } else {
1804
               Botan::TLS::Protocol_Version offer_version = policy->latest_supported_version(is_datagram);
1,493✔
1805
               shim_log("Offering " + offer_version.to_string());
4,473✔
1806

1807
               std::string host_name = args->get_string_opt_or_else("host-name", hostname);
1,491✔
1808
               if(args->test_name().starts_with("UnsolicitedServerNameAck")) {
2,982✔
1809
                  host_name = "";  // avoid sending SNI for this test
3✔
1810
               }
1811

1812
               Botan::TLS::Server_Information server_info(host_name, port);
1,491✔
1813
               const std::vector<std::string> next_protocols = args->get_alpn_string_vec_opt("advertise-alpn");
1,491✔
1814
               chan = std::make_unique<Botan::TLS::Client>(
1,491✔
1815
                  callbacks, session_manager, creds, policy, rng, server_info, offer_version, next_protocols);
1,491✔
1816
            }
2,982✔
1817

1818
            callbacks->set_channel(chan.get());
2,713✔
1819

1820
            std::vector<uint8_t> buf(buf_size);
3,518✔
1821

1822
            for(;;) {
203,970✔
1823
               if(is_datagram) {
203,970✔
1824
                  uint8_t opcode = 0;
184,524✔
1825
                  size_t got = socket.read(&opcode, 1);
184,524✔
1826
                  if(got == 0) {
184,524✔
1827
                     shim_log("EOF on socket");
578✔
1828
                     break;
578✔
1829
                  }
1830

1831
                  if(opcode == 'P') {
183,946✔
1832
                     uint8_t len_bytes[4];
183,946✔
1833
                     socket.read_exactly(len_bytes, sizeof(len_bytes));
183,946✔
1834

1835
                     size_t packet_len = Botan::load_be<uint32_t>(len_bytes, 0);
183,946✔
1836

1837
                     if(buf.size() < packet_len) {
183,946✔
1838
                        buf.resize(packet_len);
1✔
1839
                     }
1840
                     socket.read_exactly(buf.data(), packet_len);
183,946✔
1841

1842
                     chan->received_data(buf.data(), packet_len);
183,946✔
1843
                  } else if(opcode == 'T') {
×
1844
                     uint8_t timeout_ack = 't';
×
1845

1846
                     uint8_t timeout_bytes[8];
×
1847
                     socket.read_exactly(timeout_bytes, sizeof(timeout_bytes));
×
1848

1849
                     const uint64_t nsec = Botan::load_be<uint64_t>(timeout_bytes, 0);
×
1850

1851
                     shim_log("Timeout nsec " + std::to_string(nsec));
×
1852

1853
                     // FIXME handle this!
1854

1855
                     socket.write(&timeout_ack, 1);  // ack it anyway
×
1856
                  } else {
1857
                     shim_exit_with_error("Unknown opcode " + std::to_string(opcode));
×
1858
                  }
1859
               } else {
1860
                  size_t got = socket.read(buf.data(), buf.size());
19,446✔
1861
                  if(got == 0) {
19,446✔
1862
                     shim_log("EOF on socket");
1,315✔
1863
                     break;
1,315✔
1864
                  }
1865

1866
                  shim_log("Got packet of " + std::to_string(got));
54,393✔
1867

1868
                  if(args->option_used("write-settings")) {
18,131✔
1869
                     // TODO: the transcript option should probably be used differently
1870
                     std::cout << "<<<" << std::endl
×
1871
                               << Botan::hex_encode(buf.data(), got) << std::endl
×
1872
                               << "<<<" << std::endl;
×
1873
                  }
1874

1875
                  if(args->flag_set("use-exporter-between-reads") && chan->is_active()) {
36,262✔
1876
                     chan->key_material_export("some label", "some context", 42);
1✔
1877
                  }
1878
                  const size_t needed = chan->received_data(buf.data(), got);
18,130✔
1879

1880
                  if(needed > 0) {
17,487✔
1881
                     shim_log("Short read still need " + std::to_string(needed));
31,755✔
1882
                  }
1883
               }
1884
            }
1885

1886
            if(args->flag_set("check-close-notify")) {
1,893✔
1887
               if(!callbacks->saw_close_notify()) {
27✔
1888
                  throw Shim_Exception("Unexpected SSL_shutdown result: -1 != 1");
1✔
1889
               }
1890
            }
1891

1892
            if(args->option_used("expect-total-renegotiations")) {
1,892✔
1893
               const size_t exp = args->get_int_opt("expect-total-renegotiations");
21✔
1894

1895
               if(exp != callbacks->sessions_established() - 1) {
21✔
1896
                  throw Shim_Exception("Unexpected number of renegotiations: saw " +
×
1897
                                       std::to_string(callbacks->sessions_established() - 1) + " exp " +
×
1898
                                       std::to_string(exp));
×
1899
               }
1900
            }
1901
            shim_log("End of resume loop");
2,695✔
1902
         };
10,786✔
1903
         try {
2,715✔
1904
            execute_test("localhost");
5,412✔
1905
         } catch(const Shim_Exception& e) {
805✔
1906
            if(std::string(e.what()) == "Failed to connect to host") {
1✔
1907
               execute_test("::1");
×
1908
            } else {
1909
               // NOLINTNEXTLINE(cert-err60-cpp)
1910
               throw e;
1✔
1911
            }
1912
         }
1✔
1913
      }
1914
   } catch(Shim_Exception& e) {
7,070✔
1915
      shim_exit_with_error(e.what(), e.rc());
1✔
1916
   } catch(std::exception& e) {
804✔
1917
      shim_exit_with_error(map_to_bogo_error(e.what()));
804✔
1918
   } catch(...) {
×
1919
      shim_exit_with_error("Unknown exception", 3);
×
1920
   }
×
1921
   return 0;
1,283✔
1922
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc