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

randombit / botan / 15805862055

22 Jun 2025 10:58AM UTC coverage: 90.556% (-0.005%) from 90.561%
15805862055

Pull #4941

github

web-flow
Merge ec912e1c7 into cc35cab91
Pull Request #4941: Test: GCC's Stack Scrubbing on aarch64

98791 of 109094 relevant lines covered (90.56%)

12355948.55 hits per line

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

87.63
/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 <ctime>
34
#include <iostream>
35
#include <map>
36
#include <memory>
37
#include <set>
38
#include <string>
39
#include <unordered_map>
40
#include <vector>
41

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

53
namespace {
54

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

60
void shim_log(const std::string& s) {
87,569✔
61
   if(::getenv("BOTAN_BOGO_SHIM_LOG")) {
87,569✔
62
      /*
63
      FIXMEs:
64
       - Rewrite this to use a std::ostream instead
65
       - Allow using the env variable to point to where the log is written
66
       - Avoid rechecking the env variable with each call (!)
67
      */
68

69
      // NOLINTNEXTLINE(*-avoid-non-const-global-variables)
70
      static FILE* g_log = std::fopen("/tmp/bogo_shim.log", "w");
×
71

72
      if(g_log) {
×
73
         struct timeval tv;
×
74
         ::gettimeofday(&tv, nullptr);
×
75
         static_cast<void>(std::fprintf(g_log,
×
76
                                        "%lld.%lu: %s\n",
77
                                        static_cast<unsigned long long>(tv.tv_sec),
×
78
                                        static_cast<unsigned long>(tv.tv_usec),
×
79
                                        s.c_str()));
80
         static_cast<void>(std::fflush(g_log));
×
81
      }
82
   }
83
}
87,569✔
84

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

91
std::string map_to_bogo_error(const std::string& e) noexcept {
804✔
92
   shim_log("Original error " + e);
804✔
93

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

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

345
   return "Unmapped error: '" + e + "'";
8✔
346
}
804✔
347

348
class Shim_Exception final : public std::exception {
349
   public:
350
      Shim_Exception(std::string_view msg, int rc = 1) : m_msg(msg), m_rc(rc) {}
2✔
351

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

354
      int rc() const { return m_rc; }
1✔
355

356
   private:
357
      const std::string m_msg;
358
      int m_rc;
359
};
360

361
#if defined(BOTAN_TARGET_OS_HAS_SOCKETS)
362

363
class Shim_Socket final {
364
   private:
365
      typedef int socket_type;
366
      typedef ssize_t socket_op_ret_type;
367

368
      static void close_socket(socket_type s) { ::close(s); }
369

370
      static std::string get_last_socket_error() { return ::strerror(errno); }
371

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

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

382
         const std::string service = std::to_string(port);
2,715✔
383

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

391
         shim_log("Connecting " + hostname + ":" + service);
10,860✔
392

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

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

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

404
            if(m_socket == -1) {
2,715✔
405
               // unsupported socket type?
406
               continue;
×
407
            }
408

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

411
            if(err != 0) {
2,715✔
412
               ::close(m_socket);
×
413
               m_socket = -1;
×
414
            }
415
         }
416

417
         if(m_socket < 0) {
2,715✔
418
            throw Shim_Exception("Failed to connect to host");
×
419
         }
420
      }
2,715✔
421

422
      Shim_Socket(const Shim_Socket&) = delete;
423
      Shim_Socket& operator=(const Shim_Socket&) = delete;
424

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

428
      ~Shim_Socket() {
2,697✔
429
         ::close(m_socket);
2,697✔
430
         m_socket = -1;
2,697✔
431
      }
2,697✔
432

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

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

460
         if(got < 0) {
203,713✔
461
            if(errno == ECONNRESET) {
311✔
462
               return 0;
463
            }
464
            throw Shim_Exception("Socket read failed: " + std::string(strerror(errno)));
×
465
         }
466

467
         return static_cast<size_t>(got);
203,402✔
468
      }
469

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

475
         while(len > 0) {
735,800✔
476
            socket_op_ret_type got = ::read(m_socket, Botan::cast_uint8_ptr_to_char(buf), len);
367,900✔
477

478
            if(got == 0) {
367,900✔
479
               throw Shim_Exception("Socket read EOF");
×
480
            } else if(got < 0) {
367,900✔
481
               throw Shim_Exception("Socket read failed: " + std::string(strerror(errno)));
×
482
            }
483

484
            buf += static_cast<size_t>(got);
367,900✔
485
            len -= static_cast<size_t>(got);
367,900✔
486
         }
487
      }
367,900✔
488

489
   private:
490
      socket_type m_socket;
491
};
492

493
#endif
494

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

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

514
   return combined;
2,107✔
515
}
×
516

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

531
      void parse_args(char* argv[]);
532

533
      bool flag_set(const std::string& flag) const {
118,046✔
534
         if(!m_flags.contains(flag)) {
118,046✔
535
            throw Shim_Exception("Unknown bool flag " + flag);
×
536
         }
537

538
         return m_parsed_flags.contains(flag);
118,046✔
539
      }
540

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

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

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

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

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

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

582
         return Botan::to_u32bit(get_opt(key));
894✔
583
      }
584

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

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

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

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

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

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

631
      const std::set<std::string> m_flags;
632
      const std::set<std::string> m_string_opts;
633
      const std::set<std::string> m_base64_opts;
634
      const std::set<std::string> m_int_opts;
635
      const std::set<std::string> m_int_vec_opts;
636
      const std::set<std::string> m_all_options;
637

638
      std::set<std::string> m_parsed_flags;
639
      std::map<std::string, std::string> m_parsed_opts;
640
      std::map<std::string, std::vector<size_t>> m_parsed_int_vec_opts;
641
};
642

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

646
   while(argv[i] != nullptr) {
20,246✔
647
      const std::string param(argv[i]);
18,139✔
648

649
      if(param.starts_with("-")) {
18,139✔
650
         const std::string flag_name = param.substr(1, std::string::npos);
18,139✔
651

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

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

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

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

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

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

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

858
   std::unique_ptr<Shim_Arguments> args(new Shim_Arguments(
2,107✔
859
      bogo_shim_flags, bogo_shim_string_opts, bogo_shim_base64_opts, bogo_shim_int_opts, bogo_shim_int_vec_opts));
2,107✔
860

861
   // may throw:
862
   args->parse_args(argv);
2,107✔
863

864
   return args;
2,107✔
865
}
8,428✔
866

867
class Shim_Policy final : public Botan::TLS::Policy {
2,697✔
868
   public:
869
      Shim_Policy(const Shim_Arguments& args) : m_args(args), m_sessions(0) {}
2,715✔
870

871
      void incr_session_established() { m_sessions += 1; }
2,025✔
872

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

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

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

914
         return Botan::concat(allowed_without_aes, allowed_just_aes);
211,481✔
915
      }
211,481✔
916

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

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

938
      //std::vector<std::string> allowed_macs() const override;
939

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

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

955
            return schemes;
93✔
956
         }
93✔
957

958
         return Botan::TLS::Policy::acceptable_signature_schemes();
1,721✔
959
      }
960

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

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

981
            return schemes;
133✔
982
         }
133✔
983

984
         return Botan::TLS::Policy::allowed_signature_schemes();
2,965✔
985
      }
986

987
      //size_t minimum_signature_strength() const override;
988

989
      bool require_cert_revocation_info() const override { return false; }
6✔
990

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

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

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

1006
            return groups;
493✔
1007
         }
493✔
1008

1009
         return Botan::TLS::Policy::key_exchange_groups();
6,884✔
1010
      }
1011

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

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

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

1028
         return Botan::TLS::Group_Params::NONE;
599✔
1029
      }
2,662✔
1030

1031
      bool require_client_certificate_authentication() const override {
538✔
1032
         return m_args.flag_set("require-any-client-certificate");
538✔
1033
      }
1034

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

1040
      bool allow_insecure_renegotiation() const override {
1,158✔
1041
         if(m_args.flag_set("expect-no-secure-renegotiation")) {
1,158✔
1042
            return true;
1043
         } else {
1044
            return false;
1,157✔
1045
         }
1046
      }
1047

1048
      //bool include_time_in_hello_random() const override;
1049

1050
      bool allow_client_initiated_renegotiation() const override {
40✔
1051
         if(m_args.flag_set("renegotiate-freely")) {
40✔
1052
            return true;
1053
         }
1054

1055
         if(m_args.flag_set("renegotiate-once") && m_sessions <= 1) {
16✔
1056
            return true;
1057
         }
1058

1059
         return false;
1060
      }
1061

1062
      bool allow_server_initiated_renegotiation() const override {
39✔
1063
         return allow_client_initiated_renegotiation();  // same logic
39✔
1064
      }
1065

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

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

1083
         return version.known_version();
18,458✔
1084
      }
1085

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

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

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

1101
      //Botan::TLS::Group_Params default_dh_group() const override;
1102

1103
      //size_t minimum_dh_group_size() const override;
1104

1105
      size_t minimum_ecdsa_group_size() const override { return 224; }
131✔
1106

1107
      size_t minimum_ecdh_group_size() const override { return 224; }
1,786✔
1108

1109
      //size_t minimum_rsa_bits() const override;
1110

1111
      //size_t minimum_dsa_group_size() const override;
1112

1113
      //void check_peer_key_acceptable(const Botan::Public_Key& public_key) const override;
1114

1115
      //bool hide_unknown_users() const override;
1116

1117
      //std::chrono::seconds session_ticket_lifetime() const override;
1118

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

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

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

1139
      bool only_resume_with_exact_version() const override { return false; }
198✔
1140

1141
      //bool server_uses_own_ciphersuite_preferences() const override;
1142

1143
      //bool negotiate_encrypt_then_mac() const override;
1144

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

1157
         return true;
1158
      }
1159

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

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

1164
      //size_t dtls_initial_timeout() const override;
1165

1166
      //size_t dtls_maximum_timeout() const override;
1167

1168
      bool abort_connection_on_undesired_renegotiation() const override {
6✔
1169
         if(m_args.flag_set("renegotiate-ignore")) {
6✔
1170
            return false;
1171
         } else {
1172
            return true;
5✔
1173
         }
1174
      }
1175

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

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

1196
         return true;
1197
      }
2,728✔
1198

1199
   private:
1200
      const Shim_Arguments& m_args;
1201
      size_t m_sessions;
1202
};
1203

