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

randombit / botan / 19012754211

02 Nov 2025 01:10PM UTC coverage: 90.677% (+0.006%) from 90.671%
19012754211

push

github

web-flow
Merge pull request #5137 from randombit/jack/clang-tidy-includes

Remove various unused includes flagged by clang-tidy misc-include-cleaner

100457 of 110786 relevant lines covered (90.68%)

12189873.8 hits per line

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

71.56
/src/cli/tls_client.cpp
1
/*
2
* (C) 2014,2015 Jack Lloyd
3
*     2016 Matthias Gierlings
4
*     2017 René Korthaus, Rohde & Schwarz Cybersecurity
5
*     2022 René Meusel, Hannes Rantzsch - neXenio GmbH
6
*     2023 René Meusel, Rohde & Schwarz Cybersecurity
7
*
8
* Botan is released under the Simplified BSD License (see license.txt)
9
*/
10

11
#include "cli.h"
12

13
#include <botan/internal/target_info.h>
14

15
#if defined(BOTAN_HAS_TLS) && defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) && defined(BOTAN_TARGET_OS_HAS_SOCKETS)
16

17
   #include <botan/hex.h>
18
   #include <botan/ocsp.h>
19
   #include <botan/tls_callbacks.h>
20
   #include <botan/tls_client.h>
21
   #include <botan/tls_exceptn.h>
22
   #include <botan/tls_policy.h>
23
   #include <botan/tls_session_manager_memory.h>
24
   #include <botan/x509path.h>
25

26
   #if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER)
27
      #include <botan/tls_session_manager_sqlite.h>
28
   #endif
29

30
   #include <memory>
31
   #include <string>
32

33
   #include "socket_utils.h"
34
   #include "tls_helpers.h"
35

