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

randombit / botan / 35178316236

16 Sep 2026 08:38PM UTC coverage: 89.698% (-2.3%) from 92.034%
35178316236

push

github

web-flow
Merge pull request #5944 from reneme/rene/remove_unnecessary_unicode

Remove unnecessary Unicode characters

123966 of 138204 relevant lines covered (89.7%)

9445051.13 hits per line

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

71.08
/src/cli/tls_server.cpp
1
/*
2
* TLS echo server using BSD sockets
3
* (C) 2014 Jack Lloyd
4
*     2017 René Korthaus, Rohde & Schwarz Cybersecurity
5
*     2023 René Meusel, Rohde & Schwarz Cybersecurity
6
*
7
* Botan is released under the Simplified BSD License (see license.txt)
8
*/
9

10
#include "cli.h"
11

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

14
#if defined(BOTAN_TARGET_OS_HAS_SOCKETS)
15
   #include <sys/socket.h>
16
#endif
17

18
#if defined(BOTAN_HAS_TLS) && defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) && defined(BOTAN_TARGET_OS_HAS_SOCKETS)
19

20
   #if defined(SO_MARK) || defined(SO_USER_COOKIE) || defined(SO_RTABLE)
21
      #if defined(SO_MARK)
22
         #define BOTAN_SO_SOCKETID SO_MARK
23
      #elif defined(SO_USER_COOKIE)
24
         #define BOTAN_SO_SOCKETID SO_USER_COOKIE
25
      #else
26
         #define BOTAN_SO_SOCKETID SO_RTABLE
27
      #endif
28
   #endif
29

30
   #include <botan/hex.h>
31
   #include <botan/mem_ops.h>
32
   #include <botan/tls_callbacks.h>
33
   #include <botan/tls_policy.h>
34
   #include <botan/tls_server.h>
35
   #include <botan/tls_session_manager_memory.h>
36

37
   #include <chrono>
38
   #include <fstream>
39
   #include <list>
40
   #include <memory>
41

42
   #include "socket_utils.h"
43
   #include "tls_helpers.h"
44

45
namespace Botan_CLI {
46

47
class TLS_Server;
48

49
namespace {
50

51
class Callbacks : public Botan::TLS::Callbacks {
1✔
52
   public:
53
      explicit Callbacks(TLS_Server& server_command) : m_server_command(server_command) {}
1✔
54

55
      std::ostream& output();
56
      void send(std::span<const uint8_t> buffer);
57
      void push_pending_output(std::string line);
58

59
      void tls_session_established(const Botan::TLS::Session_Summary& session) override {
9✔
60
         output() << "Handshake complete, " << session.version().to_string() << " using "
9✔
61
                  << session.ciphersuite().to_string();
27✔
62

63
         if(const auto& psk = session.external_psk_identity()) {
9✔
64
            output() << " (utilized PSK identity: " << maybe_hex_encode(psk.value()) << ")";
6✔
65
         }
66

67
         output() << std::endl;
9✔
68

69
         if(const auto& session_id = session.session_id(); !session_id.empty()) {
9✔
70
            output() << "Session ID " << Botan::hex_encode(session_id.get()) << std::endl;
9✔
71
         }
72

73
         if(const auto& session_ticket = session.session_ticket()) {
9✔
74
            output() << "Session ticket " << Botan::hex_encode(session_ticket->get()) << std::endl;
×
75
         }
76
      }
9✔
77

78
      void tls_record_received(uint64_t /*seq_no*/, std::span<const uint8_t> input) override {
9✔
79
         for(auto uc : input) {
2,061✔
80
            const char c = static_cast<char>(uc);
2,052✔
81
            m_line_buf += c;
2,052✔
82
            if(c == '\n') {
2,052✔
83
               push_pending_output(std::exchange(m_line_buf, {}));
27✔
84
            }
85
         }
86
      }
9✔
87

88
      void tls_emit_data(std::span<const uint8_t> buf) override { send(buf); }
132✔
89

90
      void tls_alert(Botan::TLS::Alert alert) override { output() << "Alert: " << alert.type_string() << std::endl; }
18✔
91

92
      std::string tls_server_choose_app_protocol(const std::vector<std::string>& /*client_protos*/) override {
×
93
         // we ignore whatever the client sends here
94
         return "echo/0.1";
×
95
      }
96

97
      void tls_verify_raw_public_key(const Botan::Public_Key& raw_public_key,
×
98
                                     Botan::Usage_Type /* usage */,
99
                                     std::string_view /* hostname */,
100
                                     const Botan::TLS::Policy& /* policy */) override {
101
         const auto fingerprint = raw_public_key.fingerprint_public("SHA-256");
×
102
         output() << "received Raw Public Key (" << fingerprint << ")\n";
×
103
      }
×
104

105
   private:
106
      TLS_Server& m_server_command;
107
      std::string m_line_buf;
108
};
109

110
}  // namespace
111

112
class TLS_Server final : public Command {
113
   public:
114
   #if defined(BOTAN_SO_SOCKETID)
115
      TLS_Server() :
2✔
116
            Command(
117
               "tls_server cert-or-pubkey key --port=443 --psk= --psk-identity= --psk-prf=SHA-256 --type=tcp --policy=default --dump-traces= --max-clients=0 --socket-id=0")
4✔
118
   #else
119
      TLS_Server() :
120
            Command(
121
               "tls_server cert-or-pubkey key --port=443 --psk= --psk-identity= --psk-prf=SHA-256 --type=tcp --policy=default --dump-traces= --max-clients=0")
122
   #endif
123
      {
124
         init_sockets();
2✔
125
      }
2✔
126

127
      ~TLS_Server() override { stop_sockets(); }
2✔
128

129
      TLS_Server(const TLS_Server& other) = delete;
130
      TLS_Server(TLS_Server&& other) = delete;
131
      TLS_Server& operator=(const TLS_Server& other) = delete;
132
      TLS_Server& operator=(TLS_Server&& other) = delete;
133

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

136
      std::string description() const override { return "Accept TLS/DTLS connections from TLS/DTLS clients"; }
1✔
137

138
      void go() override {
1✔
139
         const std::string server_cred = get_arg("cert-or-pubkey");
1✔
140
         const std::string server_key = get_arg("key");
1✔
141
         const uint16_t port = get_arg_u16("port");
1✔
142
         const size_t max_clients = get_arg_sz("max-clients");
1✔
143
         const std::string transport = get_arg("type");
1✔
144
         const std::string dump_traces_to = get_arg("dump-traces");
1✔
145
         auto psk = [this]() -> std::optional<Botan::secure_vector<uint8_t>> {
×
146
            auto psk_hex = get_arg_maybe("psk");
1✔
147
            if(psk_hex) {
1✔
148
               return Botan::hex_decode_locked(psk_hex.value());
1✔
149
            } else {
150
               return {};
×
151
            }
152
         }();
2✔
153
         const std::optional<std::string> psk_identity = get_arg_maybe("psk-identity");
1✔
154
         const std::optional<std::string> psk_prf = get_arg_maybe("psk-prf");
1✔
155

156
   #if defined(BOTAN_SO_SOCKETID)
157
         m_socket_id = static_cast<uint32_t>(get_arg_sz("socket-id"));
1✔
158
   #endif
159

160
         if(transport != "tcp" && transport != "udp") {
1✔
161
            throw CLI_Usage_Error("Invalid transport type '" + transport + "' for TLS");
×
162
         }
163

164
         m_is_tcp = (transport == "tcp");
1✔
165

166
         auto policy = load_tls_policy(get_arg("policy"));
2✔
167
         auto session_manager =
1✔
168
            std::make_shared<Botan::TLS::Session_Manager_In_Memory>(rng_as_shared());  // TODO sqlite3
2✔
169
         auto creds =
1✔
170
            std::make_shared<Basic_Credentials_Manager>(server_cred, server_key, std::move(psk), psk_identity, psk_prf);
1✔
171
         auto callbacks = std::make_shared<Callbacks>(*this);
1✔
172

173
         const socket_type server_fd = make_server_socket(port);
1✔
174
         size_t clients_served = 0;
1✔
175

176
         output() << "Listening for new connections on " << transport << " port " << socket_port(server_fd)
1✔
177
                  << std::endl;
11✔
178

179
         while(true) {
21✔
180
            if(max_clients > 0 && clients_served >= max_clients) {
11✔
181
               break;
182
            }
183

184
            if(m_is_tcp) {
10✔
185
               m_socket = ::accept(server_fd, nullptr, nullptr);
10✔
186
            } else {
187
               struct sockaddr_in from {};
×
188

189
               socklen_t from_len = sizeof(sockaddr_in);
×
190

191
               void* peek_buf = nullptr;
×
192
               size_t peek_len = 0;  // NOLINT(*-const-correctness)
×
193

194
   #if defined(BOTAN_TARGET_OS_IS_MACOS)
195
               // macOS handles zero size buffers differently - it will return 0 even if there's no incoming data,
196
               // and after that connect() will fail as sockaddr_in from is not initialized
197
               int dummy;
198
               peek_buf = &dummy;
199
               peek_len = sizeof(dummy);
200
   #endif
201

202
               if(::recvfrom(server_fd,
×
203
                             static_cast<char*>(peek_buf),
204
                             static_cast<sendrecv_len_type>(peek_len),
205
                             MSG_PEEK,
206
                             reinterpret_cast<struct sockaddr*>(&from),
207
                             &from_len) != 0) {
208
                  throw CLI_Error("Could not peek next packet");
×
209
               }
210

211
               if(::connect(server_fd, reinterpret_cast<struct sockaddr*>(&from), from_len) != 0) {
×
212
                  throw CLI_Error("Could not connect UDP socket");
×
213
               }
214
               m_socket = server_fd;
×
215
            }
216

217
            clients_served++;
10✔
218

219
            Botan::TLS::Server server(callbacks, session_manager, creds, policy, rng_as_shared(), m_is_tcp == false);
60✔
220

221
            std::unique_ptr<std::ostream> dump_stream;
10✔
222

223
            if(!dump_traces_to.empty()) {
10✔
224
               auto now = std::chrono::system_clock::now().time_since_epoch();
×
225
               const uint64_t timestamp = std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
×
226
               const std::string dump_file = dump_traces_to + "/tls_" + std::to_string(timestamp) + ".bin";
×
227
               dump_stream = std::make_unique<std::ofstream>(dump_file.c_str());
×
228
            }
×
229

230
            try {
231
               while(!server.is_closed()) {
57✔
232
                  try {
47✔
233
                     uint8_t buf[4 * 1024] = {0};
47✔
234
                     const ssize_t got = ::recv(m_socket, Botan::cast_uint8_ptr_to_char(buf), sizeof(buf), 0);
47✔
235

236
                     if(got == -1) {
47✔
237
                        error_output() << "Error in socket read - " << err_to_string(errno) << std::endl;
×
238
                        break;
×
239
                     }
240

241
                     if(got == 0) {
47✔
242
                        error_output() << "EOF on socket" << std::endl;
×
243
                        break;
244
                     }
245

246
                     if(dump_stream) {
47✔
247
                        dump_stream->write(reinterpret_cast<const char*>(buf), got);
×
248
                     }
249

250
                     server.received_data(buf, got);
47✔
251

252
                     while(server.is_active() && !m_pending_output.empty()) {
55✔
253
                        const std::string output = m_pending_output.front();
9✔
254
                        m_pending_output.pop_front();
9✔
255
                        server.send(output);
9✔
256

257
                        if(output == "quit\n") {
9✔
258
                           server.close();
×
259
                        }
260
                     }
9✔
261
                  } catch(std::exception& e) {
1✔
262
                     error_output() << "Connection problem: " << e.what() << std::endl;
1✔
263
                     if(m_is_tcp) {
1✔
264
                        close_socket(m_socket);
1✔
265
                        m_socket = invalid_socket();
1✔
266
                     }
267
                  }
1✔
268
               }
269
            } catch(Botan::Exception& e) {
×
270
               error_output() << "Connection failed: " << e.what() << "\n";
×
271
            }
×
272

273
            if(m_is_tcp) {
10✔
274
               close_socket(m_socket);
10✔
275
               m_socket = invalid_socket();
10✔
276
            }
277
         }
10✔
278

279
         close_socket(server_fd);
2✔
280
      }
6✔
281

282
   public:
283
      using Command::flag_set;
284
      using Command::output;
285

286
      void send(std::span<const uint8_t> buf) {
66✔
287
         if(m_is_tcp) {
66✔
288
            const ssize_t sent = ::send(m_socket, buf.data(), static_cast<sendrecv_len_type>(buf.size()), MSG_NOSIGNAL);
66✔
289

290
            if(sent == -1) {
66✔
291
               error_output() << "Error writing to socket - " << err_to_string(errno) << std::endl;
×
292
            } else if(sent >= 0 && static_cast<size_t>(sent) != buf.size()) {
66✔
293
               error_output() << "Packet of length " << buf.size() << " truncated to " << sent << std::endl;
×
294
            }
295
         } else {
296
            while(!buf.empty()) {
×
297
               ssize_t sent = ::send(m_socket, buf.data(), static_cast<sendrecv_len_type>(buf.size()), MSG_NOSIGNAL);
×
298

299
               if(sent == -1) {
×
300
                  if(errno == EINTR) {
×
301
                     sent = 0;
302
                  } else {
303
                     throw CLI_Error("Socket write failed");
×
304
                  }
305
               }
306

307
               buf = buf.subspan(sent);
×
308
            }
309
         }
310
      }
66✔
311

312
      void push_pending_output(std::string line) { m_pending_output.emplace_back(std::move(line)); }
9✔
313

314
   private:
315
      socket_type make_server_socket(uint16_t port) {
1✔
316
         const int type = m_is_tcp ? SOCK_STREAM : SOCK_DGRAM;
1✔
317

318
         const socket_type fd = ::socket(PF_INET, type, 0);
1✔
319
         if(fd == invalid_socket()) {
1✔
320
            throw CLI_Error("Unable to acquire socket");
×
321
         }
322

323
         sockaddr_in socket_info{};
1✔
324
         Botan::clear_mem(&socket_info, 1);
1✔
325
         socket_info.sin_family = AF_INET;
1✔
326
         socket_info.sin_port = htons(port);
1✔
327

328
         // FIXME: support limiting listeners
329
         socket_info.sin_addr.s_addr = INADDR_ANY;
1✔
330

331
         if(::bind(fd, reinterpret_cast<struct sockaddr*>(&socket_info), sizeof(struct sockaddr)) != 0) {
1✔
332
            close_socket(fd);
×
333
            throw CLI_Error("server bind failed");
×
334
         }
335

336
         if(m_is_tcp) {
1✔
337
            constexpr int backlog = std::min(100, SOMAXCONN);
1✔
338
            if(::listen(fd, backlog) != 0) {
1✔
339
               close_socket(fd);
×
340
               throw CLI_Error("listen failed");
×
341
            }
342
         }
343
         if(m_socket_id > 0) {
1✔
344
   #if defined(BOTAN_SO_SOCKETID)
345
            if(::setsockopt(fd,
×
346
                            SOL_SOCKET,
347
                            BOTAN_SO_SOCKETID,
348
                            reinterpret_cast<const void*>(&m_socket_id),
×
349
                            sizeof(m_socket_id)) != 0) {
350
               // Failed but not world-ending issue
351
               output() << "set socket identifier setting failed" << std::endl;
×
352
            }
353
   #endif
354
         }
355
         return fd;
1✔
356
      }
357

358
      socket_type m_socket = invalid_socket();
359
      bool m_is_tcp = false;
360
      uint32_t m_socket_id = 0;
361
      std::list<std::string> m_pending_output;
362
};
363

364
namespace {
365

366
std::ostream& Callbacks::output() {
38✔
367
   return m_server_command.output();
38✔
368
}
369

370
void Callbacks::send(std::span<const uint8_t> buffer) {
66✔
371
   m_server_command.send(buffer);
66✔
372
}
373

374
void Callbacks::push_pending_output(std::string line) {
9✔
375
   m_server_command.push_pending_output(std::move(line));
18✔
376
}
9✔
377

378
}  // namespace
379

380
BOTAN_REGISTER_COMMAND("tls_server", TLS_Server);
2✔
381

382
}  // namespace Botan_CLI
383

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

© 2026 Coveralls, Inc