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

randombit / botan / 5955746790

23 Aug 2023 04:26PM UTC coverage: 91.708% (-0.003%) from 91.711%
5955746790

push

github

web-flow
Merge pull request #3677 from randombit/jack/ninja-build

78577 of 85682 relevant lines covered (91.71%)

8475420.58 hits per line

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

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

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

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

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

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

52
namespace {
53

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

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

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

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

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

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

326
   auto err_map_i = err_map.find(e);
732✔
327
   if(err_map_i != err_map.end()) {
732✔
328
      return err_map_i->second;
1,460✔
329
   }
330

331
   return "Unmapped error: '" + e + "'";
8✔
332
}
333

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

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

340
      int rc() const { return m_rc; }
1✔
341

342
   private:
343
      const std::string m_msg;
344
      int m_rc;
345
};
346

347
#if defined(BOTAN_TARGET_OS_HAS_SOCKETS)
348

349
class Shim_Socket final {
350
   private:
351
      typedef int socket_type;
352
      typedef ssize_t socket_op_ret_type;
353

354
      static void close_socket(socket_type s) { ::close(s); }
355

356
      static std::string get_last_socket_error() { return ::strerror(errno); }
357

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

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

368
         const std::string service = std::to_string(port);
2,598✔
369

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

377
         shim_log("Connecting " + hostname + ":" + service);
5,196✔
378

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

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

388
            m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
2,598✔
389

390
            if(m_socket == -1) {
2,598✔
391
               // unsupported socket type?
392
               continue;
×
393
            }
394

395
            int err = ::connect(m_socket, rp->ai_addr, rp->ai_addrlen);
2,598✔
396

397
            if(err != 0) {
2,598✔
398
               ::close(m_socket);
×
399
               m_socket = -1;
×
400
            }
401
         }
402

403
         if(m_socket < 0) {
2,598✔
404
            throw Shim_Exception("Failed to connect to host");
×
405
         }
406
      }
2,598✔
407

408
      Shim_Socket(const Shim_Socket&) = delete;
409
      Shim_Socket& operator=(const Shim_Socket&) = delete;
410

411
      Shim_Socket(Shim_Socket&&) = delete;
412
      Shim_Socket& operator=(Shim_Socket&&) = delete;
413

414
      ~Shim_Socket() {
2,580✔
415
         ::close(m_socket);
2,580✔
416
         m_socket = -1;
2,580✔
417
      }
2,580✔
418

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

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

446
         if(got < 0) {
167,201✔
447
            if(errno == ECONNRESET) {
550✔
448
               return 0;
449
            }
450
            throw Shim_Exception("Socket read failed: " + std::string(strerror(errno)));
×
451
         }
452

453
         return static_cast<size_t>(got);
166,651✔
454
      }
455

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

461
         while(len > 0) {
505,788✔
462
            socket_op_ret_type got = ::read(m_socket, Botan::cast_uint8_ptr_to_char(buf), len);
252,894✔
463

464
            if(got == 0) {
252,894✔
465
               throw Shim_Exception("Socket read EOF");
×
466
            } else if(got < 0) {
252,894✔
467
               throw Shim_Exception("Socket read failed: " + std::string(strerror(errno)));
×
468
            }
469

470
            buf += static_cast<size_t>(got);
252,894✔
471
            len -= static_cast<size_t>(got);
252,894✔
472
         }
473
      }
252,894✔
474

475
   private:
476
      socket_type m_socket;
477
};
478

479
#endif
480

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

487
   for(const auto& i : a) {
49,600✔
488
      combined.insert(i);
47,616✔
489
   }
490
   for(const auto& i : b) {
7,936✔
491
      combined.insert(i);
5,952✔
492
   }
493
   for(const auto& i : c) {
43,648✔
494
      combined.insert(i);
41,664✔
495
   }
496
   for(const auto& i : d) {
9,920✔
497
      combined.insert(i);
7,936✔
498
   }
499

500
   return combined;
1,984✔
501
}
×
502

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

517
      void parse_args(char* argv[]);
518

519
      bool flag_set(const std::string& flag) const {
134,861✔
520
         if(!m_flags.contains(flag)) {
134,861✔
521
            throw Shim_Exception("Unknown bool flag " + flag);
×
522
         }
523

524
         return m_parsed_flags.contains(flag);
134,861✔
525
      }
526

527
      std::string test_name() const { return get_string_opt("test-name"); }
8,146✔
528

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

536
      std::string get_string_opt_or_else(const std::string& key, const std::string& def) const {
194,533✔
537
         if(!m_string_opts.contains(key)) {
194,533✔
538
            throw Shim_Exception("Unknown string key " + key);
×
539
         }
540
         if(!option_used(key)) {
194,533✔
541
            return def;
387,789✔
542
         }
543
         return get_opt(key);
1,277✔
544
      }
545

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

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

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

568
         return Botan::to_u32bit(get_opt(key));
938✔
569
      }
570

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

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

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

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

595
      bool option_used(const std::string& key) const {
346,748✔
596
         if(!m_all_options.contains(key)) {
346,748✔
597
            throw Shim_Exception("Invalid option " + key);
×
598
         }
599
         if(m_parsed_opts.find(key) != m_parsed_opts.end()) {
346,748✔
600
            return true;
601
         }
602
         if(m_parsed_int_vec_opts.find(key) != m_parsed_int_vec_opts.end()) {
342,198✔
603
            return true;
442✔
604
         }
605
         return false;
606
      }
607

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

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

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

629
void Shim_Arguments::parse_args(char* argv[]) {
1,984✔
630
   int i = 1;  // skip argv[0]
1,984✔
631

632
   while(argv[i] != nullptr) {
17,543✔
633
      const std::string param(argv[i]);
15,559✔
634

635
      if(param.find('-') == 0) {
15,559✔
636
         const std::string flag_name = param.substr(1, std::string::npos);
15,559✔
637

638
         if(m_flags.contains(flag_name)) {
15,559✔
639
            shim_log("flag " + flag_name);
5,496✔
640
            m_parsed_flags.insert(flag_name);
5,496✔
641
            i += 1;
5,496✔
642
         } else if(m_all_options.contains(flag_name)) {
10,063✔
643
            if(argv[i + 1] == nullptr) {
10,063✔
644
               throw Shim_Exception("Expected argument following " + param);
×
645
            }
646
            std::string val(argv[i + 1]);
10,063✔
647
            shim_log(Botan::fmt("param {}={}", flag_name, val));
10,063✔
648

649
            if(m_int_vec_opts.contains(flag_name)) {
10,063✔
650
               const size_t v = Botan::to_u32bit(val);
309✔
651
               m_parsed_int_vec_opts[flag_name].push_back(v);
309✔
652
            } else {
653
               m_parsed_opts[flag_name] = val;
9,754✔
654
            }
655
            i += 2;
10,063✔
656
         } else {
10,063✔
657
            shim_log("Unknown option " + param);
×
658
            throw Shim_Exception("Unknown option " + param, 89);
×
659
         }
660
      } else {
15,559✔
661
         shim_log("Unknown option " + param);
×
662
         throw Shim_Exception("Unknown option " + param, 89);
×
663
      }
664
   }
15,559✔
665
}
1,984✔
666

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

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

795
   const std::set<std::string> bogo_shim_base64_opts = {
1,984✔
796
      "expect-certificate-types",
797
      //"expect-channel-id",
798
      "expect-ocsp-response",
799
      //"expect-quic-transport-params",
800
      //"expect-signed-cert-timestamps",
801
      "ocsp-response",
802
      //"quic-transport-params",
803
      //"signed-cert-timestamps",
804
      //"ticket-key", /* we use a different ticket format from Boring */
805
      //"token-binding-params",
806
   };
7,936✔
807

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

834
   const std::set<std::string> bogo_shim_int_vec_opts{
1,984✔
835
      "curves",
836
      "expect-peer-verify-pref",
837
      "signing-prefs",
838
      "verify-prefs",
839
   };
9,920✔
840

841
   std::unique_ptr<Shim_Arguments> args(new Shim_Arguments(
1,984✔
842
      bogo_shim_flags, bogo_shim_string_opts, bogo_shim_base64_opts, bogo_shim_int_opts, bogo_shim_int_vec_opts));
1,984✔
843

844
   // may throw:
845
   args->parse_args(argv);
1,984✔
846

847
   return args;
1,984✔
848
}
1,984✔
849

850
class Shim_Policy final : public Botan::TLS::Policy {
2,580✔
851
   public:
852
      Shim_Policy(const Shim_Arguments& args) : m_args(args), m_sessions(0) {}
2,598✔
853

854
      void incr_session_established() { m_sessions += 1; }
1,978✔
855

856
      std::vector<std::string> allowed_ciphers() const override {
183,903✔
857
         std::vector<std::string> allowed_without_aes = {
183,903✔
858
            "ChaCha20Poly1305",
859
            "Camellia-256/GCM",
860
            "Camellia-128/GCM",
861
            "ARIA-256/GCM",
862
            "ARIA-128/GCM",
863
            "Camellia-256",
864
            "Camellia-128",
865
            "SEED",
866
         };
1,655,127✔
867

868
         std::vector<std::string> allowed_just_aes = {
183,903✔
869
            "AES-256/OCB(12)",
870
            "AES-128/OCB(12)",
871
            "AES-256/GCM",
872
            "AES-128/GCM",
873
            "AES-256/CCM",
874
            "AES-128/CCM",
875
            "AES-256/CCM(8)",
876
            "AES-128/CCM(8)",
877
            "AES-256",
878
            "AES-128",
879
         };
2,022,933✔
880

881
         // 3DES is not supported by default anymore, only if the test runner
882
         // explicitly enables it via -cipher=
883
         const std::string cipher_limit = m_args.get_string_opt_or_else("cipher", "");
367,806✔
884
         if(cipher_limit == "3DES") {
183,903✔
885
            return {"3DES"};
2,012✔
886
         } else if(cipher_limit == "DEFAULT:!AES") {
182,897✔
887
            return allowed_without_aes;
183,903✔
888
         } else {
889
            // ignore this very specific config (handled in the overload of ciphersuite_list)
890
            if(!cipher_limit.empty() &&
182,803✔
891
               cipher_limit !=
892
                  "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]") {
×
893
               shim_exit_with_error("Unknown cipher limit " + cipher_limit);
×
894
            }
895
         }
896

897
         return Botan::concat(allowed_without_aes, allowed_just_aes);
182,803✔
898
      }
183,903✔
899

900
      std::vector<std::string> allowed_signature_hashes() const override {
27,997✔
901
         if(m_args.option_used("signing-prefs")) {
27,997✔
902
            std::vector<std::string> pref_hash;
76✔
903
            for(size_t pref : m_args.get_int_vec_opt("signing-prefs")) {
155✔
904
               const Botan::TLS::Signature_Scheme scheme(pref);
79✔
905
               if(!scheme.is_available()) {
79✔
906
                  shim_log("skipping inavailable but preferred signature scheme: " + std::to_string(pref));
2✔
907
                  continue;
1✔
908
               }
909
               pref_hash.push_back(scheme.hash_function_name());
78✔
910
            }
×
911

912
            if(m_args.flag_set("server")) {
76✔
913
               pref_hash.push_back("SHA-256");
128✔
914
            }
915
            return pref_hash;
76✔
916
         } else {
76✔
917
            return {"SHA-512", "SHA-384", "SHA-256", "SHA-1"};
139,605✔
918
         }
919
      }
920

921
      //std::vector<std::string> allowed_macs() const override;
922

923
      std::vector<std::string> allowed_signature_methods() const override {
26,371✔
924
         return {
26,371✔
925
            "ECDSA",
926
            "RSA",
927
            "IMPLICIT",
928
         };
105,484✔
929
      }
930

931
      std::vector<Botan::TLS::Signature_Scheme> acceptable_signature_schemes() const override {
1,713✔
932
         if(m_args.option_used("verify-prefs")) {
1,713✔
933
            std::vector<Botan::TLS::Signature_Scheme> schemes;
95✔
934
            for(size_t pref : m_args.get_int_vec_opt("verify-prefs")) {
190✔
935
               schemes.emplace_back(static_cast<uint16_t>(pref));
95✔
936
            }
×
937

938
            return schemes;
95✔
939
         }
95✔
940

941
         return Botan::TLS::Policy::acceptable_signature_schemes();
1,618✔
942
      }
943

944
      std::vector<Botan::TLS::Signature_Scheme> allowed_signature_schemes() const override {
2,874✔
945
         if(m_args.option_used("signing-prefs")) {
2,874✔
946
            std::vector<Botan::TLS::Signature_Scheme> schemes;
66✔
947
            for(size_t pref : m_args.get_int_vec_opt("signing-prefs")) {
136✔
948
               schemes.emplace_back(static_cast<uint16_t>(pref));
70✔
949
            }
×
950

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

964
            return schemes;
66✔
965
         }
66✔
966

967
         return Botan::TLS::Policy::allowed_signature_schemes();
2,808✔
968
      }
969

970
      //size_t minimum_signature_strength() const override;
971

972
      //bool require_cert_revocation_info() const override;
973

974
      std::vector<Botan::TLS::Group_Params> key_exchange_groups() const override {
6,124✔
975
         if(m_args.option_used("curves")) {
6,124✔
976
            std::vector<Botan::TLS::Group_Params> groups;
205✔
977

978
            // upcall to base class to find the groups actually supported by
979
            // this Botan build
980
            const auto supported_groups = Botan::TLS::Policy::key_exchange_groups();
205✔
981

982
            for(size_t pref : m_args.get_int_vec_opt("curves")) {
794✔
983
               const auto group = static_cast<Botan::TLS::Group_Params>(pref);
589✔
984
               if(std::find(supported_groups.cbegin(), supported_groups.cend(), group) != supported_groups.end()) {
589✔
985
                  groups.push_back(group);
457✔
986
               }
987
            }
×
988

989
            return groups;
205✔
990
         }
205✔
991

992
         return Botan::TLS::Policy::key_exchange_groups();
5,919✔
993
      }
994

995
      bool use_ecc_point_compression() const override { return false; }  // BoGo expects this
2,131✔
996

997
      Botan::TLS::Group_Params choose_key_exchange_group(
2,478✔
998
         const std::vector<Botan::TLS::Group_Params>& supported_by_peer,
999
         const std::vector<Botan::TLS::Group_Params>& offered_by_peer) const override {
1000
         BOTAN_UNUSED(offered_by_peer);
2,478✔
1001

1002
         // always insist on our most preferred group regardless of the peer's
1003
         // pre-offers (BoGo expects it like that)
1004
         const auto our_groups = key_exchange_groups();
2,478✔
1005
         for(auto g : our_groups) {
8,814✔
1006
            if(Botan::value_exists(supported_by_peer, g)) {
16,536✔
1007
               return g;
1,932✔
1008
            }
1009
         }
1010

1011
         return Botan::TLS::Group_Params::NONE;
1012
      }
2,478✔
1013

1014
      bool require_client_certificate_authentication() const override {
658✔
1015
         return m_args.flag_set("require-any-client-certificate");
1,316✔
1016
      }
1017

1018
      bool request_client_certificate_authentication() const override {
755✔
1019
         return m_args.flag_set("verify-peer") || m_args.flag_set("fail-cert-callback") ||
2,145✔
1020
                require_client_certificate_authentication();
1,385✔
1021
      }
1022

1023
      bool allow_insecure_renegotiation() const override {
1,080✔
1024
         if(m_args.flag_set("expect-no-secure-renegotiation")) {
2,160✔
1025
            return true;
1026
         } else {
1027
            return false;
1,079✔
1028
         }
1029
      }
1030

1031
      //bool include_time_in_hello_random() const override;
1032

1033
      bool allow_client_initiated_renegotiation() const override {
40✔
1034
         if(m_args.flag_set("renegotiate-freely")) {
80✔
1035
            return true;
1036
         }
1037

1038
         if(m_args.flag_set("renegotiate-once") && m_sessions <= 1) {
16✔
1039
            return true;
2✔
1040
         }
1041

1042
         return false;
1043
      }
1044

1045
      bool allow_server_initiated_renegotiation() const override {
39✔
1046
         return allow_client_initiated_renegotiation();  // same logic
39✔
1047
      }
1048

1049
      bool allow_version(Botan::TLS::Protocol_Version version) const {
17,663✔
1050
         if(m_args.option_used("min-version")) {
17,663✔
1051
            const uint16_t min_version_16 = static_cast<uint16_t>(m_args.get_int_opt("min-version"));
65✔
1052
            Botan::TLS::Protocol_Version min_version(min_version_16 >> 8, min_version_16 & 0xFF);
65✔
1053
            if(min_version > version) {
65✔
1054
               return false;
15✔
1055
            }
1056
         }
1057

1058
         if(m_args.option_used("max-version")) {
17,648✔
1059
            const uint16_t max_version_16 = static_cast<uint16_t>(m_args.get_int_opt("max-version"));
50✔
1060
            Botan::TLS::Protocol_Version max_version(max_version_16 >> 8, max_version_16 & 0xFF);
50✔
1061
            if(version > max_version) {
50✔
1062
               return false;
7✔
1063
            }
1064
         }
1065

1066
         return version.known_version();
17,641✔
1067
      }
1068

1069
      bool allow_tls12() const override {
10,396✔
1070
         return !m_args.flag_set("dtls") && !m_args.flag_set("no-tls12") &&
30,204✔
1071
                allow_version(Botan::TLS::Protocol_Version::TLS_V12);
30,204✔
1072
      }
1073

1074
      bool allow_tls13() const override {
4,773✔
1075
         return !m_args.flag_set("dtls") && !m_args.flag_set("no-tls13") &&
14,112✔
1076
                allow_version(Botan::TLS::Protocol_Version::TLS_V13);
14,112✔
1077
      }
1078

1079
      bool allow_dtls12() const override {
3,694✔
1080
         return m_args.flag_set("dtls") && !m_args.flag_set("no-tls12") &&
11,073✔
1081
                allow_version(Botan::TLS::Protocol_Version::DTLS_V12);
11,073✔
1082
      }
1083

1084
      //Botan::TLS::Group_Params default_dh_group() const override;
1085

1086
      //size_t minimum_dh_group_size() const override;
1087

1088
      size_t minimum_ecdsa_group_size() const override { return 224; }
119✔
1089

1090
      size_t minimum_ecdh_group_size() const override { return 224; }
1,726✔
1091

1092
      //size_t minimum_rsa_bits() const override;
1093

1094
      //size_t minimum_dsa_group_size() const override;
1095

1096
      //void check_peer_key_acceptable(const Botan::Public_Key& public_key) const override;
1097

1098
      //bool hide_unknown_users() const override;
1099

1100
      //std::chrono::seconds session_ticket_lifetime() const override;
1101

1102
      size_t new_session_tickets_upon_handshake_success() const override {
259✔
1103
         return m_args.flag_set("no-ticket") ? 0 : 1;
517✔
1104
      }
1105

1106
      std::vector<uint16_t> srtp_profiles() const override {
503✔
1107
         if(m_args.option_used("srtp-profiles")) {
503✔
1108
            std::string srtp = m_args.get_string_opt("srtp-profiles");
4✔
1109

1110
            if(srtp == "SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32") {
4✔
1111
               return {1, 2};
3✔
1112
            } else if(srtp == "SRTP_AES128_CM_SHA1_80") {
1✔
1113
               return {1};
1✔
1114
            } else {
1115
               shim_exit_with_error("unknown srtp-profiles");
×
1116
            }
1117
         } else {
4✔
1118
            return {};
503✔
1119
         }
1120
      }
1121

1122
      bool only_resume_with_exact_version() const override { return false; }
198✔
1123

1124
      //bool server_uses_own_ciphersuite_preferences() const override;
1125

1126
      //bool negotiate_encrypt_then_mac() const override;
1127

1128
      bool support_cert_status_message() const override {
1,988✔
1129
         if(m_args.flag_set("server")) {
1,988✔
1130
            if(!m_args.option_used("ocsp-response")) {
529✔
1131
               return false;
1132
            }
1133
            if(m_args.flag_set("decline-ocsp-callback")) {
128✔
1134
               return false;
16✔
1135
            }
1136
         } else if(!m_args.flag_set("enable-ocsp-stapling")) {
2,918✔
1137
            return false;
1,330✔
1138
         }
1139

1140
         return true;
1141
      }
1142

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

1145
      size_t dtls_default_mtu() const override { return m_args.get_int_opt_or_else("mtu", 1500); }
693✔
1146

1147
      //size_t dtls_initial_timeout() const override;
1148

1149
      //size_t dtls_maximum_timeout() const override;
1150

1151
      bool abort_connection_on_undesired_renegotiation() const override {
6✔
1152
         if(m_args.flag_set("renegotiate-ignore")) {
12✔
1153
            return false;
1154
         } else {
1155
            return true;
5✔
1156
         }
1157
      }
1158

1159
      size_t maximum_certificate_chain_size() const override { return m_args.get_int_opt_or_else("max-cert-list", 0); }
1,240✔
1160

1161
      bool tls_13_middlebox_compatibility_mode() const override {
2,647✔
1162
         // These tests expect the client to send an alert in return of a malformed TLS 1.2 server hello.
1163
         // However, our TLS 1.3 implementation produces an alert without downgrading to TLS 1.2 first.
1164
         // In compatibility mode this prepends a CCS, which BoGo does not expect to read.
1165
         const std::vector<std::string> alert_after_server_hello = {
2,647✔
1166
            "DuplicateExtensionClient-TLS-TLS12",
1167
            "WrongMessageType-ServerHello-TLS",
1168
            "SendServerHelloAsHelloRetryRequest",
1169
            "TrailingMessageData-ServerHello-TLS",
1170
            "NoSSL3-Client-Unsolicited",
1171
            "Client-TooLongSessionID",
1172
            "MinimumVersion-Client-TLS13-TLS12-TLS",
1173
            "MinimumVersion-Client2-TLS13-TLS12-TLS",
1174
         };
23,823✔
1175
         if(Botan::value_exists(alert_after_server_hello, m_args.test_name())) {
5,214✔
1176
            return false;
14✔
1177
         }
1178

1179
         return true;
1180
      }
2,647✔
1181

1182
   private:
1183
      const Shim_Arguments& m_args;
1184
      size_t m_sessions;
1185
};
1186

1187
std::vector<uint16_t> Shim_Policy::ciphersuite_list(Botan::TLS::Protocol_Version version) const {
3,314✔
1188
   std::vector<uint16_t> ciphersuite_codes;
3,314✔
1189

1190
   const std::string cipher_limit = m_args.get_string_opt_or_else("cipher", "");
6,628✔
1191
   if(cipher_limit ==
3,314✔
1192
      "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]") {
1193
      std::vector<std::string> suites = {
5✔
1194
         "ECDHE_RSA_WITH_AES_128_GCM_SHA256",
1195
         "ECDHE_RSA_WITH_AES_256_GCM_SHA384",
1196
         "ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
1197
         "ECDHE_RSA_WITH_AES_256_CBC_SHA",
1198
         "RSA_WITH_AES_256_GCM_SHA384",
1199
         "RSA_WITH_AES_256_CBC_SHA",
1200
      };
35✔
1201

1202
      for(const auto& suite_name : suites) {
35✔
1203
         const auto suite = Botan::TLS::Ciphersuite::from_name(suite_name);
30✔
1204
         if(!suite || !suite->valid()) {
30✔
1205
            shim_exit_with_error("Bad ciphersuite name " + suite_name);
×
1206
         }
1207
         ciphersuite_codes.push_back(suite->ciphersuite_code());
30✔
1208
      }
1209
   } else {
5✔
1210
      // Hack: go in reverse order to avoid preferring 3DES
1211
      auto ciphersuites = Botan::TLS::Ciphersuite::all_known_ciphersuites();
3,309✔
1212
      for(auto i = ciphersuites.rbegin(); i != ciphersuites.rend(); ++i) {
314,355✔
1213
         const auto suite = *i;
311,046✔
1214

1215
         // Can we use it?
1216
         if(suite.valid() == false || !suite.usable_in_version(version) ||
311,046✔
1217
            !Botan::value_exists(allowed_ciphers(), suite.cipher_algo())) {
507,625✔
1218
            continue;
140,215✔
1219
         }
1220

1221
         ciphersuite_codes.push_back(suite.ciphersuite_code());
170,831✔
1222
      }
1223
   }
3,309✔
1224

1225
   return ciphersuite_codes;
3,314✔
1226
}
3,314✔
1227

1228
class Shim_Credentials final : public Botan::Credentials_Manager {
1229
   public:
1230
      Shim_Credentials(const Shim_Arguments& args) : m_args(args) {
1,983✔
1231
         const auto psk_identity = m_args.get_string_opt_or_else("psk-identity", "");
3,966✔
1232
         const auto psk_str = m_args.get_string_opt_or_else("psk", "");
3,966✔
1233

1234
         if(!psk_identity.empty() || !psk_str.empty()) {
1,983✔
1235
            // If the shim received a -psk param but no -psk-identity param,
1236
            // we have to initialize the identity as "empty string".
1237
            m_psk_identity = psk_identity;
86✔
1238
         }
1239

1240
         if(!psk_str.empty()) {
1,983✔
1241
            m_psk = Botan::SymmetricKey(reinterpret_cast<const uint8_t*>(psk_str.data()), psk_str.size());
86✔
1242
         }
1243

1244
         if(m_args.option_used("key-file") && m_args.option_used("cert-file")) {
2,945✔
1245
            Botan::DataSource_Stream key_stream(m_args.get_string_opt("key-file"));
1,924✔
1246
            m_key.reset(Botan::PKCS8::load_key(key_stream).release());
962✔
1247

1248
            Botan::DataSource_Stream cert_stream(m_args.get_string_opt("cert-file"));
1,924✔
1249

1250
            while(!cert_stream.end_of_data()) {
2,892✔
1251
               try {
1,930✔
1252
                  m_cert_chain.push_back(Botan::X509_Certificate(cert_stream));
2,898✔
1253
               } catch(...) {}
962✔
1254
            }
1255
         }
962✔
1256
      }
1,983✔
1257

1258
      std::vector<Botan::Certificate_Store*> trusted_certificate_authorities(const std::string& type,
1,924✔
1259
                                                                             const std::string& context) override {
1260
         if(m_args.flag_set("server") && type != "tls-server") {
3,848✔
1261
            throw Shim_Exception("TLS server implementation asked for unexpected trusted CA type: " + type);
×
1262
         }
1263
         if(!m_args.flag_set("server") && type != "tls-client") {
3,848✔
1264
            throw Shim_Exception("TLS client implementation asked for unexpected trusted CA type: " + type);
×
1265
         }
1266

1267
         const auto expected_hostname = m_args.get_string_opt_or_else("host-name", "none");
3,848✔
1268
         if(expected_hostname != "none" && expected_hostname != context) {
1,924✔
1269
            throw Shim_Exception("Unexpected host name in trusted CA request: " + context);
×
1270
         }
1271

1272
         return Botan::Credentials_Manager::trusted_certificate_authorities(type, context);
1,924✔
1273
      }
1,924✔
1274

1275
      std::string psk_identity(const std::string& /*type*/,
48✔
1276
                               const std::string& /*context*/,
1277
                               const std::string& /*identity_hint*/) override {
1278
         return m_psk_identity.value_or("");
48✔
1279
      }
1280

1281
      std::string psk_identity_hint(const std::string& /*type*/, const std::string& /*context*/) override {
26✔
1282
         return m_psk_identity.value_or("");
26✔
1283
      }
1284

1285
      Botan::secure_vector<uint8_t> session_ticket_key() override {
1,695✔
1286
         return Botan::hex_decode_locked("ABCDEF0123456789");
1,695✔
1287
      }
1288

1289
      Botan::secure_vector<uint8_t> dtls_cookie_secret() override {
610✔
1290
         return Botan::hex_decode_locked("F00FB00FD00F100F700F");
610✔
1291
      }
1292

1293
      std::vector<Botan::TLS::ExternalPSK> find_preshared_keys(
1,004✔
1294
         std::string_view host,
1295
         Botan::TLS::Connection_Side whoami,
1296
         const std::vector<std::string>& identities = {},
1297
         const std::optional<std::string>& prf = std::nullopt) override {
1298
         if(!m_psk_identity.has_value()) {
1,004✔
1299
            return Botan::Credentials_Manager::find_preshared_keys(host, whoami, identities, prf);
898✔
1300
         }
1301

1302
         auto id_matches =
106✔
1303
            identities.empty() || std::find(identities.begin(), identities.end(), m_psk_identity) != identities.end();
106✔
1304

1305
         if(!id_matches) {
106✔
1306
            throw Shim_Exception("Unexpected PSK identity");
×
1307
         }
1308

1309
         if(!m_psk.has_value()) {
106✔
1310
            throw Shim_Exception("PSK identified but not set");
×
1311
         }
1312

1313
         std::vector<Botan::TLS::ExternalPSK> psks;
106✔
1314

1315
         // Currently, BoGo tests PSK with TLS 1.2 only. In TLS 1.2 the PRF does not
1316
         // need to be specified for PSKs.
1317
         //
1318
         // TODO: Once BoGo has tests for TLS 1.3 with externally provided PSKs, this
1319
         //       will need to be handled somehow.
1320
         const std::string psk_prf = "SHA-256";
106✔
1321
         psks.emplace_back(m_psk_identity.value(), psk_prf, m_psk->bits_of());
106✔
1322
         return psks;
106✔
1323
      }
106✔
1324

1325
      std::vector<Botan::X509_Certificate> cert_chain(
1,999✔
1326
         const std::vector<std::string>& cert_key_types,
1327
         const std::vector<Botan::AlgorithmIdentifier>& /*cert_signature_schemes*/,
1328
         const std::string& /*type*/,
1329
         const std::string& /*context*/) override {
1330
         if(m_args.flag_set("fail-cert-callback")) {
3,998✔
1331
            throw std::runtime_error("Simulating cert verify callback failure");
4✔
1332
         }
1333

1334
         if(m_key != nullptr && !m_cert_chain.empty()) {
1,995✔
1335
            for(const std::string& t : cert_key_types) {
3,125✔
1336
               if(t == m_key->algo_name()) {
2,045✔
1337
                  return m_cert_chain;
888✔
1338
               }
1339
            }
1340
         }
1341

1342
         return {};
1,995✔
1343
      }
1344

1345
      std::shared_ptr<Botan::Private_Key> private_key_for(const Botan::X509_Certificate& /*cert*/,
829✔
1346
                                                          const std::string& /*type*/,
1347
                                                          const std::string& /*context*/) override {
1348
         // assumes cert == m_cert
1349
         return m_key;
829✔
1350
      }
1351

1352
   private:
1353
      const Shim_Arguments& m_args;
1354
      std::optional<Botan::SymmetricKey> m_psk;
1355
      std::optional<std::string> m_psk_identity;
1356
      std::shared_ptr<Botan::Private_Key> m_key;
1357
      std::vector<Botan::X509_Certificate> m_cert_chain;
1358
};
1359

1360
class Shim_Callbacks final : public Botan::TLS::Callbacks {
2,580✔
1361
   public:
1362
      Shim_Callbacks(const Shim_Arguments& args, Shim_Socket& socket, Shim_Policy& policy) :
2,598✔
1363
            m_channel(nullptr),
2,598✔
1364
            m_args(args),
2,598✔
1365
            m_policy(policy),
2,598✔
1366
            m_socket(socket),
2,598✔
1367
            m_is_datagram(args.flag_set("dtls")),
2,598✔
1368
            m_warning_alerts(0),
2,598✔
1369
            m_empty_records(0),
2,598✔
1370
            m_sessions_established(0),
2,598✔
1371
            m_got_close(false),
2,598✔
1372
            m_hello_retry_request(false),
2,598✔
1373
            m_clock_skew(0) {}
5,196✔
1374

1375
      size_t sessions_established() const { return m_sessions_established; }
21✔
1376

1377
      void set_channel(Botan::TLS::Channel* channel) { m_channel = channel; }
2,596✔
1378

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

1381
      bool saw_close_notify() const { return m_got_close; }
27✔
1382

1383
      void tls_emit_data(std::span<const uint8_t> data) override {
15,862✔
1384
         shim_log("sending record of len " + std::to_string(data.size()));
31,724✔
1385

1386
         if(m_args.option_used("write-settings")) {
15,862✔
1387
            // TODO: the transcript option should probably be used differently
1388
            std::cout << ">>>" << std::endl << Botan::hex_encode(data) << std::endl << ">>>" << std::endl;
×
1389
         }
1390

1391
         if(m_is_datagram) {
15,862✔
1392
            std::vector<uint8_t> packet(data.size() + 5);
5,927✔
1393

1394
            packet[0] = 'P';
5,927✔
1395
            for(size_t i = 0; i != 4; ++i) {
29,635✔
1396
               packet[i + 1] = static_cast<uint8_t>((data.size() >> (24 - 8 * i)) & 0xFF);
23,708✔
1397
            }
1398
            std::memcpy(packet.data() + 5, data.data(), data.size());
5,927✔
1399

1400
            m_socket.write(packet.data(), packet.size());
5,927✔
1401
         } else {
5,927✔
1402
            m_socket.write(data.data(), data.size());
9,935✔
1403
         }
1404
      }
15,862✔
1405

1406
      std::vector<uint8_t> tls_provide_cert_status(const std::vector<Botan::X509_Certificate>&,
737✔
1407
                                                   const Botan::TLS::Certificate_Status_Request&) override {
1408
         if(m_args.flag_set("use-ocsp-callback") && m_args.flag_set("fail-ocsp-callback")) {
1,594✔
1409
            throw std::runtime_error("Simulating failure from OCSP response callback");
24✔
1410
         }
1411

1412
         if(m_args.flag_set("decline-ocsp-callback")) {
1,426✔
1413
            return {};
24✔
1414
         }
1415

1416
         if(m_args.option_used("ocsp-response")) {
689✔
1417
            return m_args.get_b64_opt("ocsp-response");
96✔
1418
         }
1419

1420
         return {};
713✔
1421
      }
1422

1423
      void tls_record_received(uint64_t /*seq_no*/, std::span<const uint8_t> data) override {
2,506✔
1424
         if(data.empty()) {
2,506✔
1425
            m_empty_records += 1;
98✔
1426
            if(m_empty_records > 32) {
98✔
1427
               shim_exit_with_error(":TOO_MANY_EMPTY_FRAGMENTS:");
2✔
1428
            }
1429
         } else {
1430
            m_empty_records = 0;
2,408✔
1431
         }
1432

1433
         shim_log("Reflecting application_data len " + std::to_string(data.size()));
5,008✔
1434

1435
         std::vector<uint8_t> buf(data.begin(), data.end());
2,504✔
1436
         for(auto& b : buf) {
1,183,219✔
1437
            b ^= 0xFF;
1,180,715✔
1438
         }
1439

1440
         m_channel->send(buf);
2,504✔
1441
      }
2,504✔
1442

1443
      bool tls_verify_message(const Botan::Public_Key& key,
1,003✔
1444
                              std::string_view padding,
1445
                              Botan::Signature_Format format,
1446
                              const std::vector<uint8_t>& msg,
1447
                              const std::vector<uint8_t>& sig) override {
1448
         if(m_args.option_used("expect-peer-signature-algorithm")) {
2,006✔
1449
            const Botan::TLS::Signature_Scheme scheme(
65✔
1450
               static_cast<uint16_t>(m_args.get_int_opt("expect-peer-signature-algorithm")));
65✔
1451

1452
            if(!scheme.is_available()) {
65✔
1453
               shim_exit_with_error(std::string("Unsupported signature scheme provided by BoGo: ") +
×
1454
                                    scheme.to_string());
×
1455
            }
1456

1457
            const std::string exp_padding = scheme.padding_string();
65✔
1458
            if(padding != exp_padding) {
130✔
1459
               shim_exit_with_error(Botan::fmt("Unexpected signature scheme got {} expected {}", padding, exp_padding));
×
1460
            }
1461
         }
65✔
1462

1463
         return Botan::TLS::Callbacks::tls_verify_message(key, padding, format, msg, sig);
1,003✔
1464
      }
1465

1466
      void tls_verify_cert_chain(const std::vector<Botan::X509_Certificate>& /*cert_chain*/,
1,169✔
1467
                                 const std::vector<std::optional<Botan::OCSP::Response>>& /*ocsp_responses*/,
1468
                                 const std::vector<Botan::Certificate_Store*>& /*trusted_roots*/,
1469
                                 Botan::Usage_Type /*usage*/,
1470
                                 std::string_view /*hostname*/,
1471
                                 const Botan::TLS::Policy& /*policy*/) override {
1472
         if(m_args.flag_set("enable-ocsp-stapling") && m_args.flag_set("use-ocsp-callback") &&
3,579✔
1473
            m_args.flag_set("fail-ocsp-callback")) {
1,313✔
1474
            throw Botan::TLS::TLS_Exception(Botan::TLS::Alert::BadCertificateStatusResponse,
48✔
1475
                                            "Simulated OCSP callback failure");
96✔
1476
         }
1477

1478
         if(m_args.flag_set("verify-fail")) {
1,121✔
1479
            auto alert = Botan::TLS::Alert::HandshakeFailure;
96✔
1480
            if(m_args.flag_set("use-custom-verify-callback")) {
192✔
1481
               alert = Botan::TLS::Alert::CertificateUnknown;
48✔
1482
            }
1483

1484
            throw Botan::TLS::TLS_Exception(alert, "Test requires rejecting cert");
96✔
1485
         }
1486
      }
1,025✔
1487

1488
      std::optional<Botan::OCSP::Response> tls_parse_ocsp_response(const std::vector<uint8_t>& raw_response) override {
73✔
1489
         if(m_args.option_used("expect-ocsp-response") && m_args.get_b64_opt("expect-ocsp-response") != raw_response) {
221✔
1490
            shim_exit_with_error("unexpected OCSP response");
×
1491
         }
1492

1493
         // Bogo uses invalid dummy OCSP responses. Don't even bother trying to
1494
         // decode them.
1495
         return std::nullopt;
73✔
1496
      }
1497

1498
      std::string tls_server_choose_app_protocol(const std::vector<std::string>& client_protos) override {
21✔
1499
         if(client_protos.empty()) {
21✔
1500
            return "";  // shouldn't happen?
×
1501
         }
1502

1503
         if(m_args.flag_set("reject-alpn")) {
21✔
1504
            throw Botan::TLS::TLS_Exception(Botan::TLS::Alert::NoApplicationProtocol,
3✔
1505
                                            "Rejecting ALPN request with alert");
6✔
1506
         }
1507

1508
         if(m_args.flag_set("decline-alpn")) {
18✔
1509
            return "";
6✔
1510
         }
1511

1512
         if(m_args.option_used("expect-advertised-alpn")) {
24✔
1513
            const std::vector<std::string> expected = m_args.get_alpn_string_vec_opt("expect-advertised-alpn");
12✔
1514

1515
            if(client_protos != expected) {
12✔
1516
               shim_exit_with_error("Bad ALPN from client");
×
1517
            }
1518
         }
12✔
1519

1520
         if(m_args.option_used("select-alpn")) {
12✔
1521
            return m_args.get_string_opt("select-alpn");
24✔
1522
         }
1523

1524
         return client_protos[0];  // if not configured just pick something
18✔
1525
      }
1526

1527
      void tls_alert(Botan::TLS::Alert alert) override {
1,866✔
1528
         if(alert.is_fatal()) {
1,866✔
1529
            shim_log("Got a fatal alert " + alert.type_string());
26✔
1530
         } else {
1531
            shim_log("Got a warning alert " + alert.type_string());
3,706✔
1532
         }
1533

1534
         if(alert.type() == Botan::TLS::Alert::RecordOverflow) {
1,866✔
1535
            shim_exit_with_error(":TLSV1_ALERT_RECORD_OVERFLOW:");
4✔
1536
         }
1537

1538
         if(alert.type() == Botan::TLS::Alert::DecompressionFailure) {
1,862✔
1539
            shim_exit_with_error(":SSLV3_ALERT_DECOMPRESSION_FAILURE:");
1✔
1540
         }
1541

1542
         if(!alert.is_fatal()) {
1,861✔
1543
            m_warning_alerts++;
1,853✔
1544
            if(m_warning_alerts > 5) {
1,853✔
1545
               shim_exit_with_error(":TOO_MANY_WARNING_ALERTS:");
3✔
1546
            }
1547
         }
1548

1549
         if(alert.type() == Botan::TLS::Alert::CloseNotify) {
1,858✔
1550
            if(m_got_close == false && !m_args.flag_set("shim-shuts-down")) {
3,660✔
1551
               shim_log("Sending return close notify");
1,803✔
1552
               m_channel->send_alert(alert);
1,803✔
1553
            }
1554
            m_got_close = true;
1,821✔
1555
         } else if(alert.is_fatal()) {
37✔
1556
            shim_exit_with_error("Unexpected fatal alert " + alert.type_string());
8✔
1557
         }
1558
      }
1,850✔
1559

1560
      void tls_session_established(const Botan::TLS::Session_Summary& session) override {
1,978✔
1561
         shim_log("Session established: " + Botan::hex_encode(session.session_id().get()) + " version " +
5,934✔
1562
                  session.version().to_string() + " cipher " + session.ciphersuite().to_string() + " EMS " +
11,868✔
1563
                  std::to_string(session.supports_extended_master_secret()));
1,978✔
1564
         // probably need tests here?
1565

1566
         m_policy.incr_session_established();
1,978✔
1567
         m_sessions_established++;
1,978✔
1568

1569
         if(m_args.flag_set("expect-no-session-id")) {
3,956✔
1570
            // BoGo expects that ticket issuance implies no stateful session...
1571
            if(!m_args.flag_set("server") && !session.session_id().empty()) {
112✔
1572
               shim_exit_with_error("Unexpectedly got a session ID");
×
1573
            }
1574
         } else if(m_args.flag_set("expect-session-id") && session.session_id().empty()) {
3,844✔
1575
            shim_exit_with_error("Unexpectedly got no session ID");
×
1576
         }
1577

1578
         if(m_args.option_used("expect-version")) {
1,978✔
1579
            if(session.version().version_code() != m_args.get_int_opt("expect-version")) {
×
1580
               shim_exit_with_error("Unexpected version");
×
1581
            }
1582
         }
1583

1584
         if(m_args.flag_set("expect-secure-renegotiation")) {
3,956✔
1585
            if(m_channel->secure_renegotiation_supported() == false) {
9✔
1586
               shim_exit_with_error("Expected secure renegotiation");
×
1587
            }
1588
         } else if(m_args.flag_set("expect-no-secure-renegotiation")) {
3,938✔
1589
            if(m_channel->secure_renegotiation_supported() == true) {
2✔
1590
               shim_exit_with_error("Expected no secure renegotation");
×
1591
            }
1592
         }
1593

1594
         if(m_args.flag_set("expect-extended-master-secret")) {
3,956✔
1595
            if(session.supports_extended_master_secret() == false) {
10✔
1596
               shim_exit_with_error("Expected extended maseter secret");
×
1597
            }
1598
         }
1599
      }
1,978✔
1600

1601
      void tls_session_activated() override {
1,967✔
1602
         if(m_args.flag_set("send-alert")) {
1,967✔
1603
            m_channel->send_fatal_alert(Botan::TLS::Alert::DecompressionFailure);
16✔
1604
            return;
16✔
1605
         }
1606

1607
         if(size_t length = m_args.get_int_opt_or_else("export-keying-material", 0)) {
3,902✔
1608
            const std::string label = m_args.get_string_opt("export-label");
188✔
1609
            const std::string context = m_args.get_string_opt("export-context");
188✔
1610
            const auto exported = m_channel->key_material_export(label, context, length);
188✔
1611
            shim_log("Sending " + std::to_string(length) + " bytes of key material");
376✔
1612
            m_channel->send(exported.bits_of());
376✔
1613
         }
188✔
1614

1615
         const std::string alpn = m_channel->application_protocol();
1,951✔
1616

1617
         if(m_args.option_used("expect-alpn")) {
1,951✔
1618
            if(alpn != m_args.get_string_opt("expect-alpn")) {
10✔
1619
               shim_exit_with_error("Got unexpected ALPN");
×
1620
            }
1621
         }
1622

1623
         if(alpn == "baz" && !m_args.flag_set("allow-unknown-alpn-protos")) {
1,960✔
1624
            throw Botan::TLS::TLS_Exception(Botan::TLS::Alert::IllegalParameter, "Unexpected ALPN protocol");
3✔
1625
         }
1626

1627
         if(m_args.flag_set("shim-shuts-down")) {
1,948✔
1628
            shim_log("Shim shutting down");
45✔
1629
            m_channel->close();
45✔
1630
         }
1631

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

1635
            std::vector<uint8_t> buf(32769, 0x42);
×
1636

1637
            for(size_t sz : record_sizes) {
×
1638
               m_channel->send(buf.data(), sz);
×
1639
            }
1640

1641
            m_channel->close();
×
1642
         }
×
1643

1644
         if(m_args.flag_set("expect-hrr") && !m_hello_retry_request) {
3,896✔
1645
            throw Shim_Exception("Expected Hello Retry Request but didn't see one");
×
1646
         }
1647

1648
         if(m_args.flag_set("expect-no-hrr") && m_hello_retry_request) {
3,896✔
1649
            throw Shim_Exception("Hello Retry Request seen but didn't expect one");
×
1650
         }
1651

1652
         if(m_args.flag_set("key-update")) {
1,948✔
1653
            shim_log("Updating traffic keys without asking for reciprocation");
5✔
1654
            m_channel->update_traffic_keys(false /* don't request reciprocal update */);
2✔
1655
         }
1656
      }
1,948✔
1657

1658
      std::chrono::system_clock::time_point tls_current_timestamp() override {
8,573✔
1659
         // Some tests require precise timings. Hence, the TLS 'now' timestamp
1660
         // is frozen on first access and rounded to the last full second. E.g.
1661
         // storage of sessions does store the timestamp with second-resolution.
1662
         using sec = std::chrono::seconds;
8,573✔
1663
         static auto g_now = std::chrono::floor<sec>(std::chrono::system_clock::now());
10,484✔
1664
         return g_now + m_clock_skew;
8,573✔
1665
      }
1666

1667
      void tls_inspect_handshake_msg(const Botan::TLS::Handshake_Message& msg) override {
20,301✔
1668
         if(msg.type() == Botan::TLS::Handshake_Type::HelloRetryRequest) {
20,301✔
1669
            m_hello_retry_request = true;
67✔
1670
         }
1671
      }
20,301✔
1672

1673
   private:
1674
      Botan::TLS::Channel* m_channel;
1675
      const Shim_Arguments& m_args;
1676
      Shim_Policy& m_policy;
1677
      Shim_Socket& m_socket;
1678
      const bool m_is_datagram;
1679
      size_t m_warning_alerts;
1680
      size_t m_empty_records;
1681
      size_t m_sessions_established;
1682
      bool m_got_close;
1683
      bool m_hello_retry_request;
1684
      std::chrono::seconds m_clock_skew;
1685
};
1686

1687
}  // namespace
1688

1689
int main(int /*argc*/, char* argv[]) {
1,984✔
1690
   try {
1,984✔
1691
      std::unique_ptr<Shim_Arguments> args = parse_options(argv);
1,984✔
1692

1693
      if(args->flag_set("is-handshaker-supported")) {
3,968✔
1694
         return shim_output("No\n");
1✔
1695
      }
1696

1697
      const uint16_t port = static_cast<uint16_t>(args->get_int_opt("port"));
1,983✔
1698
      const size_t resume_count = args->get_int_opt_or_else("resume-count", 0);
1,983✔
1699
      const bool is_server = args->flag_set("server");
1,983✔
1700
      const bool is_datagram = args->flag_set("dtls");
1,983✔
1701
      const size_t buf_size = args->get_int_opt_or_else("read-size", 18 * 1024);
1,983✔
1702

1703
      auto rng = std::make_shared<Botan::ChaCha_RNG>(Botan::secure_vector<uint8_t>(64));
3,966✔
1704
      auto creds = std::make_shared<Shim_Credentials>(*args);
1,983✔
1705
      auto session_manager = [&]() -> std::shared_ptr<Botan::TLS::Session_Manager> {
3,966✔
1706
         if(args->flag_set("no-ticket") || args->flag_set("on-resume-no-ticket")) {
3,964✔
1707
            // The in-memory session manager stores sessions in volatile memory and
1708
            // hands out Session_IDs (i.e. does not utilize session tickets)
1709
            return std::make_shared<Botan::TLS::Session_Manager_In_Memory>(rng, 1024);
2✔
1710
         } else {
1711
            // The hybrid session manager prefers stateless tickets (when used in
1712
            // servers) but can also fall back to stateful management when tickets
1713
            // are not an option.
1714
            return std::make_shared<Botan::TLS::Session_Manager_Hybrid>(
1,981✔
1715
               std::make_unique<Botan::TLS::Session_Manager_In_Memory>(rng, 1024), creds, rng);
3,962✔
1716
         }
1717
      }();
2,716✔
1718

1719
      if(args->flag_set("wait-for-debugger")) {
4,699✔
1720
         sleep(20);
×
1721
      }
1722

1723
      for(size_t i = 0; i != resume_count + 1; ++i) {
3,830✔
1724
         auto execute_test = [&](const std::string& hostname) {
5,196✔
1725
            Shim_Socket socket(hostname, port, args->flag_set("ipv6"));
5,199✔
1726

1727
            shim_log("Connection " + std::to_string(i + 1) + "/" + std::to_string(resume_count + 1));
5,196✔
1728

1729
            // The ShimID must be written on the socket as a 64-bit little-endian integer
1730
            // *before* any test data is transferred
1731
            // See: https://github.com/google/boringssl/commit/50ee09552cde1c2019bef24520848d041920cfd4
1732
            shim_log("Sending ShimID: " + std::to_string(args->get_int_opt("shim-id")));
5,196✔
1733
            std::array<uint8_t, 8> shim_id;
2,598✔
1734
            Botan::store_le(static_cast<uint64_t>(args->get_int_opt("shim-id")), shim_id.data());
3,331✔
1735
            socket.write(shim_id.data(), shim_id.size());
2,598✔
1736

1737
            auto policy = std::make_shared<Shim_Policy>(*args);
2,598✔
1738
            auto callbacks = std::make_shared<Shim_Callbacks>(*args, socket, *policy);
2,598✔
1739

1740
            if(args->option_used("resumption-delay") && i > 0) {
5,196✔
1741
               shim_log("skewing the clock by " + std::to_string(args->get_int_opt("resumption-delay")) + " seconds");
6✔
1742
               callbacks->set_clock_skew(std::chrono::seconds(args->get_int_opt("resumption-delay")));
739✔
1743
            }
1744

1745
            std::unique_ptr<Botan::TLS::Channel> chan;
2,598✔
1746

1747
            if(is_server) {
2,598✔
1748
               chan = std::make_unique<Botan::TLS::Server>(callbacks, session_manager, creds, policy, rng, is_datagram);
2,598✔
1749
            } else {
1750
               Botan::TLS::Protocol_Version offer_version = policy->latest_supported_version(is_datagram);
1,428✔
1751
               shim_log("Offering " + offer_version.to_string());
2,852✔
1752

1753
               std::string host_name = args->get_string_opt_or_else("host-name", hostname);
1,426✔
1754
               if(args->test_name().find("UnsolicitedServerNameAck") == 0) {
2,824✔
1755
                  host_name = "";  // avoid sending SNI for this test
3✔
1756
               }
1757

1758
               Botan::TLS::Server_Information server_info(host_name, port);
1,426✔
1759
               const std::vector<std::string> next_protocols = args->get_alpn_string_vec_opt("advertise-alpn");
1,426✔
1760
               chan = std::make_unique<Botan::TLS::Client>(
1,426✔
1761
                  callbacks, session_manager, creds, policy, rng, server_info, offer_version, next_protocols);
1,426✔
1762
            }
1,426✔
1763

1764
            callbacks->set_channel(chan.get());
2,596✔
1765

1766
            std::vector<uint8_t> buf(buf_size);
3,329✔
1767

1768
            for(;;) {
167,201✔
1769
               if(is_datagram) {
167,201✔
1770
                  uint8_t opcode;
127,018✔
1771
                  size_t got = socket.read(&opcode, 1);
127,018✔
1772
                  if(got == 0) {
127,018✔
1773
                     shim_log("EOF on socket");
571✔
1774
                     break;
571✔
1775
                  }
1776

1777
                  if(opcode == 'P') {
126,447✔
1778
                     uint8_t len_bytes[4];
126,447✔
1779
                     socket.read_exactly(len_bytes, sizeof(len_bytes));
126,447✔
1780

1781
                     size_t packet_len = Botan::load_be<uint32_t>(len_bytes, 0);
126,447✔
1782

1783
                     if(buf.size() < packet_len) {
126,447✔
1784
                        buf.resize(packet_len);
1✔
1785
                     }
1786
                     socket.read_exactly(buf.data(), packet_len);
126,447✔
1787

1788
                     chan->received_data(buf.data(), packet_len);
126,447✔
1789
                  } else if(opcode == 'T') {
×
1790
                     uint8_t timeout_ack = 't';
×
1791

1792
                     uint8_t timeout_bytes[8];
×
1793
                     socket.read_exactly(timeout_bytes, sizeof(timeout_bytes));
×
1794

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

1797
                     shim_log("Timeout nsec " + std::to_string(nsec));
×
1798

1799
                     // FIXME handle this!
1800

1801
                     socket.write(&timeout_ack, 1);  // ack it anyway
×
1802
                  } else {
1803
                     shim_exit_with_error("Unknown opcode " + std::to_string(opcode));
×
1804
                  }
1805
               } else {
1806
                  size_t got = socket.read(buf.data(), buf.size());
40,183✔
1807
                  if(got == 0) {
40,183✔
1808
                     shim_log("EOF on socket");
1,277✔
1809
                     break;
1,277✔
1810
                  }
1811

1812
                  shim_log("Got packet of " + std::to_string(got));
77,812✔
1813

1814
                  if(args->option_used("write-settings")) {
38,906✔
1815
                     // TODO: the transcript option should probably be used differently
1816
                     std::cout << "<<<" << std::endl
×
1817
                               << Botan::hex_encode(buf.data(), got) << std::endl
×
1818
                               << "<<<" << std::endl;
×
1819
                  }
1820

1821
                  if(args->flag_set("use-exporter-between-reads") && chan->is_active()) {
77,812✔
1822
                     chan->key_material_export("some label", "some context", 42);
3✔
1823
                  }
1824
                  const size_t needed = chan->received_data(buf.data(), got);
38,905✔
1825

1826
                  if(needed) {
38,278✔
1827
                     shim_log("Short read still need " + std::to_string(needed));
47,034✔
1828
                  }
1829
               }
1830
            }
1831

1832
            if(args->flag_set("check-close-notify")) {
3,696✔
1833
               if(!callbacks->saw_close_notify()) {
27✔
1834
                  throw Shim_Exception("Unexpected SSL_shutdown result: -1 != 1");
1✔
1835
               }
1836
            }
1837

1838
            if(args->option_used("expect-total-renegotiations")) {
3,694✔
1839
               const size_t exp = args->get_int_opt("expect-total-renegotiations");
21✔
1840

1841
               if(exp != callbacks->sessions_established() - 1) {
21✔
1842
                  throw Shim_Exception("Unexpected number of renegotiations: saw " +
×
1843
                                       std::to_string(callbacks->sessions_established() - 1) + " exp " +
×
1844
                                       std::to_string(exp));
×
1845
               }
1846
            }
1847
            shim_log("End of resume loop");
4,425✔
1848
         };
10,318✔
1849
         try {
2,598✔
1850
            execute_test("localhost");
5,178✔
1851
         } catch(const Shim_Exception& e) {
733✔
1852
            if(std::string(e.what()) == "Failed to connect to host") {
2✔
1853
               execute_test("::1");
×
1854
            } else {
1855
               // NOLINTNEXTLINE(cert-err60-cpp)
1856
               throw e;
1✔
1857
            }
1858
         }
1✔
1859
      }
1860
   } catch(Shim_Exception& e) {
6,629✔
1861
      shim_exit_with_error(e.what(), e.rc());
1✔
1862
   } catch(std::exception& e) {
732✔
1863
      shim_exit_with_error(map_to_bogo_error(e.what()));
732✔
1864
   } catch(...) {
×
1865
      shim_exit_with_error("Unknown exception", 3);
×
1866
   }
×
1867
   return 0;
1,232✔
1868
}
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