1204
std::vector<uint16_t> Shim_Policy::ciphersuite_list(Botan::TLS::Protocol_Version version) const {
3,456✔
1205
   std::vector<uint16_t> ciphersuite_codes;
3,456✔
1206

1207
   const std::string cipher_limit = m_args.get_string_opt_or_else("cipher", "");
6,912✔
1208
   if(cipher_limit ==
3,456✔
1209
      "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]") {
1210
      std::vector<std::string> suites = {
5✔
1211
         "ECDHE_RSA_WITH_AES_128_GCM_SHA256",
1212
         "ECDHE_RSA_WITH_AES_256_GCM_SHA384",
1213
         "ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
1214
         "ECDHE_RSA_WITH_AES_256_CBC_SHA",
1215
         "RSA_WITH_AES_256_GCM_SHA384",
1216
         "RSA_WITH_AES_256_CBC_SHA",
1217
      };
5✔
1218

1219
      for(const auto& suite_name : suites) {
35✔
1220
         const auto suite = Botan::TLS::Ciphersuite::from_name(suite_name);
30✔
1221
         if(!suite || !suite->valid()) {
30✔
1222
            shim_exit_with_error("Bad ciphersuite name " + suite_name);
×
1223
         }
1224
         ciphersuite_codes.push_back(suite->ciphersuite_code());
30✔
1225
      }
1226
   } else {
5✔
1227
      // Hack: go in reverse order to avoid preferring 3DES
1228
      auto ciphersuites = Botan::TLS::Ciphersuite::all_known_ciphersuites();
3,451✔
1229
      for(auto i = ciphersuites.rbegin(); i != ciphersuites.rend(); ++i) {
355,453✔
1230
         const auto suite = *i;
352,002✔
1231

1232
         // Can we use it?
1233
         if(suite.valid() == false || !suite.usable_in_version(version) ||
352,002✔
1234
            !Botan::value_exists(allowed_ciphers(), suite.cipher_algo())) {
593,658✔
1235
            continue;
171,092✔
1236
         }
1237

1238
         ciphersuite_codes.push_back(suite.ciphersuite_code());
180,910✔
1239
      }
1240
   }
3,451✔
1241

1242
   return ciphersuite_codes;
3,456✔
1243
}
3,456✔
1244

1245
class Shim_Credentials final : public Botan::Credentials_Manager {
1246
   public:
1247
      Shim_Credentials(const Shim_Arguments& args) : m_args(args) {
2,106✔
1248
         const auto psk_identity = m_args.get_string_opt_or_else("psk-identity", "");
4,212✔
1249
         const auto psk_str = m_args.get_string_opt_or_else("psk", "");
4,212✔
1250

1251
         if(!psk_identity.empty() || !psk_str.empty()) {
2,106✔
1252
            // If the shim received a -psk param but no -psk-identity param,
1253
            // we have to initialize the identity as "empty string".
1254
            m_psk_identity = psk_identity;
77✔
1255
         }
1256

1257
         if(!psk_str.empty()) {
2,106✔
1258
            m_psk = Botan::SymmetricKey(reinterpret_cast<const uint8_t*>(psk_str.data()), psk_str.size());
77✔
1259
         }
1260

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

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

1267
            while(!cert_stream.end_of_data()) {
3,040✔
1268
               try {
2,028✔
1269
                  m_cert_chain.push_back(Botan::X509_Certificate(cert_stream));
3,044✔
1270
               } catch(...) {}
1,012✔
1271
            }
1272
         }
1,012✔
1273

1274
         if(m_args.option_used("trust-cert") && !m_args.get_string_opt("trust-cert").empty()) {
5,092✔
1275
            Botan::DataSource_Stream cert_stream(m_args.get_string_opt("trust-cert"));
2,974✔
1276
            try {
1,487✔
1277
               m_trust_roots.add_certificate(Botan::X509_Certificate(cert_stream));
1,487✔
1278
            } catch(const std::exception& ex) {
×
1279
               throw Shim_Exception("Failed to load trusted root certificate: " + std::string(ex.what()));
×
1280
            }
×
1281
         }
1,487✔
1282
      }
2,106✔
1283

1284
      std::vector<Botan::Certificate_Store*> trusted_certificate_authorities(const std::string& type,
2,084✔
1285
                                                                             const std::string& context) override {
1286
         if(m_args.flag_set("server") && type != "tls-server") {
4,168✔
1287
            throw Shim_Exception("TLS server implementation asked for unexpected trusted CA type: " + type);
×
1288
         }
1289
         if(!m_args.flag_set("server") && type != "tls-client") {
4,168✔
1290
            throw Shim_Exception("TLS client implementation asked for unexpected trusted CA type: " + type);
×
1291
         }
1292

1293
         const auto expected_hostname = m_args.get_string_opt_or_else("host-name", "none");
4,168✔
1294
         if(expected_hostname != "none" && expected_hostname != context) {
2,084✔
1295
            throw Shim_Exception("Unexpected host name in trusted CA request: " + context);
×
1296
         }
1297

1298
         return {&m_trust_roots};
2,084✔
1299
      }
2,084✔
1300

1301
      std::string psk_identity(const std::string& /*type*/,
48✔
1302
                               const std::string& /*context*/,
1303
                               const std::string& /*identity_hint*/) override {
1304
         return m_psk_identity.value_or("");
48✔
1305
      }
1306

1307
      std::string psk_identity_hint(const std::string& /*type*/, const std::string& /*context*/) override {
27✔
1308
         return m_psk_identity.value_or("");
27✔
1309
      }
1310

1311
      Botan::secure_vector<uint8_t> session_ticket_key() override {
1,764✔
1312
         return Botan::hex_decode_locked("ABCDEF0123456789");
1,764✔
1313
      }
1314

1315
      Botan::secure_vector<uint8_t> dtls_cookie_secret() override {
658✔
1316
         return Botan::hex_decode_locked("F00FB00FD00F100F700F");
658✔
1317
      }
1318

1319
      std::vector<Botan::TLS::ExternalPSK> find_preshared_keys(
1,029✔
1320
         std::string_view host,
1321
         Botan::TLS::Connection_Side whoami,
1322
         const std::vector<std::string>& identities = {},
1323
         const std::optional<std::string>& prf = std::nullopt) override {
1324
         if(!m_psk_identity.has_value()) {
1,029✔
1325
            return Botan::Credentials_Manager::find_preshared_keys(host, whoami, identities, prf);
927✔
1326
         }
1327

1328
         auto id_matches =
102✔
1329
            identities.empty() || std::find(identities.begin(), identities.end(), m_psk_identity) != identities.end();
102✔
1330

1331
         if(!id_matches) {
102✔
1332
            throw Shim_Exception("Unexpected PSK identity");
×
1333
         }
1334

1335
         if(!m_psk.has_value()) {
102✔
1336
            throw Shim_Exception("PSK identified but not set");
×
1337
         }
1338

1339
         std::vector<Botan::TLS::ExternalPSK> psks;
102✔
1340

1341
         // Currently, BoGo tests PSK with TLS 1.2 only. In TLS 1.2 the PRF does not
1342
         // need to be specified for PSKs.
1343
         //
1344
         // TODO: Once BoGo has tests for TLS 1.3 with externally provided PSKs, this
1345
         //       will need to be handled somehow.
1346
         const std::string psk_prf = "SHA-256";
102✔
1347
         psks.emplace_back(m_psk_identity.value(), psk_prf, m_psk->bits_of());
102✔
1348
         return psks;
102✔
1349
      }
102✔
1350

1351
      std::vector<Botan::X509_Certificate> cert_chain(
2,265✔
1352
         const std::vector<std::string>& cert_key_types,
1353
         const std::vector<Botan::AlgorithmIdentifier>& /*cert_signature_schemes*/,
1354
         const std::string& /*type*/,
1355
         const std::string& /*context*/) override {
1356
         if(m_args.flag_set("fail-cert-callback")) {
2,265✔
1357
            throw std::runtime_error("Simulating cert verify callback failure");
4✔
1358
         }
1359

1360
         if(m_key != nullptr && !m_cert_chain.empty()) {
2,261✔
1361
            for(const std::string& t : cert_key_types) {
3,298✔
1362
               if(t == m_key->algo_name()) {
2,161✔
1363
                  return m_cert_chain;
2,261✔
1364
               }
1365
            }
1366
         }
1367

1368
         return {};
1,320✔
1369
      }
1370

1371
      std::shared_ptr<Botan::Private_Key> private_key_for(const Botan::X509_Certificate& /*cert*/,
897✔
1372
                                                          const std::string& /*type*/,
1373
                                                          const std::string& /*context*/) override {
1374
         // assumes cert == m_cert
1375
         return m_key;
897✔
1376
      }
1377

1378
   private:
1379
      const Shim_Arguments& m_args;
1380
      std::optional<Botan::SymmetricKey> m_psk;
1381
      std::optional<std::string> m_psk_identity;
1382
      std::shared_ptr<Botan::Private_Key> m_key;
1383
      std::vector<Botan::X509_Certificate> m_cert_chain;
1384
      Botan::Certificate_Store_In_Memory m_trust_roots;
1385
};
1386

1387
class Shim_Callbacks final : public Botan::TLS::Callbacks {
2,697✔
1388
   public:
1389
      Shim_Callbacks(const Shim_Arguments& args, Shim_Socket& socket, Shim_Policy& policy) :
2,715✔
1390
            m_channel(nullptr),
2,715✔
1391
            m_args(args),
2,715✔
1392
            m_policy(policy),
2,715✔
1393
            m_socket(socket),
2,715✔
1394
            m_is_datagram(args.flag_set("dtls")),
2,715✔
1395
            m_warning_alerts(0),
2,715✔
1396
            m_empty_records(0),
2,715✔
1397
            m_sessions_established(0),
2,715✔
1398
            m_got_close(false),
2,715✔
1399
            m_hello_retry_request(false),
2,715✔
1400
            m_clock_skew(0) {}
5,430✔
1401

1402
      size_t sessions_established() const { return m_sessions_established; }
21✔
1403

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

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

1408
      bool saw_close_notify() const { return m_got_close; }
27✔
1409

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

1413
         if(m_args.option_used("write-settings")) {
16,341✔
1414
            // TODO: the transcript option should probably be used differently
1415
            std::cout << ">>>" << std::endl << Botan::hex_encode(data) << std::endl << ">>>" << std::endl;
×
1416
         }
1417

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

1421
            packet[0] = 'P';
6,030✔
1422
            for(size_t i = 0; i != 4; ++i) {
30,150✔
1423
               packet[i + 1] = static_cast<uint8_t>((data.size() >> (24 - 8 * i)) & 0xFF);
24,120✔
1424
            }
1425
            std::memcpy(packet.data() + 5, data.data(), data.size());
6,030✔
1426

1427
            m_socket.write(packet.data(), packet.size());
6,030✔
1428
         } else {
6,030✔
1429
            m_socket.write(data.data(), data.size());
10,311✔
1430
         }
1431
      }
16,341✔
1432

1433
      std::vector<uint8_t> tls_provide_cert_status(const std::vector<Botan::X509_Certificate>&,
794✔
1434
                                                   const Botan::TLS::Certificate_Status_Request&) override {
1435
         if(m_args.flag_set("use-ocsp-callback") && m_args.flag_set("fail-ocsp-callback")) {
874✔
1436
            throw std::runtime_error("Simulating failure from OCSP response callback");
32✔
1437
         }
1438

1439
         if(m_args.flag_set("decline-ocsp-callback")) {
762✔
1440
            return {};
24✔
1441
         }
1442

1443
         if(m_args.option_used("ocsp-response")) {
738✔
1444
            return m_args.get_b64_opt("ocsp-response");
96✔
1445
         }
1446

1447
         return {};
690✔
1448
      }
1449

1450
      void tls_record_received(uint64_t /*seq_no*/, std::span<const uint8_t> data) override {
2,352✔
1451
         if(data.empty()) {
2,352✔
1452
            m_empty_records += 1;
98✔
1453
            if(m_empty_records > 32) {
98✔
1454
               shim_exit_with_error(":TOO_MANY_EMPTY_FRAGMENTS:");
2✔
1455
            }
1456
         } else {
1457
            m_empty_records = 0;
2,254✔
1458
         }
1459

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

1462
         std::vector<uint8_t> buf(data.begin(), data.end());
2,350✔
1463
         for(auto& b : buf) {
1,178,137✔
1464
            b ^= 0xFF;
1,175,787✔
1465
         }
1466

1467
         m_channel->send(buf);
2,350✔
1468
      }
2,350✔
1469

1470
      bool tls_verify_message(const Botan::Public_Key& key,
1,094✔
1471
                              std::string_view padding,
1472
                              Botan::Signature_Format format,
1473
                              const std::vector<uint8_t>& msg,
1474
                              const std::vector<uint8_t>& sig) override {
1475
         if(m_args.option_used("expect-peer-signature-algorithm")) {
1,094✔
1476
            const Botan::TLS::Signature_Scheme scheme(
65✔
1477
               static_cast<uint16_t>(m_args.get_int_opt("expect-peer-signature-algorithm")));
65✔
1478

1479
            if(!scheme.is_available()) {
65✔
1480
               shim_exit_with_error(std::string("Unsupported signature scheme provided by BoGo: ") +
×
1481
                                    scheme.to_string());
×
1482
            }
1483

1484
            const std::string exp_padding = scheme.padding_string();
65✔
1485
            if(padding != exp_padding) {
130✔
1486
               shim_exit_with_error(Botan::fmt("Unexpected signature scheme got {} expected {}", padding, exp_padding));
×
1487
            }
1488
         }
65✔
1489

1490
         return Botan::TLS::Callbacks::tls_verify_message(key, padding, format, msg, sig);
1,094✔
1491
      }
1492

1493
      void tls_verify_cert_chain(const std::vector<Botan::X509_Certificate>& cert_chain,
1,278✔
1494
                                 const std::vector<std::optional<Botan::OCSP::Response>>& ocsp_responses,
1495
                                 const std::vector<Botan::Certificate_Store*>& trusted_roots,
1496
                                 Botan::Usage_Type usage,
1497
                                 std::string_view /* hostname */,
1498
                                 const Botan::TLS::Policy& policy) override {
1499
         if(m_args.flag_set("enable-ocsp-stapling") && m_args.flag_set("use-ocsp-callback") &&
2,679✔
1500
            m_args.flag_set("fail-ocsp-callback")) {
1,374✔
1501
            throw Botan::TLS::TLS_Exception(Botan::TLS::Alert::BadCertificateStatusResponse,
64✔
1502
                                            "Simulated OCSP callback failure");
64✔
1503
         }
1504

1505
         if(m_args.flag_set("verify-fail")) {
1,214✔
1506
            auto alert = Botan::TLS::Alert::HandshakeFailure;
128✔
1507
            if(m_args.flag_set("use-custom-verify-callback")) {
128✔
1508
               alert = Botan::TLS::Alert::CertificateUnknown;
64✔
1509
            }
1510

1511
            throw Botan::TLS::TLS_Exception(alert, "Test requires rejecting cert");
128✔
1512
         }
1513

1514
         if(!cert_chain.empty() && cert_chain.front().is_self_signed()) {
1,086✔
1515
            for(const auto roots : trusted_roots) {
1,080✔
1516
               if(roots->certificate_known(cert_chain.front())) {
1,080✔
1517
                  shim_log("Trusting self-signed certificate");
1,080✔
1518
                  return;
1,080✔
1519
               }
1520
            }
1521
         }
1522

1523
         shim_log("Establishing trust from a certificate chain");
6✔
1524

1525
         Botan::TLS::Callbacks::tls_verify_cert_chain(
6✔
1526
            cert_chain, ocsp_responses, trusted_roots, usage, "" /* hostname */, policy);
1527
      }
1528

1529
      std::optional<Botan::OCSP::Response> tls_parse_ocsp_response(const std::vector<uint8_t>& raw_response) override {
89✔
1530
         if(m_args.option_used("expect-ocsp-response") && m_args.get_b64_opt("expect-ocsp-response") != raw_response) {
164✔
1531
            shim_exit_with_error("unexpected OCSP response");
×
1532
         }
1533

1534
         // Bogo uses invalid dummy OCSP responses. Don't even bother trying to
1535
         // decode them.
1536
         return std::nullopt;
89✔
1537
      }
1538

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

1562
      std::string tls_server_choose_app_protocol(const std::vector<std::string>& client_protos) override {
21✔
1563
         if(client_protos.empty()) {
21✔
1564
            return "";  // shouldn't happen?
×
1565
         }
1566

1567
         if(m_args.flag_set("reject-alpn")) {
21✔
1568
            throw Botan::TLS::TLS_Exception(Botan::TLS::Alert::NoApplicationProtocol,
3✔
1569
                                            "Rejecting ALPN request with alert");
3✔
1570
         }
1571

1572
         if(m_args.flag_set("decline-alpn")) {
18✔
1573
            return "";
6✔
1574
         }
1575

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

1579
            if(client_protos != expected) {
12✔
1580
               shim_exit_with_error("Bad ALPN from client");
×
1581
            }
1582
         }
12✔
1583

1584
         if(m_args.option_used("select-alpn")) {
12✔
1585
            return m_args.get_string_opt("select-alpn");
24✔
1586
         }
1587

1588
         return client_protos[0];  // if not configured just pick something
×
1589
      }
1590

1591
      void tls_alert(Botan::TLS::Alert alert) override {
1,911✔
1592
         if(alert.is_fatal()) {
1,911✔
1593
            shim_log("Got a fatal alert " + alert.type_string());
39✔
1594
         } else {
1595
            shim_log("Got a warning alert " + alert.type_string());
5,694✔
1596
         }
1597

1598
         if(alert.type() == Botan::TLS::Alert::RecordOverflow) {
1,911✔
1599
            shim_exit_with_error(":TLSV1_ALERT_RECORD_OVERFLOW:");
4✔
1600
         }
1601

1602
         if(alert.type() == Botan::TLS::Alert::DecompressionFailure) {
1,907✔
1603
            shim_exit_with_error(":SSLV3_ALERT_DECOMPRESSION_FAILURE:");
1✔
1604
         }
1605

1606
         if(!alert.is_fatal()) {
1,906✔
1607
            m_warning_alerts++;
1,898✔
1608
            if(m_warning_alerts > 5) {
1,898✔
1609
               shim_exit_with_error(":TOO_MANY_WARNING_ALERTS:");
3✔
1610
            }
1611
         }
1612

1613
         if(alert.type() == Botan::TLS::Alert::CloseNotify) {
1,903✔
1614
            if(m_got_close == false && !m_args.flag_set("shim-shuts-down")) {
3,750✔
1615
               shim_log("Sending return close notify");
1,848✔
1616
               m_channel->send_alert(alert);
1,848✔
1617
            }
1618
            m_got_close = true;
1,866✔
1619
         } else if(alert.is_fatal()) {
37✔
1620
            shim_exit_with_error("Unexpected fatal alert " + alert.type_string());
16✔
1621
         }
1622
      }
1,895✔
1623

1624
      void tls_session_established(const Botan::TLS::Session_Summary& session) override {
2,025✔
1625
         shim_log("Session established: " + Botan::hex_encode(session.session_id().get()) + " version " +
10,125✔
1626
                  session.version().to_string() + " cipher " + session.ciphersuite().to_string() + " EMS " +
12,150✔
1627
                  std::to_string(session.supports_extended_master_secret()));
2,025✔
1628
         // probably need tests here?
1629

1630
         m_policy.incr_session_established();
2,025✔
1631
         m_sessions_established++;
2,025✔
1632

1633
         if(m_args.flag_set("expect-no-session-id")) {
2,025✔
1634
            // BoGo expects that ticket issuance implies no stateful session...
1635
            if(!m_args.flag_set("server") && !session.session_id().empty()) {
112✔
1636
               shim_exit_with_error("Unexpectedly got a session ID");
×
1637
            }
1638
         } else if(m_args.flag_set("expect-session-id") && session.session_id().empty()) {
3,938✔
1639
            shim_exit_with_error("Unexpectedly got no session ID");
×
1640
         }
1641

1642
         if(m_args.option_used("expect-version")) {
2,025✔
1643
            if(session.version().version_code() != m_args.get_int_opt("expect-version")) {
×
1644
               shim_exit_with_error("Unexpected version");
×
1645
            }
1646
         }
1647

1648
         if(m_args.flag_set("expect-secure-renegotiation")) {
2,025✔
1649
            if(m_channel->secure_renegotiation_supported() == false) {
9✔
1650
               shim_exit_with_error("Expected secure renegotiation");
×
1651
            }
1652
         } else if(m_args.flag_set("expect-no-secure-renegotiation")) {
2,016✔
1653
            if(m_channel->secure_renegotiation_supported() == true) {
2✔
1654
               shim_exit_with_error("Expected no secure renegotation");
×
1655
            }
1656
         }
1657

1658
         if(m_args.flag_set("expect-extended-master-secret")) {
2,025✔
1659
            if(session.supports_extended_master_secret() == false) {
10✔
1660
               shim_exit_with_error("Expected extended maseter secret");
×
1661
            }
1662
         }
1663
      }
2,025✔
1664

1665
      void tls_session_activated() override {
2,012✔
1666
         if(m_args.flag_set("send-alert")) {
2,012✔
1667
            m_channel->send_fatal_alert(Botan::TLS::Alert::DecompressionFailure);
16✔
1668
            return;
16✔
1669
         }
1670

1671
         if(size_t length = m_args.get_int_opt_or_else("export-keying-material", 0)) {
1,996✔
1672
            const std::string label = m_args.get_string_opt("export-label");
176✔
1673
            const std::string context = m_args.get_string_opt("export-context");
176✔
1674
            const auto exported = m_channel->key_material_export(label, context, length);
176✔
1675
            shim_log("Sending " + std::to_string(length) + " bytes of key material");
704✔
1676
            m_channel->send(exported.bits_of());
352✔
1677
         }
176✔
1678

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

1681
         if(m_args.option_used("expect-alpn")) {
1,996✔
1682
            if(alpn != m_args.get_string_opt("expect-alpn")) {
10✔
1683
               shim_exit_with_error("Got unexpected ALPN");
×
1684
            }
1685
         }
1686

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

1691
         if(m_args.flag_set("shim-shuts-down")) {
1,993✔
1692
            shim_log("Shim shutting down");
45✔
1693
            m_channel->close();
45✔
1694
         }
1695

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

1699
            std::vector<uint8_t> buf(32769, 0x42);
×
1700

1701
            for(size_t sz : record_sizes) {
×
1702
               m_channel->send(buf.data(), sz);
×
1703
            }
1704

1705
            m_channel->close();
×
1706
         }
×
1707

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

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

1716
         if(m_args.flag_set("key-update")) {
1,993✔
1717
            shim_log("Updating traffic keys without asking for reciprocation");
5✔
1718
            m_channel->update_traffic_keys(false /* don't request reciprocal update */);
2✔
1719
         }
1720
      }
1,993✔
1721

1722
      std::chrono::system_clock::time_point tls_current_timestamp() override {
8,910✔
1723
         // Some tests require precise timings. Hence, the TLS 'now' timestamp
1724
         // is frozen on first access and rounded to the last full second. E.g.
1725
         // storage of sessions does store the timestamp with second-resolution.
1726
         using sec = std::chrono::seconds;
8,910✔
1727
         static auto g_now = std::chrono::floor<sec>(std::chrono::system_clock::now());
8,910✔
1728
         return g_now + m_clock_skew;
8,910✔
1729
      }
1730

1731
      void tls_inspect_handshake_msg(const Botan::TLS::Handshake_Message& msg) override {
21,458✔
1732
         if(msg.type() == Botan::TLS::Handshake_Type::HelloRetryRequest) {
21,458✔
1733
            m_hello_retry_request = true;
82✔
1734
         }
1735
      }
21,458✔
1736

1737
   private:
1738
      Botan::TLS::Channel* m_channel;
1739
      const Shim_Arguments& m_args;
1740
      Shim_Policy& m_policy;
1741
      Shim_Socket& m_socket;
1742
      const bool m_is_datagram;
1743
      size_t m_warning_alerts;
1744
      size_t m_empty_records;
1745
      size_t m_sessions_established;
1746
      bool m_got_close;
1747
      bool m_hello_retry_request;
1748
      std::chrono::seconds m_clock_skew;
1749
};
1750

1751
}  // namespace
1752

