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

randombit / botan / 5655173672

25 Jul 2023 09:40AM UTC coverage: 91.696% (-0.002%) from 91.698%
5655173672

push

github

web-flow
Merge pull request #3634 from FAlbertDev/fix/tls_http_server_segfault

Fix: Segfault in tls_http_server

78295 of 85385 relevant lines covered (91.7%)

12309528.76 hits per line

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

86.08
/src/cli/tls_http_server.cpp
1
/*
2
* (C) 2014,2015,2017,2019 Jack Lloyd
3
* (C) 2016 Matthias Gierlings
4
* (C) 2023 René Meusel, Rohde & Schwarz Cybersecurity
5
*
6
* Botan is released under the Simplified BSD License (see license.txt)
7
*/
8

9
#include "cli.h"
10

11
#if defined(BOTAN_HAS_TLS) && defined(BOTAN_HAS_BOOST_ASIO) && defined(BOTAN_TARGET_OS_HAS_FILESYSTEM)
12

13
   #include <atomic>
14
   #include <fstream>
15
   #include <iomanip>
16
   #include <iostream>
17
   #include <memory>
18
   #include <string>
19
   #include <thread>
20
   #include <utility>
21
   #include <vector>
22

23
   #include <botan/internal/os_utils.h>
24
   #include <boost/asio.hpp>
25
   #include <boost/bind.hpp>
26

27
   #include <botan/hex.h>
28
   #include <botan/pkcs8.h>
29
   #include <botan/rng.h>
30
   #include <botan/tls_messages.h>
31
   #include <botan/tls_server.h>
32
   #include <botan/tls_session_manager_memory.h>
33
   #include <botan/version.h>
34
   #include <botan/x509cert.h>
35

36
   #if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER)
37
      #include <botan/tls_session_manager_sqlite.h>
38
   #endif
39

40
   #include "tls_helpers.h"
41

42
namespace Botan_CLI {
43

44
namespace {
45

46
using boost::asio::ip::tcp;
47

48
template <typename T>
49
boost::asio::io_context& get_io_service(T& s) {
4✔
50
   #if BOOST_VERSION >= 107000
51
   return static_cast<boost::asio::io_context&>((s).get_executor().context());
8✔
52
   #else
53
   return s.get_io_service();
54
   #endif
55
}
56

57
inline void log_error(const char* msg) {
×
58
   std::cout << msg << std::endl;
×
59
}
60

61
inline void log_exception(const char* where, const std::exception& e) {
×
62
   std::cout << where << ' ' << e.what() << std::endl;
×
63
}
×
64

65
class ServerStatus {
66
   public:
67
      ServerStatus(size_t max_clients) : m_max_clients(max_clients), m_clients_serviced(0) {}
1✔
68

69
      bool should_exit() const {
4✔
70
         if(m_max_clients == 0) {
4✔
71
            return false;
72
         }
73

74
         return clients_serviced() >= m_max_clients;
4✔
75
      }
76

77
      void client_serviced() { m_clients_serviced++; }
4✔
78

79
      size_t clients_serviced() const { return m_clients_serviced.load(); }
4✔
80

81
   private:
82
      size_t m_max_clients;
83
      std::atomic<size_t> m_clients_serviced;
84
};
85

86
/*
87
* This is an incomplete and highly buggy HTTP request parser. It is just
88
* barely sufficient to handle a GET request sent by a browser.
89
*/
90
class HTTP_Parser final {
8✔
91
   public:
92
      class Request {
93
         public:
94
            const std::string& verb() const { return m_verb; }
6✔
95

96
            const std::string& location() const { return m_location; }
4✔
97

98
            const std::map<std::string, std::string>& headers() const { return m_headers; }
4✔
99

100
            Request(const std::string& verb,
4✔
101
                    const std::string& location,
102
                    const std::map<std::string, std::string>& headers) :
4✔
103
                  m_verb(verb), m_location(location), m_headers(headers) {}
8✔
104

105
         private:
106
            std::string m_verb;
107
            std::string m_location;
108
            std::map<std::string, std::string> m_headers;
109
      };
110

111
      class Callbacks {
112
         public:
113
            virtual void handle_http_request(const Request& request) = 0;
114

115
            virtual ~Callbacks() = default;
×
116

117
            Callbacks() = default;
4✔
118

119
            Callbacks(const Callbacks& other) = delete;
120
            Callbacks(Callbacks&& other) = delete;
121
            Callbacks& operator=(const Callbacks& other) = delete;
122
            Callbacks& operator=(Callbacks&&) = delete;
123
      };
124

125
      HTTP_Parser(Callbacks& cb) : m_cb(cb) {}
4✔
126

127
      void consume_input(std::span<const uint8_t> buf) {
4✔
128
         m_req_buf.append(reinterpret_cast<const char*>(buf.data()), buf.size());
4✔
129

130
         std::istringstream strm(m_req_buf);
4✔
131

132
         std::string http_version;
4✔
133
         std::string verb;
4✔
134
         std::string location;
4✔
135
         std::map<std::string, std::string> headers;
4✔
136

137
         strm >> verb >> location >> http_version;
4✔
138

139
         if(verb.empty() || location.empty()) {
4✔
140
            return;
×
141
         }
142

143
         while(true) {
22✔
144
            std::string header_line;
22✔
145
            std::getline(strm, header_line);
22✔
146

147
            if(header_line == "\r") {
22✔
148
               continue;
8✔
149
            }
150

151
            auto delim = header_line.find(": ");
14✔
152
            if(delim == std::string::npos) {
14✔
153
               break;
154
            }
155

156
            const std::string hdr_name = header_line.substr(0, delim);
10✔
157
            const std::string hdr_val = header_line.substr(delim + 2, std::string::npos);
10✔
158

159
            headers[hdr_name] = hdr_val;
10✔
160

161
            if(headers.size() > 1024) {
10✔
162
               throw Botan::Invalid_Argument("Too many HTTP headers sent in request");
×
163
            }
164
         }
28✔
165

166
         if(!verb.empty() && !location.empty()) {
4✔
167
            Request req(verb, location, headers);
4✔
168
            m_cb.handle_http_request(req);
4✔
169
            m_req_buf.clear();
4✔
170
         }
4✔
171
      }
4✔
172

173
   private:
174
      Callbacks& m_cb;
175
      std::string m_req_buf;
176
};
177

178
const size_t READBUF_SIZE = 4096;
179

180
class TLS_Asio_HTTP_Session final : public std::enable_shared_from_this<TLS_Asio_HTTP_Session>,
181
                                    public Botan::TLS::Callbacks,
182
                                    public HTTP_Parser::Callbacks {
183
   public:
184
      typedef std::shared_ptr<TLS_Asio_HTTP_Session> pointer;
185

186
      static pointer create(boost::asio::io_service& io,
4✔
187
                            const std::shared_ptr<Botan::TLS::Session_Manager>& session_manager,
188
                            const std::shared_ptr<Botan::Credentials_Manager>& credentials,
189
                            const std::shared_ptr<Botan::TLS::Policy>& policy) {
190
         auto session = std::make_shared<TLS_Asio_HTTP_Session>(io);
4✔
191

192
         // Defer the setup of the TLS server to make use of
193
         // shared_from_this() which wouldn't work in the c'tor.
194
         session->setup(session_manager, credentials, policy);
4✔
195

196
         return session;
4✔
197
      }
×
198

199
      tcp::socket& client_socket() { return m_client_socket; }
200

201
      void start() {
4✔
202
         m_c2s.resize(READBUF_SIZE);
4✔
203
         client_read(boost::system::error_code(), 0);  // start read loop
4✔
204
      }
4✔
205

206
      void stop() {
4✔
207
         if(!m_tls) {
4✔
208
            // Server is already closed
209
            return;
210
         }
211

212
         m_tls->close();
4✔
213

214
         // Need to explicitly destroy the TLS::Server object to break the
215
         // circular ownership of shared_from_this() and the shared_ptr of
216
         // this kept inside the TLS::Channel.
217
         m_tls.reset();
4✔
218
      }
219

220
      TLS_Asio_HTTP_Session(boost::asio::io_service& io) : m_strand(io), m_client_socket(io), m_rng(cli_make_rng()) {}
12✔
221

222
   private:
223
      void setup(const std::shared_ptr<Botan::TLS::Session_Manager>& session_manager,
4✔
224
                 const std::shared_ptr<Botan::Credentials_Manager>& credentials,
225
                 const std::shared_ptr<Botan::TLS::Policy>& policy) {
226
         m_tls = std::make_unique<Botan::TLS::Server>(shared_from_this(), session_manager, credentials, policy, m_rng);
4✔
227
      }
4✔
228

229
      void client_read(const boost::system::error_code& error, size_t bytes_transferred) {
20✔
230
         if(error) {
20✔
231
            return stop();
4✔
232
         }
233

234
         if(!m_tls) {
16✔
235
            log_error("Received client data after close");
×
236
            return;
×
237
         }
238

239
         try {
16✔
240
            m_tls->received_data(&m_c2s[0], bytes_transferred);
16✔
241
         } catch(Botan::Exception& e) {
×
242
            log_exception("TLS connection failed", e);
×
243
            return stop();
×
244
         }
×
245

246
         m_client_socket.async_read_some(boost::asio::buffer(&m_c2s[0], m_c2s.size()),
32✔
247
                                         m_strand.wrap(boost::bind(&TLS_Asio_HTTP_Session::client_read,
32✔
248
                                                                   shared_from_this(),
32✔
249
                                                                   boost::asio::placeholders::error,
250
                                                                   boost::asio::placeholders::bytes_transferred)));
251
      }
252

253
      void handle_client_write_completion(const boost::system::error_code& error) {
21✔
254
         if(error) {
21✔
255
            return stop();
×
256
         }
257

258
         m_s2c.clear();
21✔
259

260
         if(m_s2c_pending.empty() && (!m_tls || m_tls->is_closed_for_writing())) {
21✔
261
            m_client_socket.close();
4✔
262
         }
263
         tls_emit_data({});  // initiate another write if needed
21✔
264
      }
265

266
      std::string tls_server_choose_app_protocol(const std::vector<std::string>& /*client_protos*/) override {
×
267
         return "http/1.1";
×
268
      }
269

270
      void tls_record_received(uint64_t /*rec_no*/, std::span<const uint8_t> buf) override {
4✔
271
         if(!m_http_parser) {
4✔
272
            m_http_parser = std::make_unique<HTTP_Parser>(*this);
4✔
273
         }
274

275
         m_http_parser->consume_input(buf);
4✔
276
      }
4✔
277

278
      std::string summarize_request(const HTTP_Parser::Request& request) {
2✔
279
         std::ostringstream strm;
2✔
280

281
         strm << "Client " << client_socket().remote_endpoint().address().to_string() << " requested " << request.verb()
4✔
282
              << " " << request.location() << "\n";
4✔
283

284
         if(request.headers().empty() == false) {
2✔
285
            strm << "Client HTTP headers:\n";
2✔
286
            for(const auto& kv : request.headers()) {
6✔
287
               strm << " " << kv.first << ": " << kv.second << "\n";
4✔
288
            }
289
         }
290

291
         return strm.str();
4✔
292
      }
2✔
293

294
      void handle_http_request(const HTTP_Parser::Request& request) override {
4✔
295
         if(!m_tls) {
4✔
296
            log_error("Received client data after close");
×
297
            return;
×
298
         }
299
         std::ostringstream response;
4✔
300
         if(request.verb() == "GET") {
4✔
301
            if(request.location() == "/" || request.location() == "/status") {
2✔
302
               const std::string http_summary = summarize_request(request);
2✔
303

304
               const std::string report = m_connection_summary + m_session_summary + m_chello_summary + http_summary;
4✔
305

306
               response << "HTTP/1.0 200 OK\r\n";
2✔
307
               response << "Server: " << Botan::version_string() << "\r\n";
4✔
308
               response << "Content-Type: text/plain\r\n";
2✔
309
               response << "Content-Length: " << report.size() << "\r\n";
2✔
310
               response << "\r\n";
2✔
311

312
               response << report;
2✔
313
            } else {
4✔
314
               response << "HTTP/1.0 404 Not Found\r\n\r\n";
×
315
            }
316
         } else {
317
            response << "HTTP/1.0 405 Method Not Allowed\r\n\r\n";
2✔
318
         }
319

320
         const std::string response_str = response.str();
4✔
321
         m_tls->send(response_str);
4✔
322
         m_tls->close();
4✔
323
      }
4✔
324

325
      void tls_emit_data(std::span<const uint8_t> buf) override {
49✔
326
         if(!buf.empty()) {
49✔
327
            m_s2c_pending.insert(m_s2c_pending.end(), buf.begin(), buf.end());
28✔
328
         }
329

330
         // no write now active and we still have output pending
331
         if(m_s2c.empty() && !m_s2c_pending.empty()) {
49✔
332
            std::swap(m_s2c_pending, m_s2c);
21✔
333

334
            boost::asio::async_write(m_client_socket,
21✔
335
                                     boost::asio::buffer(&m_s2c[0], m_s2c.size()),
21✔
336
                                     m_strand.wrap(boost::bind(&TLS_Asio_HTTP_Session::handle_client_write_completion,
42✔
337
                                                               shared_from_this(),
42✔
338
                                                               boost::asio::placeholders::error)));
339
         }
340
      }
49✔
341

342
      void tls_session_activated() override {
4✔
343
         std::ostringstream strm;
4✔
344

345
         strm << "TLS negotiation with " << Botan::version_string() << " test server\n\n";
8✔
346

347
         m_connection_summary = strm.str();
4✔
348
      }
4✔
349

350
      void tls_session_established(const Botan::TLS::Session_Summary& session) override {
4✔
351
         std::ostringstream strm;
4✔
352

353
         strm << "Version: " << session.version().to_string() << "\n";
8✔
354
         strm << "Ciphersuite: " << session.ciphersuite().to_string() << "\n";
8✔
355
         if(const auto& session_id = session.session_id(); !session_id.empty()) {
4✔
356
            strm << "SessionID: " << Botan::hex_encode(session_id.get()) << "\n";
8✔
357
         }
358
         if(!session.server_info().hostname().empty()) {
8✔
359
            strm << "SNI: " << session.server_info().hostname() << "\n";
12✔
360
         }
361

362
         m_session_summary = strm.str();
4✔
363
      }
4✔
364

365
      void tls_inspect_handshake_msg(const Botan::TLS::Handshake_Message& message) override {
34✔
366
         if(message.type() == Botan::TLS::Handshake_Type::ClientHello) {
34✔
367
            const Botan::TLS::Client_Hello& client_hello = dynamic_cast<const Botan::TLS::Client_Hello&>(message);
6✔
368

369
            std::ostringstream strm;
6✔
370

371
            strm << "Client random: " << Botan::hex_encode(client_hello.random()) << "\n";
6✔
372

373
            strm << "Client offered following ciphersuites:\n";
6✔
374
            for(uint16_t suite_id : client_hello.ciphersuites()) {
74✔
375
               const auto ciphersuite = Botan::TLS::Ciphersuite::by_id(suite_id);
68✔
376

377
               strm << " - 0x" << std::hex << std::setfill('0') << std::setw(4) << suite_id << std::dec
68✔
378
                    << std::setfill(' ') << std::setw(0) << " ";
68✔
379

380
               if(ciphersuite && ciphersuite->valid()) {
68✔
381
                  strm << ciphersuite->to_string() << "\n";
186✔
382
               } else if(suite_id == 0x00FF) {
6✔
383
                  strm << "Renegotiation SCSV\n";
6✔
384
               } else {
385
                  strm << "Unknown ciphersuite\n";
×
386
               }
387
            }
388

389
            m_chello_summary = strm.str();
6✔
390
         }
6✔
391
      }
34✔
392

393
      void tls_alert(Botan::TLS::Alert alert) override {
×
394
         if(!m_tls) {
×
395
            log_error("Received client data after close");
×
396
            return;
×
397
         }
398
         if(alert.type() == Botan::TLS::Alert::CloseNotify) {
×
399
            m_tls->close();
×
400
         } else {
401
            std::cout << "Alert " << alert.type_string() << std::endl;
×
402
         }
403
      }
404

405
      boost::asio::io_service::strand m_strand;
406

407
      tcp::socket m_client_socket;
408

409
      std::shared_ptr<Botan::RandomNumberGenerator> m_rng;
410
      std::unique_ptr<Botan::TLS::Server> m_tls;
411
      std::string m_chello_summary;
412
      std::string m_connection_summary;
413
      std::string m_session_summary;
414
      std::unique_ptr<HTTP_Parser> m_http_parser;
415

416
      std::vector<uint8_t> m_c2s;
417
      std::vector<uint8_t> m_s2c;
418
      std::vector<uint8_t> m_s2c_pending;
419
};
420

421
class TLS_Asio_HTTP_Server final {
422
   public:
423
      typedef TLS_Asio_HTTP_Session session;
424

425
      TLS_Asio_HTTP_Server(boost::asio::io_service& io,
1✔
426
                           unsigned short port,
427
                           std::shared_ptr<Botan::Credentials_Manager> creds,
428
                           std::shared_ptr<Botan::TLS::Policy> policy,
429
                           std::shared_ptr<Botan::TLS::Session_Manager> session_mgr,
430
                           size_t max_clients) :
1✔
431
            m_acceptor(io, tcp::endpoint(tcp::v4(), port)),
1✔
432
            m_creds(std::move(creds)),
1✔
433
            m_policy(std::move(policy)),
1✔
434
            m_session_manager(std::move(session_mgr)),
1✔
435
            m_status(max_clients) {
1✔
436
         serve_one_session();
1✔
437
      }
1✔
438

439
   private:
440
      void serve_one_session() {
4✔
441
         auto new_session = session::create(get_io_service(m_acceptor), m_session_manager, m_creds, m_policy);
4✔
442

443
         m_acceptor.async_accept(
8✔
444
            new_session->client_socket(),
4✔
445
            boost::bind(&TLS_Asio_HTTP_Server::handle_accept, this, new_session, boost::asio::placeholders::error));
12✔
446
      }
4✔
447

448
      void handle_accept(const session::pointer& new_session, const boost::system::error_code& error) {
4✔
449
         if(!error) {
4✔
450
            new_session->start();
4✔
451
            m_status.client_serviced();
4✔
452

453
            if(!m_status.should_exit()) {
4✔
454
               serve_one_session();
3✔
455
            }
456
         }
457
      }
4✔
458

459
      tcp::acceptor m_acceptor;
460

461
      std::shared_ptr<Botan::Credentials_Manager> m_creds;
462
      std::shared_ptr<Botan::TLS::Policy> m_policy;
463
      std::shared_ptr<Botan::TLS::Session_Manager> m_session_manager;
464
      ServerStatus m_status;
465
};
466

467
}  // namespace
468

469
class TLS_HTTP_Server final : public Command {
470
   public:
471
      TLS_HTTP_Server() :
2✔
472
            Command(
473
               "tls_http_server server_cert server_key "
474
               "--port=443 --policy=default --threads=0 --max-clients=0 "
475
               "--session-db= --session-db-pass=") {}
4✔
476

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

479
      std::string description() const override { return "Provides a simple HTTP server"; }
1✔
480

481
      size_t thread_count() const {
1✔
482
         if(size_t t = get_arg_sz("threads")) {
1✔
483
            return t;
484
         }
485
         if(size_t t = Botan::OS::get_cpu_available()) {
1✔
486
            return t;
1✔
487
         }
488
         return 2;
489
      }
490

491
      void go() override {
1✔
492
         const uint16_t listen_port = get_arg_u16("port");
1✔
493

494
         const std::string server_crt = get_arg("server_cert");
1✔
495
         const std::string server_key = get_arg("server_key");
1✔
496

497
         const size_t num_threads = thread_count();
1✔
498
         const size_t max_clients = get_arg_sz("max-clients");
1✔
499

500
         auto creds = std::make_shared<Basic_Credentials_Manager>(server_crt, server_key);
1✔
501

502
         auto policy = load_tls_policy(get_arg("policy"));
2✔
503

504
         std::shared_ptr<Botan::TLS::Session_Manager> session_mgr;
1✔
505

506
         const std::string sessions_db = get_arg("session-db");
1✔
507

508
         if(!sessions_db.empty()) {
1✔
509
   #if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER)
510
            const std::string sessions_passphrase = get_passphrase_arg("Session DB passphrase", "session-db-pass");
×
511
            session_mgr.reset(
×
512
               new Botan::TLS::Session_Manager_SQLite(sessions_passphrase, rng_as_shared(), sessions_db));
×
513
   #else
514
            throw CLI_Error_Unsupported("Sqlite3 support not available");
515
   #endif
516
         }
×
517

518
         if(!session_mgr) {
1✔
519
            session_mgr.reset(new Botan::TLS::Session_Manager_In_Memory(rng_as_shared()));
2✔
520
         }
521

522
         boost::asio::io_service io;
1✔
523

524
         TLS_Asio_HTTP_Server server(io, listen_port, creds, policy, session_mgr, max_clients);
2✔
525

526
         std::vector<std::shared_ptr<std::thread>> threads;
1✔
527

528
         // run forever... first thread is main calling io.run below
529
         for(size_t i = 2; i <= num_threads; ++i) {
2✔
530
            threads.push_back(std::make_shared<std::thread>([&io]() { io.run(); }));
2✔
531
         }
532

533
         io.run();
1✔
534

535
         for(size_t i = 0; i < threads.size(); ++i) {
2✔
536
            threads[i]->join();
1✔
537
         }
538
      }
6✔
539
};
540

541
BOTAN_REGISTER_COMMAND("tls_http_server", TLS_HTTP_Server);
2✔
542

543
}  // namespace Botan_CLI
544

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

© 2025 Coveralls, Inc