36
namespace Botan_CLI {
37

38
class TLS_Client;
39

40
namespace {
41

42
class Callbacks : public Botan::TLS::Callbacks {
10✔
43
   public:
44
      explicit Callbacks(TLS_Client& client_command) : m_client_command(client_command), m_peer_closed(false) {}
10✔
45

46
      std::ostream& output();
47
      bool flag_set(const std::string& flag_name) const;
48
      std::string get_arg(const std::string& arg_name) const;
49
      void send(std::span<const uint8_t> buffer);
50

51
      bool peer_closed() const { return m_peer_closed; }
1✔
52

53
      void tls_verify_cert_chain(const std::vector<Botan::X509_Certificate>& cert_chain,
7✔
54
                                 const std::vector<std::optional<Botan::OCSP::Response>>& ocsp,
55
                                 const std::vector<Botan::Certificate_Store*>& trusted_roots,
56
                                 Botan::Usage_Type usage,
57
                                 std::string_view hostname,
58
                                 const Botan::TLS::Policy& policy) override {
59
         if(cert_chain.empty()) {
7✔
60
            throw Botan::Invalid_Argument("Certificate chain was empty");
×
61
         }
62

63
         Botan::Path_Validation_Restrictions restrictions(policy.require_cert_revocation_info(),
7✔
64
                                                          policy.minimum_signature_strength());
21✔
65

66
         auto ocsp_timeout = std::chrono::milliseconds(1000);
7✔
67

68
         const std::string checked_name = flag_set("skip-hostname-check") ? "" : std::string(hostname);
21✔
69

70
         Botan::Path_Validation_Result result = Botan::x509_path_validate(
7✔
71
            cert_chain, restrictions, trusted_roots, checked_name, usage, tls_current_timestamp(), ocsp_timeout, ocsp);
7✔
72

73
         if(result.successful_validation()) {
7✔
74
            output() << "Certificate validation status: " << result.result_string() << "\n";
14✔
75
            const auto& status = result.all_statuses();
7✔
76

77
            if(!status.empty() && status[0].contains(Botan::Certificate_Status_Code::OCSP_RESPONSE_GOOD)) {
14✔
78
               output() << "Valid OCSP response for this server\n";
×
79
            }
80
         } else {
81
            if(flag_set("ignore-cert-error")) {
×
82
               output() << "Certificate validation status: " << result.result_string() << "\n";
×
83
            } else {
84
               throw Botan::TLS::TLS_Exception(Botan::TLS::Alert::BadCertificate,
×
85
                                               "Certificate validation failure: " + result.result_string());
×
86
            }
87
         }
88
      }
7✔
89

90
      void tls_verify_raw_public_key(const Botan::Public_Key& raw_public_key,
×
91
                                     Botan::Usage_Type /* usage */,
92
                                     std::string_view /* hostname */,
93
                                     const Botan::TLS::Policy& /* policy */) override {
94
         const auto fingerprint = raw_public_key.fingerprint_public("SHA-256");
×
95
         const auto trusted = (fingerprint == get_arg("trusted-pubkey-sha256"));
×
96
         output() << "Raw Public Key (" << fingerprint
×
97
                  << ") validation status: " << (trusted ? "trusted" : "NOT trusted") << "\n";
×
98
      }
×
99

100
      void tls_session_activated() override { output() << "Handshake complete\n"; }
9✔
101

102
      void tls_session_established(const Botan::TLS::Session_Summary& session) override {
9✔
103
         output() << "Handshake complete, " << session.version().to_string() << "\n";
18✔
104

105
         if(const auto& psk = session.external_psk_identity()) {
9✔
106
            output() << "Utilized PSK identity: " << maybe_hex_encode(psk.value()) << "\n";
6✔
107
         }
108

109
         output() << "Negotiated ciphersuite " << session.ciphersuite().to_string() << "\n";
18✔
110

111
         if(auto kex_params = session.kex_parameters()) {
9✔
112
            output() << "Key exchange using " << *kex_params << "\n";
6✔
113
         }
×
114

115
         if(const auto& session_id = session.session_id(); !session_id.empty()) {
9✔
116
            output() << "Session ID " << Botan::hex_encode(session_id.get()) << "\n";
18✔
117
         }
118

119
         if(const auto& session_ticket = session.session_ticket()) {
9✔
120
            output() << "Session ticket " << Botan::hex_encode(session_ticket->get()) << "\n";
×
121
         }
122

123
         if(flag_set("print-certs")) {
18✔
124
            const std::vector<Botan::X509_Certificate>& certs = session.peer_certs();
125

126
            for(size_t i = 0; i != certs.size(); ++i) {
×
127
               output() << "Certificate " << i + 1 << "/" << certs.size() << "\n";
×
128
               output() << certs[i].to_string();
×
129
               output() << certs[i].PEM_encode();
×
130
            }
131
         }
132
         output() << std::flush;
9✔
133
      }
9✔
134

135
      void tls_emit_data(std::span<const uint8_t> buf) override {
47✔
136
         if(flag_set("debug")) {
94✔
137
            output() << "<< " << Botan::hex_encode(buf) << "\n";
×
138
         }
139

140
         send(buf);
94✔
141
      }
47✔
142

143
      void tls_alert(Botan::TLS::Alert alert) override { output() << "Alert: " << alert.type_string() << "\n"; }
3✔
144

145
      void tls_record_received(uint64_t /*seq_no*/, std::span<const uint8_t> buf) override {
12✔
146
         for(const auto c : buf) {
2,064✔
147
            output() << c;
2,052✔
148
         }
149
         output() << std::flush;
12✔
150
      }
12✔
151

152
      std::vector<uint8_t> tls_sign_message(const Botan::Private_Key& key,
×
153
                                            Botan::RandomNumberGenerator& rng,
154
                                            const std::string_view padding,
155
                                            Botan::Signature_Format format,
156
                                            const std::vector<uint8_t>& msg) override {
157
         output() << "Performing client authentication\n";
×
158
         return Botan::TLS::Callbacks::tls_sign_message(key, rng, padding, format, msg);
×
159
      }
160

161
      bool tls_peer_closed_connection() override {
×
162
         m_peer_closed = true;
×
163
         return Botan::TLS::Callbacks::tls_peer_closed_connection();
×
164
      }
165

166
   private:
167
      TLS_Client& m_client_command;
168
      bool m_peer_closed;
169
};
170

171
}  // namespace
172

173
class TLS_Client final : public Command {
174
   public:
175
      TLS_Client() :
11✔
176
            Command(
177
               "tls_client host --port=443 --print-certs --policy=default "
178
               "--skip-system-cert-store --trusted-cas= --trusted-pubkey-sha256= "
179
               "--skip-hostname-check --ignore-cert-error "
180
               "--tls-version=default --session-db= --session-db-pass= "
181
               "--next-protocols= --type=tcp --client-cert= --client-cert-key= "
182
               "--psk= --psk-identity= --psk-prf=SHA-256 --debug") {
22✔
183
         init_sockets();
11✔
184
      }
11✔
185

186
      ~TLS_Client() override { stop_sockets(); }
11✔
187

188
      TLS_Client(const TLS_Client& other) = delete;
189
      TLS_Client(TLS_Client&& other) = delete;
190
      TLS_Client& operator=(const TLS_Client& other) = delete;
191
      TLS_Client& operator=(TLS_Client&& other) = delete;
192

193
      std::string group() const override { return "tls"; }
1✔
194

195
      std::string description() const override { return "Connect to a host using TLS/DTLS"; }
1✔
196

197
      void go() override {
10✔
198
         std::shared_ptr<Botan::TLS::Session_Manager> session_mgr;
10✔
199

200
         auto callbacks = std::make_shared<Callbacks>(*this);
10✔
201

202
         const std::string sessions_db = get_arg("session-db");
10✔
203
         const std::string host = get_arg("host");
10✔
204
         const uint16_t port = get_arg_u16("port");
10✔
205
         const std::string transport = get_arg("type");
10✔
206
         const std::string next_protos = get_arg("next-protocols");
10✔
207
         const bool use_system_cert_store = !flag_set("skip-system-cert-store");
10✔
208
         const std::string trusted_CAs = get_arg("trusted-cas");
10✔
209
         const auto tls_version = get_arg("tls-version");
10✔
210

211
         if(!sessions_db.empty()) {
10✔
212
   #if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER)
213
            const std::string sessions_passphrase = get_passphrase_arg("Session DB passphrase", "session-db-pass");
×
214
            session_mgr =
×
215
               std::make_shared<Botan::TLS::Session_Manager_SQLite>(sessions_passphrase, rng_as_shared(), sessions_db);
×
216
   #else
217
            error_output() << "Ignoring session DB file, sqlite not enabled\n";
218
   #endif
219
         }
×
220

221
         if(!session_mgr) {
10✔
222
            session_mgr = std::make_shared<Botan::TLS::Session_Manager_In_Memory>(rng_as_shared());
30✔
223
         }
224

225
         auto policy = load_tls_policy(get_arg("policy"));
20✔
226

227
         if(transport != "tcp" && transport != "udp") {
10✔
228
            throw CLI_Usage_Error("Invalid transport type '" + transport + "' for TLS");
×
229
         }
230

231
         const std::vector<std::string> protocols_to_offer = Command::split_on(next_protos, ',');
10✔
232

233
         if(!policy) {
10✔
234
            policy = std::make_shared<Botan::TLS::Policy>();
×
235
         }
236

237
         const bool use_tcp = (transport == "tcp");
10✔
238
         Botan::TLS::Protocol_Version version = policy->latest_supported_version(!use_tcp);
10✔
239

240
         if(tls_version != "default") {
10✔
241
            if(tls_version == "1.2") {
10✔
242
               version = use_tcp ? Botan::TLS::Protocol_Version::TLS_V12 : Botan::TLS::Protocol_Version::DTLS_V12;
3✔
243
            } else if(tls_version == "1.3") {
7✔
244
               version = use_tcp ? Botan::TLS::Protocol_Version::TLS_V13 : Botan::TLS::Protocol_Version::DTLS_V13;
7✔
245
            } else {
246
               error_output() << "Unknown TLS protocol version " << tls_version << '\n';
×
247
            }
248
         }
249

250
         m_sockfd = connect_to_host(host, port, use_tcp);
10✔
251

252
         const auto client_crt_path = get_arg_maybe("client-cert");
10✔
253
         const auto client_key_path = get_arg_maybe("client-cert-key");
10✔
254

255
         auto psk = [this]() -> std::optional<Botan::secure_vector<uint8_t>> {
×
256
            auto psk_hex = get_arg_maybe("psk");
10✔
257
            if(psk_hex) {
10✔
258
               return Botan::hex_decode_locked(psk_hex.value());
2✔
259
            } else {
260
               return {};
8✔
261
            }
262
         }();
20✔
263
         const std::optional<std::string> psk_identity = get_arg_maybe("psk-identity");
10✔
264
         const std::optional<std::string> psk_prf = get_arg_maybe("psk-prf");
10✔
265

266
         auto creds = std::make_shared<Basic_Credentials_Manager>(use_system_cert_store,
10✔
267
                                                                  trusted_CAs,
268
                                                                  client_crt_path,
269
                                                                  client_key_path,
270
                                                                  std::move(psk),
271
                                                                  psk_identity,
272
                                                                  psk_prf);
10✔
273

274
         Botan::TLS::Client client(callbacks,
10✔
275
                                   session_mgr,
276
                                   creds,
277
                                   policy,
278
                                   rng_as_shared(),
10✔
279
                                   Botan::TLS::Server_Information(host, port),
10✔
280
                                   version,
281
                                   protocols_to_offer);
40✔
282

283
         bool first_active = true;
10✔
284
         bool we_closed = false;
10✔
285

286
         while(!client.is_closed()) {
56✔
287
            fd_set readfds;
288
            FD_ZERO(&readfds);
935✔
289
            FD_SET(m_sockfd, &readfds);
55✔
290

291
            if(client.is_active()) {
55✔
292
               FD_SET(STDIN_FILENO, &readfds);
31✔
293
               if(first_active && !protocols_to_offer.empty()) {
31✔
294
                  std::string app = client.application_protocol();
×
295
                  if(!app.empty()) {
×
296
                     output() << "Server choose protocol: " << client.application_protocol() << "\n";
×
297
                  }
298
                  first_active = false;
×
299
               }
×
300
            }
301

302
            struct timeval timeout = {1, 0};
55✔
303

304
            ::select(static_cast<int>(m_sockfd + 1), &readfds, nullptr, nullptr, &timeout);
55✔
305

306
            if(FD_ISSET(m_sockfd, &readfds)) {
55✔
307
               uint8_t buf[4 * 1024] = {0};
38✔
308

309
               ssize_t got = ::read(m_sockfd, buf, sizeof(buf));
38✔
310

311
               if(got == 0) {
38✔
312
                  output() << "EOF on socket\n";
×
313
                  break;
×
314
               } else if(got == -1) {
38✔
315
                  output() << "Socket error: " << errno << " " << err_to_string(errno) << "\n";
×
316
                  continue;
×
317
               }
318

319
               if(flag_set("debug")) {
38✔
320
                  output() << ">> " << Botan::hex_encode(buf, got) << "\n";
×
321
               }
322

323
               client.received_data(buf, got);
38✔
324
            }
325

326
            if(FD_ISSET(STDIN_FILENO, &readfds)) {
55✔
327
               uint8_t buf[1024] = {0};
18✔
328
               ssize_t got = read(STDIN_FILENO, buf, sizeof(buf));
18✔
329

330
               if(got == 0) {
18✔
331
                  output() << "EOF on stdin\n";
9✔
332
                  client.close();
9✔
333
                  we_closed = true;
9✔
334
                  break;
9✔
335
               } else if(got == -1) {
9✔
336
                  output() << "Stdin error: " << errno << " " << err_to_string(errno) << "\n";
×
337
                  continue;
×
338
               }
339

340
               if(got == 2 && buf[1] == '\n') {
9✔
341
                  char cmd = buf[0];
×
342

343
                  if(cmd == 'R' || cmd == 'r') {
×
344
                     output() << "Client initiated renegotiation\n";
×
345
                     client.renegotiate(cmd == 'R');
×
346
                  } else if(cmd == 'Q') {
×
347
                     output() << "Client initiated close\n";
×
348
                     client.close();
×
349
                     we_closed = true;
350
                  }
351
               } else {
352
                  client.send(buf, got);
9✔
353
               }
354
            }
355

356
            if(client.timeout_check()) {
46✔
357
               output() << "Timeout detected\n";
×
358
            }
359
         }
360

361
         set_return_code((we_closed || callbacks->peer_closed()) ? 0 : 1);
19✔
362

363
         ::close(m_sockfd);
10✔
364
      }
62✔
365

366
   public:
367
      using Command::flag_set;
368
      using Command::get_arg;
369
      using Command::output;
370

371
      void send(std::span<const uint8_t> buf) const {
47✔
372
         while(!buf.empty()) {
94✔
373
            ssize_t sent = ::send(m_sockfd, buf.data(), buf.size(), MSG_NOSIGNAL);
47✔
374

375
            if(sent == -1) {
47✔
376
               if(errno == EINTR) {
×
377
                  sent = 0;
378
               } else {
379
                  throw CLI_Error("Socket write failed errno=" + std::to_string(errno));
×
380
               }
381
            }
382

383
            buf = buf.subspan(sent);
47✔
384
         }
385
      }
47✔
386

387
   private:
388
      static socket_type connect_to_host(const std::string& host, uint16_t port, bool tcp) {
10✔
389
         addrinfo hints{};
10✔
390
         std::memset(&hints, 0, sizeof(hints));
10✔
391
         hints.ai_family = AF_UNSPEC;
10✔
392
         hints.ai_socktype = tcp ? SOCK_STREAM : SOCK_DGRAM;
10✔
393
         addrinfo* res = nullptr;
10✔
394

395
         if(::getaddrinfo(host.c_str(), std::to_string(port).c_str(), &hints, &res) != 0) {
10✔
396
            throw CLI_Error("getaddrinfo failed for " + host);
×
397
         }
398

399
         socket_type fd = 0;
10✔
400
         bool success = false;
10✔
401

402
         for(addrinfo* rp = res; rp != nullptr; rp = rp->ai_next) {
20✔
403
            fd = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
20✔
404

405
            if(fd == invalid_socket()) {
20✔
406
               continue;
×
407
            }
408

409
            if(::connect(fd, rp->ai_addr, rp->ai_addrlen) != 0) {
20✔
410
               ::close(fd);
10✔
411
               continue;
10✔
412
            }
413

414
            success = true;
415
            break;
416
         }
417

418
         ::freeaddrinfo(res);
10✔
419

420
         if(!success) {
10✔
421
            // no address succeeded
422
            throw CLI_Error("Connecting to host failed");
×
423
         }
424

425
         return fd;
10✔
426
      }
427

428
      static void dgram_socket_write(int sockfd, const uint8_t buf[], size_t length) {
429
         auto r = ::send(sockfd, buf, length, MSG_NOSIGNAL);
430

431
         if(r == -1) {
432
            throw CLI_Error("Socket write failed errno=" + std::to_string(errno));
433
         }
434
      }
435

436
      socket_type m_sockfd = invalid_socket();
437
};
438

439
namespace {
440

441
std::ostream& Callbacks::output() {
2,125✔
442
   return m_client_command.output();
2,125✔
443
}
444

445
bool Callbacks::flag_set(const std::string& flag_name) const {
63✔
446
   return m_client_command.flag_set(flag_name);
63✔
447
}
448

449
std::string Callbacks::get_arg(const std::string& arg_name) const {
×
450
   return m_client_command.get_arg(arg_name);
×
451
}
452

453
void Callbacks::send(std::span<const uint8_t> buffer) {
47✔
454
   m_client_command.send(buffer);
47✔
455
}
456

457
}  // namespace
458

459
BOTAN_REGISTER_COMMAND("tls_client", TLS_Client);
11✔
460

461
}  // namespace Botan_CLI
462

463
#endif
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc