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

randombit / botan / 29630228535

18 Jul 2026 02:46AM UTC coverage: 89.407% (-2.3%) from 91.66%
29630228535

push

github

web-flow
Merge pull request #5740 from randombit/jack/x509-serial-number

Add an explicit type for X509 certificate serial numbers

114089 of 127606 relevant lines covered (89.41%)

10801388.62 hits per line

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

70.41
/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
#include "sandbox.h"
12

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

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

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

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

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

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

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

46
namespace Botan_CLI {
47

48
class TLS_Server;
49

50
namespace {
51

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

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

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

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

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

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

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

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

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

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

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

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

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

111
}  // namespace
112

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

128
      ~TLS_Server() override { stop_sockets(); }
4✔
129

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

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

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

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

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

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

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

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

174
         if(!m_sandbox.init()) {
1✔
175
            error_output() << "Failed sandboxing\n";
×
176
            return;
×
177
         }
178

179
         const socket_type server_fd = make_server_socket(port);
1✔
180
         size_t clients_served = 0;
1✔
181

182
         output() << "Listening for new connections on " << transport << " port " << socket_port(server_fd)
1✔
183
                  << std::endl;
11✔
184

185
         while(true) {
21✔
186
            if(max_clients > 0 && clients_served >= max_clients) {
11✔
187
               break;
188
            }
189

190
            if(m_is_tcp) {
10✔
191
               m_socket = ::accept(server_fd, nullptr, nullptr);
10✔
192
            } else {
193
               struct sockaddr_in from {};
×
194

195
               socklen_t from_len = sizeof(sockaddr_in);
×
196

197
               void* peek_buf = nullptr;
×
198
               size_t peek_len = 0;  // NOLINT(*-const-correctness)
×
199

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

208
               if(::recvfrom(server_fd,
×
209
                             static_cast<char*>(peek_buf),
210
                             static_cast<sendrecv_len_type>(peek_len),
211
                             MSG_PEEK,
212
                             reinterpret_cast<struct sockaddr*>(&from),
213
                             &from_len) != 0) {
214
                  throw CLI_Error("Could not peek next packet");
×
215
               }
216

217
               if(::connect(server_fd, reinterpret_cast<struct sockaddr*>(&from), from_len) != 0) {
×
218
                  throw CLI_Error("Could not connect UDP socket");
×
219
               }
220
               m_socket = server_fd;
×
221
            }
222

223
            clients_served++;
10✔
224

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

227
            std::unique_ptr<std::ostream> dump_stream;
10✔
228

229
            if(!dump_traces_to.empty()) {
10✔
230
               auto now = std::chrono::system_clock::now().time_since_epoch();
×
231
               const uint64_t timestamp = std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
×
232
               const std::string dump_file = dump_traces_to + "/tls_" + std::to_string(timestamp) + ".bin";
×
233
               dump_stream = std::make_unique<std::ofstream>(dump_file.c_str());
×
234
            }
×
235

236
            try {
237
               while(!server.is_closed()) {
54✔
238
                  try {
44✔
239
                     uint8_t buf[4 * 1024] = {0};
44✔
240
                     const ssize_t got = ::recv(m_socket, Botan::cast_uint8_ptr_to_char(buf), sizeof(buf), 0);
44✔
241

242
                     if(got == -1) {
44✔
243
                        error_output() << "Error in socket read - " << err_to_string(errno) << std::endl;
×
244
                        break;
×
245
                     }
246

247
                     if(got == 0) {
44✔
248
                        error_output() << "EOF on socket" << std::endl;
×
249
                        break;
250
                     }
251

252
                     if(dump_stream) {
44✔
253
                        dump_stream->write(reinterpret_cast<const char*>(buf), got);
×
254
                     }
255

256
                     server.received_data(buf, got);
44✔
257

258
                     while(server.is_active() && !m_pending_output.empty()) {
52✔
259
                        const std::string output = m_pending_output.front();
9✔
260
                        m_pending_output.pop_front();
9✔
261
                        server.send(output);
9✔
262

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

279
            if(m_is_tcp) {
10✔
280
               close_socket(m_socket);
10✔
281
               m_socket = invalid_socket();
10✔
282
            }
283
         }
10✔
284

285
         close_socket(server_fd);
2✔
286
      }
6✔
287

288
   public:
289
      using Command::flag_set;
290
      using Command::output;
291

292
      void send(std::span<const uint8_t> buf) {
66✔
293
         if(m_is_tcp) {
66✔
294
            const ssize_t sent = ::send(m_socket, buf.data(), static_cast<sendrecv_len_type>(buf.size()), MSG_NOSIGNAL);
66✔
295

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

305
               if(sent == -1) {
×
306
                  if(errno == EINTR) {
×
307
                     sent = 0;
308
                  } else {
309
                     throw CLI_Error("Socket write failed");
×
310
                  }
311
               }
312

313
               buf = buf.subspan(sent);
×
314
            }
315
         }
316
      }
66✔
317

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

320
   private:
321
      socket_type make_server_socket(uint16_t port) {
1✔
322
         const int type = m_is_tcp ? SOCK_STREAM : SOCK_DGRAM;
1✔
323

324
         const socket_type fd = ::socket(PF_INET, type, 0);
1✔
325
         if(fd == invalid_socket()) {
1✔
326
            throw CLI_Error("Unable to acquire socket");
×
327
         }
328

329
         sockaddr_in socket_info{};
1✔
330
         Botan::clear_mem(&socket_info, 1);
1✔
331
         socket_info.sin_family = AF_INET;
1✔
332
         socket_info.sin_port = htons(port);
1✔
333

334
         // FIXME: support limiting listeners
335
         socket_info.sin_addr.s_addr = INADDR_ANY;
1✔
336

337
         if(::bind(fd, reinterpret_cast<struct sockaddr*>(&socket_info), sizeof(struct sockaddr)) != 0) {
1✔
338
            close_socket(fd);
×
339
            throw CLI_Error("server bind failed");
×
340
         }
341

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

364
      socket_type m_socket = invalid_socket();
365
      bool m_is_tcp = false;
366
      uint32_t m_socket_id = 0;
367
      std::list<std::string> m_pending_output;
368
      Sandbox m_sandbox;
369
};
370

371
namespace {
372

373
std::ostream& Callbacks::output() {
38✔
374
   return m_server_command.output();
38✔
375
}
376

377
void Callbacks::send(std::span<const uint8_t> buffer) {
66✔
378
   m_server_command.send(buffer);
66✔
379
}
380

381
void Callbacks::push_pending_output(std::string line) {
9✔
382
   m_server_command.push_pending_output(std::move(line));
18✔
383
}
9✔
384

385
}  // namespace
386

387
BOTAN_REGISTER_COMMAND("tls_server", TLS_Server);
2✔
388

389
}  // namespace Botan_CLI
390

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