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

randombit / botan / 10861438717

09 Sep 2024 08:10AM UTC coverage: 91.28% (+0.003%) from 91.277%
10861438717

push

github

web-flow
Merge pull request #4335 from Rohde-Schwarz/fix/context_visibility

Fix TLS::Context Visibility

87856 of 96249 relevant lines covered (91.28%)

9147770.11 hits per line

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

87.79
/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

32
#include <ctime>
33
#include <iostream>
34
#include <map>
35
#include <memory>
36
#include <set>
37
#include <string>
38
#include <unordered_map>
39
#include <vector>
40

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

52
namespace {
53

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

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

68
      // NOLINTNEXTLINE(*-avoid-non-const-global-variables)
69
      static FILE* g_log = std::fopen("/tmp/bogo_shim.log", "w");
×
70
      struct timeval tv;
×
71
      ::gettimeofday(&tv, nullptr);
×
72
      static_cast<void>(std::fprintf(g_log,
×
73
                                     "%lld.%lu: %s\n",
74
                                     static_cast<unsigned long long>(tv.tv_sec),
×
75
                                     static_cast<unsigned long>(tv.tv_usec),
×
76
                                     s.c_str()));
77
      static_cast<void>(std::fflush(g_log));
×
78
   }
79
}
78,642✔
80

81
[[noreturn]] void shim_exit_with_error(const std::string& s, int rc = 1) {
753✔
82
   shim_log("Exiting with " + s);
753✔
83
   std::cerr << s << "\n";
753✔
84
   std::exit(rc);
753✔
85
}
86

87
std::string map_to_bogo_error(const std::string& e) {
734✔
88
   shim_log("Original error " + e);
734✔
89

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

328
   auto err_map_i = err_map.find(e);
734✔
329
   if(err_map_i != err_map.end()) {
734✔
330
      return err_map_i->second;
1,464✔
331
   }
332

333
   return "Unmapped error: '" + e + "'";
8✔
334
}
734✔
335

336
class Shim_Exception final : public std::exception {
337
   public:
338
      Shim_Exception(std::string_view msg, int rc = 1) : m_msg(msg), m_rc(rc) {}
2✔
339

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

342
      int rc() const { return m_rc; }
1✔
343

344
   private:
345
      const std::string m_msg;
346
      int m_rc;
347
};
348

349
#if defined(BOTAN_TARGET_OS_HAS_SOCKETS)
350

351
class Shim_Socket final {
352
   private:
353
      typedef int socket_type;
354
      typedef ssize_t socket_op_ret_type;
355

356
      static void close_socket(socket_type s) { ::close(s); }
357

358
      static std::string get_last_socket_error() { return ::strerror(errno); }
359

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

362
   public:
363
      Shim_Socket(const std::string& hostname, int port, const bool ipv6) : m_socket(-1) {
2,609✔
364
         addrinfo hints;
2,609✔
365
         std::memset(&hints, 0, sizeof(hints));
2,609✔
366
         hints.ai_family = AF_UNSPEC;
2,609✔
367
         hints.ai_socktype = SOCK_STREAM;
2,609✔
368
         hints.ai_flags = AI_NUMERICSERV;
2,609✔
369

370
         const std::string service = std::to_string(port);
2,609✔
371

372
         // TODO: C++23 will introduce std::out_ptr() that should replace the
373
         //       temporary variable for the call to ::getaddrinfo() and
374
         //       std::unique_ptr<>::reset().
375
         unique_addrinfo_t::pointer res_tmp;
2,609✔
376
         int rc = ::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res_tmp);
2,609✔
377
         unique_addrinfo_t res(res_tmp, &::freeaddrinfo);
2,609✔
378

379
         shim_log("Connecting " + hostname + ":" + service);
10,436✔
380

381
         if(rc != 0) {
2,609✔
382
            throw Shim_Exception("Name resolution failed for " + hostname);
×
383
         }
384

385
         for(addrinfo* rp = res.get(); (m_socket == -1) && (rp != nullptr); rp = rp->ai_next) {
5,218✔
386
            if((!ipv6 && rp->ai_family != AF_INET) || (ipv6 && rp->ai_family != AF_INET6)) {
2,609✔
387
               continue;
×
388
            }
389

390
            m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
2,609✔
391

392
            if(m_socket == -1) {
2,609✔
393
               // unsupported socket type?
394
               continue;
×
395
            }
396

397
            int err = ::connect(m_socket, rp->ai_addr, rp->ai_addrlen);
2,609✔
398

399
            if(err != 0) {
2,609✔
400
               ::close(m_socket);
×
401
               m_socket = -1;
×
402
            }
403
         }
404

405
         if(m_socket < 0) {
2,609✔
406
            throw Shim_Exception("Failed to connect to host");
×
407
         }
408
      }
2,609✔
409

410
      Shim_Socket(const Shim_Socket&) = delete;
411
      Shim_Socket& operator=(const Shim_Socket&) = delete;
412

413
      Shim_Socket(Shim_Socket&&) = delete;
414
      Shim_Socket& operator=(Shim_Socket&&) = delete;
415

416
      ~Shim_Socket() {
2,591✔
417
         ::close(m_socket);
2,591✔
418
         m_socket = -1;
2,591✔
419
      }
2,591✔
420

421
      void write(const uint8_t buf[], size_t len) const {
18,315✔
422
         if(m_socket < 0) {
18,315✔
423
            throw Shim_Exception("Socket was bad on write");
×
424
         }
425
         size_t sent_so_far = 0;
426
         while(sent_so_far != len) {
36,622✔
427
            const size_t left = len - sent_so_far;
18,315✔
428
            socket_op_ret_type sent =
18,315✔
429
               ::send(m_socket, Botan::cast_uint8_ptr_to_char(&buf[sent_so_far]), left, MSG_NOSIGNAL);
18,315✔
430
            if(sent < 0) {
18,315✔
431
               if(errno == EPIPE) {
8✔
432
                  return;
433
               } else {
434
                  throw Shim_Exception("Socket write failed", errno);
×
435
               }
436
            } else {
437
               sent_so_far += static_cast<size_t>(sent);
18,307✔
438
            }
439
         }
440
      }
441

442
      size_t read(uint8_t buf[], size_t len) const {
135,497✔
443
         if(m_socket < 0) {
135,497✔
444
            throw Shim_Exception("Socket was bad on read");
×
445
         }
446
         socket_op_ret_type got = ::read(m_socket, Botan::cast_uint8_ptr_to_char(buf), len);
135,497✔
447

448
         if(got < 0) {
135,497✔
449
            if(errno == ECONNRESET) {
307✔
450
               return 0;
451
            }
452
            throw Shim_Exception("Socket read failed: " + std::string(strerror(errno)));
×
453
         }
454

455
         return static_cast<size_t>(got);
135,190✔
456
      }
