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

randombit / botan / 17011479145

16 Aug 2025 06:17PM UTC coverage: 90.648% (-0.004%) from 90.652%
17011479145

Pull #4660

github

web-flow
Merge 1b0477060 into a2a0b43c3
Pull Request #4660: Consolidation and Enhancement of BSD Socket Layer

100083 of 110409 relevant lines covered (90.65%)

12305774.18 hits per line

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

69.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
      2025 Kagan Can Sit
7
*
8
* Botan is released under the Simplified BSD License (see license.txt)
9
*/
10

11
#include "cli.h"
12
#include "sandbox.h"
13

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

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

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

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

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

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

44
   #include "tls_helpers.h"
45
   #include <botan/internal/socket_platform.h>
46

47
namespace Botan_CLI {
48

49
class TLS_Server;
50

51
namespace {
52

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

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

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

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

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

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

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

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

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

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

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

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

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

112
}  // namespace
113

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

129
      ~TLS_Server() override { Botan::OS::Socket_Platform::socket_fini(); }
4✔
130

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

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

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

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

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

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

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

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

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

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

183
         output() << "Listening for new connections on " << transport << " port " << port << std::endl;
1✔
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;
×
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
               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
                     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 - "
×
244
                                       << Botan::OS::Socket_Platform::get_last_socket_error() << std::endl;
×
245
                        break;
×
246
                     }
247

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

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

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

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

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

280
            if(m_is_tcp) {
10✔
281
               Botan::OS::Socket_Platform::close_socket(m_socket);
10✔
282
               m_socket = Botan::OS::Socket_Platform::invalid_socket();
10✔
283
            }
284
         }
10✔
285

286
         Botan::OS::Socket_Platform::close_socket(server_fd);
2✔
287
      }
6✔
288

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

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

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

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

315
               buf = buf.subspan(sent);
×
316
            }
317
         }
318
      }
66✔
319

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

322
   private:
323
      using socket_type = Botan::OS::Socket_Platform::socket_type;
324
      using socket_op_ret_type = Botan::OS::Socket_Platform::socket_op_ret_type;
325
      using socklen_type = Botan::OS::Socket_Platform::socklen_type;
326
      using sendrecv_len_type = Botan::OS::Socket_Platform::sendrecv_len_type;
327

328
      socket_type make_server_socket(uint16_t port) {
1✔
329
         const int type = m_is_tcp ? SOCK_STREAM : SOCK_DGRAM;
1✔
330

331
         socket_type fd = ::socket(PF_INET, type, 0);
1✔
332
         if(fd == Botan::OS::Socket_Platform::invalid_socket()) {
1✔
333
            throw CLI_Error("Unable to acquire socket");
×
334
         }
335

336
         sockaddr_in socket_info{};
1✔
337
         Botan::clear_mem(&socket_info, 1);
1✔
338
         socket_info.sin_family = AF_INET;
1✔
339
         socket_info.sin_port = htons(port);
1✔
340

341
         // FIXME: support limiting listeners
342
         socket_info.sin_addr.s_addr = INADDR_ANY;
1✔
343

344
         if(::bind(fd, reinterpret_cast<struct sockaddr*>(&socket_info), sizeof(struct sockaddr)) != 0) {
1✔
345
            Botan::OS::Socket_Platform::close_socket(fd);
×
346
            throw CLI_Error("server bind failed");
×
347
         }
348

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

371
      socket_type m_socket = Botan::OS::Socket_Platform::invalid_socket();
372
      bool m_is_tcp = false;
373
      uint32_t m_socket_id = 0;
374
      std::list<std::string> m_pending_output;
375
      Sandbox m_sandbox;
376
};
377

378
namespace {
379

380
std::ostream& Callbacks::output() {
38✔
381
   return m_server_command.output();
38✔
382
}
383

384
void Callbacks::send(std::span<const uint8_t> buffer) {
66✔
385
   m_server_command.send(buffer);
66✔
386
}
387

388
void Callbacks::push_pending_output(std::string line) {
9✔
389
   m_server_command.push_pending_output(std::move(line));
18✔
390
}
9✔
391

392
}  // namespace
393

394
BOTAN_REGISTER_COMMAND("tls_server", TLS_Server);
2✔
395

396
}  // namespace Botan_CLI
397

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