1753
int main(int /*argc*/, char* argv[]) {
2,107✔
1754
   try {
2,107✔
1755
      std::unique_ptr<Shim_Arguments> args = parse_options(argv);
2,107✔
1756

1757
      if(args->flag_set("is-handshaker-supported")) {
2,107✔
1758
         return shim_output("No\n");
1✔
1759
      }
1760

1761
      const uint16_t port = static_cast<uint16_t>(args->get_int_opt("port"));
2,106✔
1762
      const size_t resume_count = args->get_int_opt_or_else("resume-count", 0);
2,106✔
1763
      const bool is_server = args->flag_set("server");
2,106✔
1764
      const bool is_datagram = args->flag_set("dtls");
2,106✔
1765
      const size_t buf_size = args->get_int_opt_or_else("read-size", 18 * 1024);
2,106✔
1766

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

1783
      if(args->flag_set("wait-for-debugger")) {
2,911✔
1784
         sleep(20);
×
1785
      }
1786

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

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

1793
            // The ShimID must be written on the socket as a 64-bit little-endian integer
1794
            // *before* any test data is transferred
1795
            // See: https://github.com/google/boringssl/commit/50ee09552cde1c2019bef24520848d041920cfd4
1796
            shim_log("Sending ShimID: " + std::to_string(args->get_int_opt("shim-id")));
8,145✔
1797
            std::array<uint8_t, 8> shim_id;
2,715✔
1798
            Botan::store_le(static_cast<uint64_t>(args->get_int_opt("shim-id")), shim_id.data());
3,520✔
1799
            socket.write(shim_id.data(), shim_id.size());
2,715✔
1800

1801
            auto policy = std::make_shared<Shim_Policy>(*args);
2,715✔
1802
            auto callbacks = std::make_shared<Shim_Callbacks>(*args, socket, *policy);
2,715✔
1803

1804
            if(args->option_used("resumption-delay") && i > 0) {
5,430✔
1805
               shim_log("skewing the clock by " + std::to_string(args->get_int_opt("resumption-delay")) + " seconds");
12✔
1806
               callbacks->set_clock_skew(std::chrono::seconds(args->get_int_opt("resumption-delay")));
808✔
1807
            }
1808

1809
            std::unique_ptr<Botan::TLS::Channel> chan;
2,715✔
1810

1811
            if(is_server) {
2,715✔
1812
               chan = std::make_unique<Botan::TLS::Server>(callbacks, session_manager, creds, policy, rng, is_datagram);
1,222✔
1813
            } else {
1814
               Botan::TLS::Protocol_Version offer_version = policy->latest_supported_version(is_datagram);
1,493✔
1815
               shim_log("Offering " + offer_version.to_string());
4,473✔
1816

1817
               std::string host_name = args->get_string_opt_or_else("host-name", hostname);
1,491✔
1818
               if(args->test_name().starts_with("UnsolicitedServerNameAck")) {
2,982✔
1819
                  host_name = "";  // avoid sending SNI for this test
3✔
1820
               }
1821

1822
               Botan::TLS::Server_Information server_info(host_name, port);
1,491✔
1823
               const std::vector<std::string> next_protocols = args->get_alpn_string_vec_opt("advertise-alpn");
1,491✔
1824
               chan = std::make_unique<Botan::TLS::Client>(
1,491✔
1825
                  callbacks, session_manager, creds, policy, rng, server_info, offer_version, next_protocols);
1,491✔
1826
            }
2,982✔
1827

1828
            callbacks->set_channel(chan.get());
2,713✔
1829

1830
            std::vector<uint8_t> buf(buf_size);
3,518✔
1831

1832
            for(;;) {
203,713✔
1833
               if(is_datagram) {
203,713✔
1834
                  uint8_t opcode;
184,528✔
1835
                  size_t got = socket.read(&opcode, 1);
184,528✔
1836
                  if(got == 0) {
184,528✔
1837
                     shim_log("EOF on socket");
578✔
1838
                     break;
578✔
1839
                  }
1840

1841
                  if(opcode == 'P') {
183,950✔
1842
                     uint8_t len_bytes[4];
183,950✔
1843
                     socket.read_exactly(len_bytes, sizeof(len_bytes));
183,950✔
1844

1845
                     size_t packet_len = Botan::load_be<uint32_t>(len_bytes, 0);
183,950✔
1846

1847
                     if(buf.size() < packet_len) {
183,950✔
1848
                        buf.resize(packet_len);
1✔
1849
                     }
1850
                     socket.read_exactly(buf.data(), packet_len);
183,950✔
1851

1852
                     chan->received_data(buf.data(), packet_len);
183,950✔
1853
                  } else if(opcode == 'T') {
×
1854
                     uint8_t timeout_ack = 't';
×
1855

1856
                     uint8_t timeout_bytes[8];
×
1857
                     socket.read_exactly(timeout_bytes, sizeof(timeout_bytes));
×
1858

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

1861
                     shim_log("Timeout nsec " + std::to_string(nsec));
×
1862

1863
                     // FIXME handle this!
1864

1865
                     socket.write(&timeout_ack, 1);  // ack it anyway
×
1866
                  } else {
1867
                     shim_exit_with_error("Unknown opcode " + std::to_string(opcode));
×
1868
                  }
1869
               } else {
1870
                  size_t got = socket.read(buf.data(), buf.size());
19,185✔
1871
                  if(got == 0) {
19,185✔
1872
                     shim_log("EOF on socket");
1,315✔
1873
                     break;
1,315✔
1874
                  }
1875

1876
                  shim_log("Got packet of " + std::to_string(got));
53,610✔
1877

1878
                  if(args->option_used("write-settings")) {
17,870✔
1879
                     // TODO: the transcript option should probably be used differently
1880
                     std::cout << "<<<" << std::endl
×
1881
                               << Botan::hex_encode(buf.data(), got) << std::endl
×
1882
                               << "<<<" << std::endl;
×
1883
                  }
1884

1885
                  if(args->flag_set("use-exporter-between-reads") && chan->is_active()) {
35,740✔
1886
                     chan->key_material_export("some label", "some context", 42);
1✔
1887
                  }
1888
                  const size_t needed = chan->received_data(buf.data(), got);
17,869✔
1889

1890
                  if(needed) {
17,226✔
1891
                     shim_log("Short read still need " + std::to_string(needed));
32,169✔
1892
                  }
1893
               }
1894
            }
1895

1896
            if(args->flag_set("check-close-notify")) {
1,893✔
1897
               if(!callbacks->saw_close_notify()) {
27✔
1898
                  throw Shim_Exception("Unexpected SSL_shutdown result: -1 != 1");
1✔
1899
               }
1900
            }
1901

1902
            if(args->option_used("expect-total-renegotiations")) {
1,892✔
1903
               const size_t exp = args->get_int_opt("expect-total-renegotiations");
21✔
1904

1905
               if(exp != callbacks->sessions_established() - 1) {
21✔
1906
                  throw Shim_Exception("Unexpected number of renegotiations: saw " +
×
1907
                                       std::to_string(callbacks->sessions_established() - 1) + " exp " +
×
1908
                                       std::to_string(exp));
×
1909
               }
1910
            }
1911
            shim_log("End of resume loop");
4,587✔
1912
         };
10,786✔
1913
         try {
2,715✔
1914
            execute_test("localhost");
5,412✔
1915
         } catch(const Shim_Exception& e) {
805✔
1916
            if(std::string(e.what()) == "Failed to connect to host") {
1✔
1917
               execute_test("::1");
×
1918
            } else {
1919
               // NOLINTNEXTLINE(cert-err60-cpp)
1920
               throw e;
1✔
1921
            }
1922
         }
1✔
1923
      }
1924
   } catch(Shim_Exception& e) {
7,070✔
1925
      shim_exit_with_error(e.what(), e.rc());
1✔
1926
   } catch(std::exception& e) {
804✔
1927
      shim_exit_with_error(map_to_bogo_error(e.what()));
804✔
1928
   } catch(...) {
×
1929
      shim_exit_with_error("Unknown exception", 3);
×
1930
   }
×
1931
   return 0;
1,283✔
1932
}
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

© 2025 Coveralls, Inc