457

458
      void read_exactly(uint8_t buf[], size_t len) const {
238,008✔
459
         if(m_socket < 0) {
238,008✔
460
            throw Shim_Exception("Socket was bad on read");
×
461
         }
462

463
         while(len > 0) {
476,016✔
464
            socket_op_ret_type got = ::read(m_socket, Botan::cast_uint8_ptr_to_char(buf), len);
238,008✔
465

466
            if(got == 0) {
238,008✔
467
               throw Shim_Exception("Socket read EOF");
×
468
            } else if(got < 0) {
238,008✔
469
               throw Shim_Exception("Socket read failed: " + std::string(strerror(errno)));
×
470
            }
471

472
            buf += static_cast<size_t>(got);
238,008✔
473
            len -= static_cast<size_t>(got);
238,008✔
474
         }
475
      }
238,008✔
476

477
   private:
478
      socket_type m_socket;
479
};
480

481
#endif
482

483
std::set<std::string> combine_options(const std::set<std::string>& a,
1,995✔
484
                                      const std::set<std::string>& b,
485
                                      const std::set<std::string>& c,
486
                                      const std::set<std::string>& d) {
487
   std::set<std::string> combined;
1,995✔
488

489
   for(const auto& i : a) {
51,870✔
490
      combined.insert(i);
49,875✔
491
   }
492
   for(const auto& i : b) {
7,980✔
493
      combined.insert(i);
5,985✔
494
   }
495
   for(const auto& i : c) {
43,890✔
496
      combined.insert(i);
41,895✔
497
   }
498
   for(const auto& i : d) {
9,975✔
499
      combined.insert(i);
7,980✔
500
   }
501

502
   return combined;
1,995✔
503
}
×
504

505
class Shim_Arguments final {
506
   public:
507
      Shim_Arguments(const std::set<std::string>& flags,
1,995✔
508
                     const std::set<std::string>& string_opts,
509
                     const std::set<std::string>& base64_opts,
510
                     const std::set<std::string>& int_opts,
511
                     const std::set<std::string>& int_vec_opts) :
1,995✔
512
            m_flags(flags),
1,995✔
513
            m_string_opts(string_opts),
1,995✔
514
            m_base64_opts(base64_opts),
1,995✔
515
            m_int_opts(int_opts),
1,995✔
516
            m_int_vec_opts(int_vec_opts),
1,995✔
517
            m_all_options(combine_options(string_opts, base64_opts, int_opts, int_vec_opts)) {}
1,995✔
518

519
      void parse_args(char* argv[]);
520

521
      bool flag_set(const std::string& flag) const {
110,731✔
522
         if(!m_flags.contains(flag)) {
110,731✔
523
            throw Shim_Exception("Unknown bool flag " + flag);
×
524
         }
525

526
         return m_parsed_flags.contains(flag);
110,731✔
527
      }
528

529
      std::string test_name() const { return get_string_opt("test-name"); }
8,182✔
530

531
      std::string get_string_opt(const std::string& key) const {
9,263✔
532
         if(!m_string_opts.contains(key)) {
9,263✔
533
            throw Shim_Exception("Unknown string key " + key);
×
534
         }
535
         return get_opt(key);
9,263✔
536
      }
537

538
      std::string get_string_opt_or_else(const std::string& key, const std::string& def) const {
195,280✔
539
         if(!m_string_opts.contains(key)) {
195,280✔
540
            throw Shim_Exception("Unknown string key " + key);
×
541
         }
542
         if(!option_used(key)) {
195,280✔
543
            return def;
194,001✔
544
         }
545
         return get_opt(key);
1,279✔
546
      }
547

548
      std::vector<uint8_t> get_b64_opt(const std::string& key) const {
73✔
549
         if(!m_base64_opts.contains(key)) {
73✔
550
            throw Shim_Exception("Unknown base64 key " + key);
×
551
         }
552
         return Botan::unlock(Botan::base64_decode(get_opt(key)));
219✔
553
      }
554

555
      size_t get_int_opt(const std::string& key) const {
7,433✔
556
         if(!m_int_opts.contains(key)) {
7,433✔
557
            throw Shim_Exception("Unknown int key " + key);
×
558
         }
559
         return Botan::to_u32bit(get_opt(key));
7,433✔
560
      }
561

562
      size_t get_int_opt_or_else(const std::string& key, size_t def) const {
7,910✔
563
         if(!m_int_opts.contains(key)) {
7,910✔
564
            throw Shim_Exception("Unknown int key " + key);
×
565
         }
566
         if(!option_used(key)) {
7,910✔
567
            return def;
568
         }
569

570
         return Botan::to_u32bit(get_opt(key));
938✔
571
      }
572

573
      std::vector<size_t> get_int_vec_opt(const std::string& key) const {
549✔
574
         if(!m_int_vec_opts.contains(key)) {
549✔
575
            throw Shim_Exception("Unknown int vec key " + key);
×
576
         }
577

578
         auto i = m_parsed_int_vec_opts.find(key);
549✔
579
         if(i == m_parsed_int_vec_opts.end()) {
549✔
580
            return std::vector<size_t>();
×
581
         } else {
582
            return i->second;
549✔
583
         }
584
      }
585

586
      std::vector<std::string> get_alpn_string_vec_opt(const std::string& option) const {
1,443✔
587
         // hack used for alpn list (relies on all ALPNs being 3 chars long...)
588
         char delim = 0x03;
1,443✔
589

590
         if(option_used(option)) {
1,443✔
591
            return Botan::split_on(get_string_opt(option), delim);
58✔
592
         } else {
593
            return std::vector<std::string>();
1,414✔
594
         }
595
      }
596

597
      bool option_used(const std::string& key) const {
325,268✔
598
         if(!m_all_options.contains(key)) {
325,268✔
599
            throw Shim_Exception("Invalid option " + key);
×
600
         }
601
         if(m_parsed_opts.find(key) != m_parsed_opts.end()) {
325,268✔
602
            return true;
603
         }
604
         if(m_parsed_int_vec_opts.find(key) != m_parsed_int_vec_opts.end()) {
319,315✔
605
            return true;
606
         }
607
         return false;
608
      }
609

610
   private:
611
      std::string get_opt(const std::string& key) const {
18,986✔
612
         auto i = m_parsed_opts.find(key);
18,986✔
613
         if(i == m_parsed_opts.end()) {
18,986✔
614
            throw Shim_Exception("Option " + key + " was not provided");
×
615
         }
616
         return i->second;
18,986✔
617
      }
618

619
      const std::set<std::string> m_flags;
620
      const std::set<std::string> m_string_opts;
621
      const std::set<std::string> m_base64_opts;
622
      const std::set<std::string> m_int_opts;
623
      const std::set<std::string> m_int_vec_opts;
624
      const std::set<std::string> m_all_options;
625

626
      std::set<std::string> m_parsed_flags;
627
      std::map<std::string, std::string> m_parsed_opts;
628
      std::map<std::string, std::vector<size_t>> m_parsed_int_vec_opts;
629
};
630

631
void Shim_Arguments::parse_args(char* argv[]) {
1,995✔
632
   int i = 1;  // skip argv[0]
1,995✔
633

634
   while(argv[i] != nullptr) {
18,868✔
635
      const std::string param(argv[i]);
16,873✔
636

637
      if(param.starts_with("-")) {
16,873✔
638
         const std::string flag_name = param.substr(1, std::string::npos);
16,873✔
639

640
         if(m_flags.contains(flag_name)) {
16,873✔
641
            shim_log("flag " + flag_name);
5,515✔
642
            m_parsed_flags.insert(flag_name);
5,515✔
643
            i += 1;
5,515✔
644
         } else if(m_all_options.contains(flag_name)) {
11,358✔
645
            if(argv[i + 1] == nullptr) {
11,358✔
646
               throw Shim_Exception("Expected argument following " + param);
×
647
            }
648
            std::string val(argv[i + 1]);
11,358✔
649
            shim_log(Botan::fmt("param {}={}", flag_name, val));
11,358✔
650

651
            if(m_int_vec_opts.contains(flag_name)) {
11,358✔
652
               const size_t v = Botan::to_u32bit(val);
370✔
653
               m_parsed_int_vec_opts[flag_name].push_back(v);
370✔
654
            } else {
655
               m_parsed_opts[flag_name] = val;
10,988✔
656
            }
657
            i += 2;
11,358✔
658
         } else {
11,358✔
659
            shim_log("Unknown option " + param);
×
660
            throw Shim_Exception("Unknown option " + param, 89);
×
661
         }
662
      } else {
16,873✔
663
         shim_log("Unknown option " + param);
×
664
         throw Shim_Exception("Unknown option " + param, 89);
×
665
      }
666
   }
16,873✔
667
}
1,995✔
668

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

768
   const std::set<std::string> bogo_shim_string_opts = {
1,995✔
769
      "advertise-alpn",
770
      //"advertise-npn",
771
      "cert-file",
772
      "cipher",
773
      //"delegated-credential",
774
      "expect-advertised-alpn",
775
      "expect-alpn",
776
      "expect-client-ca-list",
777
      "expect-early-data-reason",
778
      "expect-late-alpn",
779
      "expect-msg-callback",
780
      //"expect-next-proto",
781
      "expect-peer-cert-file",
782
      "expect-server-name",
783
      "export-context",
784
      "export-label",
785
      "handshaker-path",
786
      "host-name",
787
      "key-file",
788
      "psk",
789
      "psk-identity",
790
      "select-alpn",
791
      "select-next-proto",
792
      "srtp-profiles",
793
      "test-name",
794
      "trust-cert",
795
      "use-client-ca-list",
796
      //"send-channel-id",
797
      "write-settings",
798
   };
1,995✔
799

800
   const std::set<std::string> bogo_shim_base64_opts = {
1,995✔
801
      "expect-certificate-types",
802
      //"expect-channel-id",
803
      "expect-ocsp-response",
804
      //"expect-quic-transport-params",
805
      //"expect-signed-cert-timestamps",
806
      "ocsp-response",
807
      //"quic-transport-params",
808
      //"signed-cert-timestamps",
809
      //"ticket-key", /* we use a different ticket format from Boring */
810
      //"token-binding-params",
811
   };
1,995✔
812

813
   const std::set<std::string> bogo_shim_int_opts{
1,995✔
814
      "expect-cipher-aes",
815
      "expect-cipher-no-aes",
816
      "expect-curve-id",
817
      "expect-peer-signature-algorithm",
818
      "expect-ticket-age-skew",
819
      "expect-token-binding-param",
820
      "expect-total-renegotiations",
821
      "expect-version",
822
      //"export-early-keying-material",
823
      "export-keying-material",
824
      "initial-timeout-duration-ms",
825
      "max-cert-list",
826
      //"max-send-fragment",
827
      "max-version",
828
      "min-version",
829
      "mtu",
830
      "on-initial-expect-curve-id",
831
      "on-resume-expect-curve-id",
832
      "port",
833
      "read-size",
834
      "resume-count",
835
      "resumption-delay",
836
      "shim-id",
837
   };
45,885✔
838

839
   const std::set<std::string> bogo_shim_int_vec_opts{
1,995✔
840
      "curves",
841
      "expect-peer-verify-pref",
842
      "signing-prefs",
843
      "verify-prefs",
844
   };
11,970✔
845

846
   std::unique_ptr<Shim_Arguments> args(new Shim_Arguments(
1,995✔
847
      bogo_shim_flags, bogo_shim_string_opts, bogo_shim_base64_opts, bogo_shim_int_opts, bogo_shim_int_vec_opts));
1,995✔
848

849
   // may throw:
850
   args->parse_args(argv);
1,995✔
851

852
   return args;
1,995✔
853
}
7,980✔
854

855
class Shim_Policy final : public Botan::TLS::Policy {
2,591✔
856
   public:
857
      Shim_Policy(const Shim_Arguments& args) : m_args(args), m_sessions(0) {}
2,609✔
858

859
      void incr_session_established() { m_sessions += 1; }
1,987✔
860

861
      std::vector<std::string> allowed_ciphers() const override {
184,571✔
862
         std::vector<std::string> allowed_without_aes = {
184,571✔
863
            "ChaCha20Poly1305",
864
            "Camellia-256/GCM",
865
            "Camellia-128/GCM",
866
            "ARIA-256/GCM",
867
            "ARIA-128/GCM",
868
            "Camellia-256",
869
            "Camellia-128",
870
            "SEED",
871
         };
184,571✔
872

873
         std::vector<std::string> allowed_just_aes = {
184,571✔
874
            "AES-256/OCB(12)",
875
            "AES-128/OCB(12)",
876
            "AES-256/GCM",
877
            "AES-128/GCM",
878
            "AES-256/CCM",
879
            "AES-128/CCM",
880
            "AES-256/CCM(8)",
881
            "AES-128/CCM(8)",
882
            "AES-256",
883
            "AES-128",
884
         };
184,571✔
885

886
         // 3DES is not supported by default anymore, only if the test runner
887
         // explicitly enables it via -cipher=
888
         const std::string cipher_limit = m_args.get_string_opt_or_else("cipher", "");
369,142✔
889
         if(cipher_limit == "3DES") {
184,571✔
890
            return {"3DES"};
1,006✔
891
         } else if(cipher_limit == "DEFAULT:!AES") {
183,565✔
892
            return allowed_without_aes;
94✔
893
         } else {
894
            // ignore this very specific config (handled in the overload of ciphersuite_list)
895
            if(!cipher_limit.empty() &&
183,471✔
896
               cipher_limit !=
897
                  "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]") {
×
898
               shim_exit_with_error("Unknown cipher limit " + cipher_limit);
×
899
            }
900
         }
901

902
         return Botan::concat(allowed_without_aes, allowed_just_aes);
184,571✔
903
      }
184,571✔
904

905
      std::vector<std::string> allowed_signature_hashes() const override {
27,730✔
906
         if(m_args.option_used("signing-prefs")) {
27,730✔
907
            std::vector<std::string> pref_hash;
106✔
908
            for(size_t pref : m_args.get_int_vec_opt("signing-prefs")) {
215✔
909
               const Botan::TLS::Signature_Scheme scheme(pref);
109✔
910
               if(!scheme.is_available()) {
109✔
911
                  shim_log("skipping inavailable but preferred signature scheme: " + std::to_string(pref));
3✔
912
                  continue;
1✔
913
               }
914
               pref_hash.push_back(scheme.hash_function_name());
108✔
915
            }
106✔
916

917
            if(m_args.flag_set("server")) {
106✔
918
               pref_hash.push_back("SHA-256");
168✔
919
            }
920
            return pref_hash;
106✔
921
         } else {
106✔
922
            return {"SHA-512", "SHA-384", "SHA-256", "SHA-1"};
27,624✔
923
         }
924
      }
925

926
      //std::vector<std::string> allowed_macs() const override;
927

928
      std::vector<std::string> allowed_signature_methods() const override {
26,131✔
929
         return {
26,131✔
930
            "ECDSA",
931
            "RSA",
932
            "IMPLICIT",
933
         };
26,131✔
934
      }
935

936
      std::vector<Botan::TLS::Signature_Scheme> acceptable_signature_schemes() const override {
1,743✔
937
         if(m_args.option_used("verify-prefs")) {
1,743✔
938
            std::vector<Botan::TLS::Signature_Scheme> schemes;
95✔
939
            for(size_t pref : m_args.get_int_vec_opt("verify-prefs")) {
190✔
940
               schemes.emplace_back(static_cast<uint16_t>(pref));
95✔
941
            }
95✔
942

943
            return schemes;
95✔
944
         }
95✔
945

946
         return Botan::TLS::Policy::acceptable_signature_schemes();
1,648✔
947
      }
948

949
      std::vector<Botan::TLS::Signature_Scheme> allowed_signature_schemes() const override {
2,910✔
950
         if(m_args.option_used("signing-prefs")) {
2,910✔
951
            std::vector<Botan::TLS::Signature_Scheme> schemes;
132✔
952
            for(size_t pref : m_args.get_int_vec_opt("signing-prefs")) {
268✔
953
               schemes.emplace_back(static_cast<uint16_t>(pref));
136✔
954
            }
132✔
955

956
            // The relevant tests (*-Sign-Negotiate-*) want to configure a preference
957
            // for the scheme of our signing operation (-signing-prefs). However, this
958
            // policy method (`allowed_signature_schemes`) also restricts the peer's
959
            // signing operation. If we weren't to add a few 'common' algorithms, initial
960
            // security parameter negotiation would fail.
961
            // By placing the BoGo-configured scheme first we make sure our implementation
962
            // meets BoGo's expectation when it is our turn to sign.
963
            if(!m_args.flag_set("server")) {
132✔
964
               schemes.emplace_back(Botan::TLS::Signature_Scheme::RSA_PKCS1_SHA256);
77✔
965
               schemes.emplace_back(Botan::TLS::Signature_Scheme::RSA_PSS_SHA256);
77✔
966
               schemes.emplace_back(Botan::TLS::Signature_Scheme::ECDSA_SHA256);
77✔
967
            }
968

969
            return schemes;
132✔
970
         }
132✔
971

972
         return Botan::TLS::Policy::allowed_signature_schemes();
2,778✔
973
      }
974

975
      //size_t minimum_signature_strength() const override;
976

977
      bool require_cert_revocation_info() const override { return false; }
6✔
978

979
      std::vector<Botan::TLS::Group_Params> key_exchange_groups() const override {
6,152✔
980
         if(m_args.option_used("curves")) {
6,152✔
981
            std::vector<Botan::TLS::Group_Params> groups;
216✔
982

983
            // upcall to base class to find the groups actually supported by
984
            // this Botan build
985
            const auto supported_groups = Botan::TLS::Policy::key_exchange_groups();
216✔
986

987
            for(size_t pref : m_args.get_int_vec_opt("curves")) {
844✔
988
               const auto group = static_cast<Botan::TLS::Group_Params>(pref);
628✔
989
               if(std::find(supported_groups.cbegin(), supported_groups.cend(), group) != supported_groups.end()) {
628✔
990
                  groups.push_back(group);
480✔
991
               }
992

993
               // Given that this is still a draft-standard, we didn't add the
994
               // hybrid groups to the default policy, yet.
995
               //
996
               // TODO: once `TLS::Policy::key_exchange_groups()` contains it by
997
               //       default, remove this explicit check.
998
               if(group == Botan::TLS::Group_Params::HYBRID_X25519_KYBER_768_R3_OQS) {
628✔
999
                  groups.push_back(group);
59✔
1000
               }
1001
            }
216✔
1002

1003
            return groups;
216✔
1004
         }
216✔
1005

1006
         return Botan::TLS::Policy::key_exchange_groups();
5,936✔
1007
      }
1008

1009
      bool use_ecc_point_compression() const override { return false; }  // BoGo expects this
2,137✔
1010

1011
      Botan::TLS::Group_Params choose_key_exchange_group(
2,489✔
1012
         const std::vector<Botan::TLS::Group_Params>& supported_by_peer,
1013
         const std::vector<Botan::TLS::Group_Params>& offered_by_peer) const override {
1014
         BOTAN_UNUSED(offered_by_peer);
2,489✔
1015

1016
         // always insist on our most preferred group regardless of the peer's
1017
         // pre-offers (BoGo expects it like that)
1018
         const auto our_groups = key_exchange_groups();
2,489✔
1019
         for(auto g : our_groups) {
9,396✔
1020
            if(Botan::value_exists(supported_by_peer, g)) {
17,698✔
1021
               return g;
1,942✔
1022
            }
1023
         }
1024

1025
         return Botan::TLS::Group_Params::NONE;
547✔
1026
      }
2,489✔
1027

1028
      bool require_client_certificate_authentication() const override {
504✔
1029
         return m_args.flag_set("require-any-client-certificate");
504✔
1030
      }
1031

1032
      bool request_client_certificate_authentication() const override {
505✔
1033
         return m_args.flag_set("verify-peer") || m_args.flag_set("fail-cert-callback") ||
1,458✔
1034
                require_client_certificate_authentication();
981✔
1035
      }
1036

1037
      bool allow_insecure_renegotiation() const override {
1,082✔
1038
         if(m_args.flag_set("expect-no-secure-renegotiation")) {
1,082✔
1039
            return true;
1040
         } else {
1041
            return false;
1,081✔
1042
         }
1043
      }
1044

1045
      //bool include_time_in_hello_random() const override;
1046

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

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

1056
         return false;
1057
      }
1058

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

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

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

1080
         return version.known_version();
17,714✔
1081
      }
1082

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

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

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

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

1100
      //size_t minimum_dh_group_size() const override;
1101

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

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

1106
      //size_t minimum_rsa_bits() const override;
1107

1108
      //size_t minimum_dsa_group_size() const override;
1109

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

1112
      //bool hide_unknown_users() const override;
1113

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

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

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

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

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

1138
      //bool server_uses_own_ciphersuite_preferences() const override;
1139

1140
      //bool negotiate_encrypt_then_mac() const override;
1141

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

1154
         return true;
1155
      }
1156

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

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

1161
      //size_t dtls_initial_timeout() const override;
1162

1163
      //size_t dtls_maximum_timeout() const override;
1164

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

1173
      size_t maximum_certificate_chain_size() const override { return m_args.get_int_opt_or_else("max-cert-list", 0); }
1,270✔
1174

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

1193
         return true;
1194
      }
2,660✔
1195

1196
   private:
1197
      const Shim_Arguments& m_args;
1198
      size_t m_sessions;
1199
};
1200

1201
std::vector<uint16_t> Shim_Policy::ciphersuite_list(Botan::TLS::Protocol_Version version) const {
3,330✔
1202
   std::vector<uint16_t> ciphersuite_codes;
3,330✔
1203

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

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

1229
         // Can we use it?
1230
         if(suite.valid() == false || !suite.usable_in_version(version) ||
312,550✔
1231
            !Botan::value_exists(allowed_ciphers(), suite.cipher_algo())) {
509,839✔
1232
            continue;
141,093✔
1233
         }
1234

1235
         ciphersuite_codes.push_back(suite.ciphersuite_code());
171,457✔
1236
      }
1237
   }
3,325✔
1238

1239
   return ciphersuite_codes;
3,330✔
1240
}
3,330✔
1241

1242
class Shim_Credentials final : public Botan::Credentials_Manager {
1243
   public:
1244
      Shim_Credentials(const Shim_Arguments& args) : m_args(args) {
1,994✔
1245
         const auto psk_identity = m_args.get_string_opt_or_else("psk-identity", "");
3,988✔
1246
         const auto psk_str = m_args.get_string_opt_or_else("psk", "");
3,988✔
1247

1248
         if(!psk_identity.empty() || !psk_str.empty()) {
1,994✔
1249
            // If the shim received a -psk param but no -psk-identity param,
1250
            // we have to initialize the identity as "empty string".
1251
            m_psk_identity = psk_identity;
87✔
1252
         }
1253

1254
         if(!psk_str.empty()) {
1,994✔
1255
            m_psk = Botan::SymmetricKey(reinterpret_cast<const uint8_t*>(psk_str.data()), psk_str.size());
87✔
1256
         }
1257

1258
         if(m_args.option_used("key-file") && m_args.option_used("cert-file")) {
2,932✔
1259
            Botan::DataSource_Stream key_stream(m_args.get_string_opt("key-file"));
1,876✔
1260
            m_key.reset(Botan::PKCS8::load_key(key_stream).release());
938✔
1261

1262
            Botan::DataSource_Stream cert_stream(m_args.get_string_opt("cert-file"));
1,876✔
1263

1264
            while(!cert_stream.end_of_data()) {
2,818✔
1265
               try {
1,880✔
1266
                  m_cert_chain.push_back(Botan::X509_Certificate(cert_stream));
2,822✔
1267
               } catch(...) {}
938✔
1268
            }
1269
         }
938✔
1270

1271
         if(m_args.option_used("trust-cert") && !m_args.get_string_opt("trust-cert").empty()) {
4,864✔
1272
            Botan::DataSource_Stream cert_stream(m_args.get_string_opt("trust-cert"));
2,858✔
1273
            try {
1,429✔
1274
               m_trust_roots.add_certificate(Botan::X509_Certificate(cert_stream));
1,429✔
1275
            } catch(const std::exception& ex) {
×
1276
               throw Shim_Exception("Failed to load trusted root certificate: " + std::string(ex.what()));
×
1277
            }
×
1278
         }
1,429✔
1279
      }
1,994✔
1280

1281
      std::vector<Botan::Certificate_Store*> trusted_certificate_authorities(const std::string& type,
1,960✔
1282
                                                                             const std::string& context) override {
1283
         if(m_args.flag_set("server") && type != "tls-server") {
3,920✔
1284
            throw Shim_Exception("TLS server implementation asked for unexpected trusted CA type: " + type);
×
1285
         }
1286
         if(!m_args.flag_set("server") && type != "tls-client") {
3,920✔
1287
            throw Shim_Exception("TLS client implementation asked for unexpected trusted CA type: " + type);
×
1288
         }
1289

1290
         const auto expected_hostname = m_args.get_string_opt_or_else("host-name", "none");
3,920✔
1291
         if(expected_hostname != "none" && expected_hostname != context) {
1,960✔
1292
            throw Shim_Exception("Unexpected host name in trusted CA request: " + context);
×
1293
         }
1294

1295
         return {&m_trust_roots};
1,960✔
1296
      }
1,960✔
1297

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

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

1308
      Botan::secure_vector<uint8_t> session_ticket_key() override {
1,702✔
1309
         return Botan::hex_decode_locked("ABCDEF0123456789");
1,702✔
1310
      }
1311

1312
      Botan::secure_vector<uint8_t> dtls_cookie_secret() override {
610✔
1313
         return Botan::hex_decode_locked("F00FB00FD00F100F700F");
610✔
1314
      }
1315

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

1325
         auto id_matches =
107✔
1326
            identities.empty() || std::find(identities.begin(), identities.end(), m_psk_identity) != identities.end();
107✔
1327

1328
         if(!id_matches) {
107✔
1329
            throw Shim_Exception("Unexpected PSK identity");
×
1330
         }
1331

1332
         if(!m_psk.has_value()) {
107✔
1333
            throw Shim_Exception("PSK identified but not set");
×
1334
         }
1335

1336
         std::vector<Botan::TLS::ExternalPSK> psks;
107✔
1337

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

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

1357
         if(m_key != nullptr && !m_cert_chain.empty()) {
2,084✔
1358
            for(const std::string& t : cert_key_types) {
3,013✔
1359
               if(t == m_key->algo_name()) {
1,980✔
1360
                  return m_cert_chain;
2,084✔
1361
               }
1362
            }
1363
         }
1364

1365
         return {};
1,216✔
1366
      }
1367

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

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

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

1399
      size_t sessions_established() const { return m_sessions_established; }
21✔
1400

1401
      void set_channel(Botan::TLS::Channel* channel) { m_channel = channel; }
2,607✔
1402

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

1405
      bool saw_close_notify() const { return m_got_close; }
27✔
1406

1407
      void tls_emit_data(std::span<const uint8_t> data) override {
15,706✔
1408
         shim_log("sending record of len " + std::to_string(data.size()));
47,118✔
1409

1410
         if(m_args.option_used("write-settings")) {
15,706✔
1411
            // TODO: the transcript option should probably be used differently
1412
            std::cout << ">>>" << std::endl << Botan::hex_encode(data) << std::endl << ">>>" << std::endl;
×
1413
         }
1414

1415
         if(m_is_datagram) {
15,706✔
1416
            std::vector<uint8_t> packet(data.size() + 5);
5,692✔
1417

1418
            packet[0] = 'P';
5,692✔
1419
            for(size_t i = 0; i != 4; ++i) {
28,460✔
1420
               packet[i + 1] = static_cast<uint8_t>((data.size() >> (24 - 8 * i)) & 0xFF);
22,768✔
1421
            }
1422
            std::memcpy(packet.data() + 5, data.data(), data.size());
5,692✔
1423

1424
            m_socket.write(packet.data(), packet.size());
5,692✔
1425
         } else {
5,692✔
1426
            m_socket.write(data.data(), data.size());
10,014✔
1427
         }
1428
      }
15,706✔
1429

1430
      std::vector<uint8_t> tls_provide_cert_status(const std::vector<Botan::X509_Certificate>&,
742✔
1431
                                                   const Botan::TLS::Certificate_Status_Request&) override {
1432
         if(m_args.flag_set("use-ocsp-callback") && m_args.flag_set("fail-ocsp-callback")) {
814✔
1433
            throw std::runtime_error("Simulating failure from OCSP response callback");
24✔
1434
         }
1435

1436
         if(m_args.flag_set("decline-ocsp-callback")) {
718✔
1437
            return {};
24✔
1438
         }
1439

1440
         if(m_args.option_used("ocsp-response")) {
694✔
1441
            return m_args.get_b64_opt("ocsp-response");
96✔
1442
         }
1443

1444
         return {};
646✔
1445
      }
1446

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

1457
         shim_log("Reflecting application_data len " + std::to_string(data.size()));
6,942✔
1458

1459
         std::vector<uint8_t> buf(data.begin(), data.end());
2,314✔
1460
         for(auto& b : buf) {
1,176,949✔
1461
            b ^= 0xFF;
1,174,635✔
1462
         }
1463

1464
         m_channel->send(buf);
2,314✔
1465
      }
2,314✔
1466

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

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

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

1487
         return Botan::TLS::Callbacks::tls_verify_message(key, padding, format, msg, sig);
1,033✔
1488
      }
1489

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

1502
         if(m_args.flag_set("verify-fail")) {
1,151✔
1503
            auto alert = Botan::TLS::Alert::HandshakeFailure;
96✔
1504
            if(m_args.flag_set("use-custom-verify-callback")) {
96✔
1505
               alert = Botan::TLS::Alert::CertificateUnknown;
48✔
1506
            }
1507

1508
            throw Botan::TLS::TLS_Exception(alert, "Test requires rejecting cert");
96✔
1509
         }
1510

1511
         if(!cert_chain.empty() && cert_chain.front().is_self_signed()) {
1,055✔
1512
            for(const auto roots : trusted_roots) {
1,049✔
1513
               if(roots->certificate_known(cert_chain.front())) {
1,049✔
1514
                  shim_log("Trusting self-signed certificate");
1,049✔
1515
                  return;
1,049✔
1516
               }
1517
            }
1518
         }
1519

1520
         shim_log("Establishing trust from a certificate chain");
6✔
1521

1522
         Botan::TLS::Callbacks::tls_verify_cert_chain(
6✔
1523
            cert_chain, ocsp_responses, trusted_roots, usage, "" /* hostname */, policy);
1524
      }
1525

1526
      std::optional<Botan::OCSP::Response> tls_parse_ocsp_response(const std::vector<uint8_t>& raw_response) override {
73✔
1527
         if(m_args.option_used("expect-ocsp-response") && m_args.get_b64_opt("expect-ocsp-response") != raw_response) {
148✔
1528
            shim_exit_with_error("unexpected OCSP response");
×
1529
         }
1530

1531
         // Bogo uses invalid dummy OCSP responses. Don't even bother trying to
1532
         // decode them.
1533
         return std::nullopt;
73✔
1534
      }
1535

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

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

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

1569
         if(m_args.flag_set("decline-alpn")) {
18✔
1570
            return "";
6✔
1571
         }
1572

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

1576
            if(client_protos != expected) {
12✔
1577
               shim_exit_with_error("Bad ALPN from client");
×
1578
            }
1579
         }
12✔
1580

1581
         if(m_args.option_used("select-alpn")) {
12✔
1582
            return m_args.get_string_opt("select-alpn");
24✔
1583
         }
1584

1585
         return client_protos[0];  // if not configured just pick something
×
1586
      }
1587

1588
      void tls_alert(Botan::TLS::Alert alert) override {
1,875✔
1589
         if(alert.is_fatal()) {
1,875✔
1590
            shim_log("Got a fatal alert " + alert.type_string());
39✔
1591
         } else {
1592
            shim_log("Got a warning alert " + alert.type_string());
5,586✔
1593
         }
1594

1595
         if(alert.type() == Botan::TLS::Alert::RecordOverflow) {
1,875✔
1596
            shim_exit_with_error(":TLSV1_ALERT_RECORD_OVERFLOW:");
4✔
1597
         }
1598

1599
         if(alert.type() == Botan::TLS::Alert::DecompressionFailure) {
1,871✔
1600
            shim_exit_with_error(":SSLV3_ALERT_DECOMPRESSION_FAILURE:");
1✔
1601
         }
1602

1603
         if(!alert.is_fatal()) {
1,870✔
1604
            m_warning_alerts++;
1,862✔
1605
            if(m_warning_alerts > 5) {
1,862✔
1606
               shim_exit_with_error(":TOO_MANY_WARNING_ALERTS:");
3✔
1607
            }
1608
         }
1609

1610
         if(alert.type() == Botan::TLS::Alert::CloseNotify) {
1,867✔
1611
            if(m_got_close == false && !m_args.flag_set("shim-shuts-down")) {
3,678✔
1612
               shim_log("Sending return close notify");
1,812✔
1613
               m_channel->send_alert(alert);
1,812✔
1614
            }
1615
            m_got_close = true;
1,830✔
1616
         } else if(alert.is_fatal()) {
37✔
1617
            shim_exit_with_error("Unexpected fatal alert " + alert.type_string());
16✔
1618
         }
1619
      }
1,859✔
1620

1621
      void tls_session_established(const Botan::TLS::Session_Summary& session) override {
1,987✔
1622
         shim_log("Session established: " + Botan::hex_encode(session.session_id().get()) + " version " +
9,935✔
1623
                  session.version().to_string() + " cipher " + session.ciphersuite().to_string() + " EMS " +
11,922✔
1624
                  std::to_string(session.supports_extended_master_secret()));
1,987✔
1625
         // probably need tests here?
1626

1627
         m_policy.incr_session_established();
1,987✔
1628
         m_sessions_established++;
1,987✔
1629

1630
         if(m_args.flag_set("expect-no-session-id")) {
1,987✔
1631
            // BoGo expects that ticket issuance implies no stateful session...
1632
            if(!m_args.flag_set("server") && !session.session_id().empty()) {
112✔
1633
               shim_exit_with_error("Unexpectedly got a session ID");
×
1634
            }
1635
         } else if(m_args.flag_set("expect-session-id") && session.session_id().empty()) {
3,862✔
1636
            shim_exit_with_error("Unexpectedly got no session ID");
×
1637
         }
1638

1639
         if(m_args.option_used("expect-version")) {
1,987✔
1640
            if(session.version().version_code() != m_args.get_int_opt("expect-version")) {
×
1641
               shim_exit_with_error("Unexpected version");
×
1642
            }
1643
         }
1644

1645
         if(m_args.flag_set("expect-secure-renegotiation")) {
1,987✔
1646
            if(m_channel->secure_renegotiation_supported() == false) {
9✔
1647
               shim_exit_with_error("Expected secure renegotiation");
×
1648
            }
1649
         } else if(m_args.flag_set("expect-no-secure-renegotiation")) {
1,978✔
1650
            if(m_channel->secure_renegotiation_supported() == true) {
2✔
1651
               shim_exit_with_error("Expected no secure renegotation");
×
1652
            }
1653
         }
1654

1655
         if(m_args.flag_set("expect-extended-master-secret")) {
1,987✔
1656
            if(session.supports_extended_master_secret() == false) {
10✔
1657
               shim_exit_with_error("Expected extended maseter secret");
×
1658
            }
1659
         }
1660
      }
1,987✔
1661

1662
      void tls_session_activated() override {
1,976✔
1663
         if(m_args.flag_set("send-alert")) {
1,976✔
1664
            m_channel->send_fatal_alert(Botan::TLS::Alert::DecompressionFailure);
16✔
1665
            return;
16✔
1666
         }
1667

1668
         if(size_t length = m_args.get_int_opt_or_else("export-keying-material", 0)) {
1,960✔
1669
            const std::string label = m_args.get_string_opt("export-label");
188✔
1670
            const std::string context = m_args.get_string_opt("export-context");
188✔
1671
            const auto exported = m_channel->key_material_export(label, context, length);
188✔
1672
            shim_log("Sending " + std::to_string(length) + " bytes of key material");
752✔
1673
            m_channel->send(exported.bits_of());
376✔
1674
         }
188✔
1675

1676
         const std::string alpn = m_channel->application_protocol();
1,960✔
1677

1678
         if(m_args.option_used("expect-alpn")) {
1,960✔
1679
            if(alpn != m_args.get_string_opt("expect-alpn")) {
10✔
1680
               shim_exit_with_error("Got unexpected ALPN");
×
1681
            }
1682
         }
1683

1684
         if(alpn == "baz" && !m_args.flag_set("allow-unknown-alpn-protos")) {
1,969✔
1685
            throw Botan::TLS::TLS_Exception(Botan::TLS::Alert::IllegalParameter, "Unexpected ALPN protocol");
3✔
1686
         }
1687

1688
         if(m_args.flag_set("shim-shuts-down")) {
1,957✔
1689
            shim_log("Shim shutting down");
45✔
1690
            m_channel->close();
45✔
1691
         }
1692

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

1696
            std::vector<uint8_t> buf(32769, 0x42);
×
1697

1698
            for(size_t sz : record_sizes) {
×
1699
               m_channel->send(buf.data(), sz);
×
1700
            }
1701

1702
            m_channel->close();
×
1703
         }
×
1704

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

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

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

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

1728
      void tls_inspect_handshake_msg(const Botan::TLS::Handshake_Message& msg) override {
20,467✔
1729
         if(msg.type() == Botan::TLS::Handshake_Type::HelloRetryRequest) {
20,467✔
1730
            m_hello_retry_request = true;
69✔
1731
         }
1732
      }
20,467✔
1733

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

1748
}  // namespace
1749

1750
int main(int /*argc*/, char* argv[]) {
1,995✔
1751
   try {
1,995✔
1752
      std::unique_ptr<Shim_Arguments> args = parse_options(argv);
1,995✔
1753

1754
      if(args->flag_set("is-handshaker-supported")) {
1,995✔
1755
         return shim_output("No\n");
1✔
1756
      }
1757

1758
      const uint16_t port = static_cast<uint16_t>(args->get_int_opt("port"));
1,994✔
1759
      const size_t resume_count = args->get_int_opt_or_else("resume-count", 0);
1,994✔
1760
      const bool is_server = args->flag_set("server");
1,994✔
1761
      const bool is_datagram = args->flag_set("dtls");
1,994✔
1762
      const size_t buf_size = args->get_int_opt_or_else("read-size", 18 * 1024);
1,994✔
1763

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

1780
      if(args->flag_set("wait-for-debugger")) {
2,729✔
1781
         sleep(20);
×
1782
      }
1783

1784
      for(size_t i = 0; i != resume_count + 1; ++i) {
3,850✔
1785
         auto execute_test = [&](const std::string& hostname) {
5,218✔
1786
            Shim_Socket socket(hostname, port, args->flag_set("ipv6"));
2,609✔
1787

1788
            shim_log("Connection " + std::to_string(i + 1) + "/" + std::to_string(resume_count + 1));
10,436✔
1789

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

1798
            auto policy = std::make_shared<Shim_Policy>(*args);
2,609✔
1799
            auto callbacks = std::make_shared<Shim_Callbacks>(*args, socket, *policy);
2,609✔
1800

1801
            if(args->option_used("resumption-delay") && i > 0) {
5,218✔
1802
               shim_log("skewing the clock by " + std::to_string(args->get_int_opt("resumption-delay")) + " seconds");
12✔
1803
               callbacks->set_clock_skew(std::chrono::seconds(args->get_int_opt("resumption-delay")));
738✔
1804
            }
1805

1806
            std::unique_ptr<Botan::TLS::Channel> chan;
2,609✔
1807

1808
            if(is_server) {
2,609✔
1809
               chan = std::make_unique<Botan::TLS::Server>(callbacks, session_manager, creds, policy, rng, is_datagram);
1,176✔
1810
            } else {
1811
               Botan::TLS::Protocol_Version offer_version = policy->latest_supported_version(is_datagram);
1,433✔
1812
               shim_log("Offering " + offer_version.to_string());
4,293✔
1813

1814
               std::string host_name = args->get_string_opt_or_else("host-name", hostname);
1,431✔
1815
               if(args->test_name().starts_with("UnsolicitedServerNameAck")) {
2,862✔
1816
                  host_name = "";  // avoid sending SNI for this test
3✔
1817
               }
1818

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

1825
            callbacks->set_channel(chan.get());
2,607✔
1826

1827
            std::vector<uint8_t> buf(buf_size);
3,342✔
1828

1829
            for(;;) {
135,497✔
1830
               if(is_datagram) {
135,497✔
1831
                  uint8_t opcode;
119,574✔
1832
                  size_t got = socket.read(&opcode, 1);
119,574✔
1833
                  if(got == 0) {
119,574✔
1834
                     shim_log("EOF on socket");
570✔
1835
                     break;
570✔
1836
                  }
1837

1838
                  if(opcode == 'P') {
119,004✔
1839
                     uint8_t len_bytes[4];
119,004✔
1840
                     socket.read_exactly(len_bytes, sizeof(len_bytes));
119,004✔
1841

1842
                     size_t packet_len = Botan::load_be<uint32_t>(len_bytes, 0);
119,004✔
1843

1844
                     if(buf.size() < packet_len) {
119,004✔
1845
                        buf.resize(packet_len);
1✔
1846
                     }
1847
                     socket.read_exactly(buf.data(), packet_len);
119,004✔
1848

1849
                     chan->received_data(buf.data(), packet_len);
119,004✔
1850
                  } else if(opcode == 'T') {
×
1851
                     uint8_t timeout_ack = 't';
×
1852

1853
                     uint8_t timeout_bytes[8];
×
1854
                     socket.read_exactly(timeout_bytes, sizeof(timeout_bytes));
×
1855

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

1858
                     shim_log("Timeout nsec " + std::to_string(nsec));
×
1859

1860
                     // FIXME handle this!
1861

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

1873
                  shim_log("Got packet of " + std::to_string(got));
43,908✔
1874

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

1882
                  if(args->flag_set("use-exporter-between-reads") && chan->is_active()) {
29,272✔
1883
                     chan->key_material_export("some label", "some context", 42);
1✔
1884
                  }
1885
                  const size_t needed = chan->received_data(buf.data(), got);
14,635✔
1886

1887
                  if(needed) {
14,006✔
1888
                     shim_log("Short read still need " + std::to_string(needed));
23,061✔
1889
                  }
1890
               }
1891
            }
1892

1893
            if(args->flag_set("check-close-notify")) {
1,857✔
1894
               if(!callbacks->saw_close_notify()) {
27✔
1895
                  throw Shim_Exception("Unexpected SSL_shutdown result: -1 != 1");
1✔
1896
               }
1897
            }
1898

1899
            if(args->option_used("expect-total-renegotiations")) {
1,856✔
1900
               const size_t exp = args->get_int_opt("expect-total-renegotiations");
21✔
1901

1902
               if(exp != callbacks->sessions_established() - 1) {
21✔
1903
                  throw Shim_Exception("Unexpected number of renegotiations: saw " +
×
1904
                                       std::to_string(callbacks->sessions_established() - 1) + " exp " +
×
1905
                                       std::to_string(exp));
×
1906
               }
1907
            }
1908
            shim_log("End of resume loop");
4,445✔
1909
         };
10,362✔
1910
         try {
2,609✔
1911
            execute_test("localhost");
5,200✔
1912
         } catch(const Shim_Exception& e) {
735✔
1913
            if(std::string(e.what()) == "Failed to connect to host") {
1✔
1914
               execute_test("::1");
×
1915
            } else {
1916
               // NOLINTNEXTLINE(cert-err60-cpp)
1917
               throw e;
1✔
1918
            }
1919
         }
1✔
1920
      }
1921
   } catch(Shim_Exception& e) {
6,664✔
1922
      shim_exit_with_error(e.what(), e.rc());
1✔
1923
   } catch(std::exception& e) {
734✔
1924
      shim_exit_with_error(map_to_bogo_error(e.what()));
734✔
1925
   } catch(...) {
×
1926
      shim_exit_with_error("Unknown exception", 3);
×
1927
   }
×
1928
   return 0;
1,241✔
1929
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc