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

randombit / botan / 16245054916

13 Jul 2025 03:51AM UTC coverage: 90.581% (+0.009%) from 90.572%
16245054916

Pull #4982

github

web-flow
Merge 11956826b into e87c8e33a
Pull Request #4982: Enable and fix clang-tidy warning cert-err58-cpp

99186 of 109500 relevant lines covered (90.58%)

12549723.2 hits per line

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

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

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

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

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

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

53
namespace {
54

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

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

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

72
      if(g_log != nullptr) {
×
73
         timeval tv{};
×
74

75
         ::gettimeofday(&tv, nullptr);
×
76
         // NOLINTNEXTLINE(*-vararg)
77
         static_cast<void>(std::fprintf(g_log,
×
78
                                        "%lld.%lu: %s\n",
79
                                        static_cast<unsigned long long>(tv.tv_sec),
×
80
                                        static_cast<unsigned long>(tv.tv_usec),
×
81
                                        s.c_str()));
82
         static_cast<void>(std::fflush(g_log));
×
83
      }
84
   }
85
}
88,588✔
86

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

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

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

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

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

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

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

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

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

363
#if defined(BOTAN_TARGET_OS_HAS_SOCKETS)
364

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

469
         return static_cast<size_t>(got);
204,074✔
470
      }
471

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

477
         while(len > 0) {
735,768✔
478
            socket_op_ret_type got = ::read(m_socket, Botan::cast_uint8_ptr_to_char(buf), len);
367,884✔
479

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

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

491
   private:
492
      socket_type m_socket;
493
};
494

495
#endif
496

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

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

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

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

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

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

540
         return m_parsed_flags.contains(flag);
118,736✔
541
      }
542

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

957
            return schemes;
93✔
958
         }
93✔
959

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

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

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

983
            return schemes;
133✔
984
         }
133✔
985

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

989
      //size_t minimum_signature_strength() const override;
990

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

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

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

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

1008
            return groups;
493✔
1009
         }
493✔
1010

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

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

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

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

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

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

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

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

1050
      //bool include_time_in_hello_random() const override;
1051

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

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

1061
         return false;
1062
      }
1063

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

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

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

1085
         return version.known_version();
18,458✔
1086
      }
1087

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

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

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

1103
      //Botan::TLS::Group_Params default_dh_group() const override;
1104

1105
      //size_t minimum_dh_group_size() const override;
1106

1107
      size_t minimum_ecdsa_group_size() const override { return 224; }
131✔
1108

1109
      size_t minimum_ecdh_group_size() const override { return 224; }
1,786✔
1110

1111
      //size_t minimum_rsa_bits() const override;
1112

1113
      //size_t minimum_dsa_group_size() const override;
1114

1115
      //void check_peer_key_acceptable(const Botan::Public_Key& public_key) const override;
1116

1117
      //bool hide_unknown_users() const override;
1118

1119
      //std::chrono::seconds session_ticket_lifetime() const override;
1120

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

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

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

1141
      bool only_resume_with_exact_version() const override { return false; }
198✔
1142

1143
      //bool server_uses_own_ciphersuite_preferences() const override;
1144

1145
      //bool negotiate_encrypt_then_mac() const override;
1146

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

1159
         return true;
1160
      }
1161

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

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

1166
      //size_t dtls_initial_timeout() const override;
1167

1168
      //size_t dtls_maximum_timeout() const override;
1169

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

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

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

1198
         return true;
1199
      }
2,728✔
1200

1201
   private:
1202
      const Shim_Arguments& m_args;
1203
      size_t m_sessions;
1204
};
1205

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

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

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

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

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

1244
   return ciphersuite_codes;
3,456✔
1245
}
3,456✔
1246

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

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

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

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

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

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

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

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

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

1300
         return {&m_trust_roots};
2,084✔
1301
      }
2,084✔
1302

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

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

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

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

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

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

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

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

1341
         std::vector<Botan::TLS::ExternalPSK> psks;
102✔
1342

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

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

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

1370
         return {};
1,320✔
1371
      }
1372

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

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

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

1404
      size_t sessions_established() const { return m_sessions_established; }
21✔
1405

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

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

1410
      bool saw_close_notify() const { return m_got_close; }
27✔
1411

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

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

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

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

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

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

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

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

1449
         return {};
690✔
1450
      }
1451

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

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

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

1469
         m_channel->send(buf);
2,350✔
1470
      }
2,350✔
1471

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

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

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

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

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

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

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

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

1525
         shim_log("Establishing trust from a certificate chain");
6✔
1526

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1632
         m_policy.incr_session_established();
2,025✔
1633
         m_sessions_established++;
2,025✔
1634

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

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

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

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

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

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

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

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

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

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

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

1701
            std::vector<uint8_t> buf(32769, 0x42);
×
1702

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

1707
            m_channel->close();
×
1708
         }
×
1709

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

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

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

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

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

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

1753
}  // namespace
1754

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

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

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

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

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

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

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

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

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

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

1811
            std::unique_ptr<Botan::TLS::Channel> chan;
2,715✔
1812

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

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

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

1830
            callbacks->set_channel(chan.get());
2,713✔
1831

1832
            std::vector<uint8_t> buf(buf_size);
3,518✔
1833

1834
            for(;;) {
204,395✔
1835
               if(is_datagram) {
204,395✔
1836
                  uint8_t opcode = 0;
184,520✔
1837
                  size_t got = socket.read(&opcode, 1);
184,520✔
1838
                  if(got == 0) {
184,520✔
1839
                     shim_log("EOF on socket");
578✔
1840
                     break;
578✔
1841
                  }
1842

1843
                  if(opcode == 'P') {
183,942✔
1844
                     uint8_t len_bytes[4];
183,942✔
1845
                     socket.read_exactly(len_bytes, sizeof(len_bytes));
183,942✔
1846

1847
                     size_t packet_len = Botan::load_be<uint32_t>(len_bytes, 0);
183,942✔
1848

1849
                     if(buf.size() < packet_len) {
183,942✔
1850
                        buf.resize(packet_len);
1✔
1851
                     }
1852
                     socket.read_exactly(buf.data(), packet_len);
183,942✔
1853

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

1858
                     uint8_t timeout_bytes[8];
×
1859
                     socket.read_exactly(timeout_bytes, sizeof(timeout_bytes));
×
1860

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

1863
                     shim_log("Timeout nsec " + std::to_string(nsec));
×
1864

1865
                     // FIXME handle this!
1866

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

1878
                  shim_log("Got packet of " + std::to_string(got));
55,680✔
1879

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

1887
                  if(args->flag_set("use-exporter-between-reads") && chan->is_active()) {
37,120✔
1888
                     chan->key_material_export("some label", "some context", 42);
1✔
1889
                  }
1890
                  const size_t needed = chan->received_data(buf.data(), got);
18,559✔
1891

1892
                  if(needed) {
17,916✔
1893
                     shim_log("Short read still need " + std::to_string(needed));
33,156✔
1894
                  }
1895
               }
1896
            }
1897

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

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

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

© 2025 Coveralls, Inc