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

randombit / botan / 16094367594

06 Jul 2025 02:24AM UTC coverage: 90.574%. Remained the same
16094367594

push

github

web-flow
Merge pull request #4959 from randombit/jack/fix-clang-tidy-cppcoreguidelines-init-variables

Enable and fix clang-tidy warning cppcoreguidelines-init-variables

99051 of 109359 relevant lines covered (90.57%)

12385300.74 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
   #include <fstream>
26

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

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

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

37
namespace Botan_CLI {
38

39
class TLS_Client;
40

41
namespace {
42

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

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

52
      int peer_closed() const { return m_peer_closed; }
1✔
53

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

172
}  // namespace
173

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

287
         while(!client.is_closed()) {
52✔
288
            fd_set readfds;
289
            FD_ZERO(&readfds);
867✔
290
            FD_SET(m_sockfd, &readfds);
51✔
291

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

303
            struct timeval timeout = {1, 0};
51✔
304

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

307
            if(FD_ISSET(m_sockfd, &readfds)) {
51✔
308
               uint8_t buf[4 * 1024] = {0};
35✔
309

310
               ssize_t got = ::read(m_sockfd, buf, sizeof(buf));
35✔
311

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

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

324
               client.received_data(buf, got);
35✔
325
            }
326

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

415
            success = true;
416
            break;
417
         }
418

419
         ::freeaddrinfo(res);
10✔
420

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

426
         return fd;
10✔
427
      }
428

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

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

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

440
namespace {
441

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

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

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

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

458
}  // namespace
459

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

462
}  // namespace Botan_CLI
463

464
#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