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

randombit / botan / 5079590438

25 May 2023 12:28PM UTC coverage: 92.228% (+0.5%) from 91.723%
5079590438

Pull #3502

github

Pull Request #3502: Apply clang-format to the codebase

75589 of 81959 relevant lines covered (92.23%)

12139530.51 hits per line

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

87.88
/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 <string>
18
   #include <thread>
19
   #include <vector>
20

21
   #define _GLIBCXX_HAVE_GTHR_DEFAULT
22
   #include <botan/internal/os_utils.h>
23
   #include <boost/asio.hpp>
24
   #include <boost/bind.hpp>
25

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

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

39
   #include "tls_helpers.h"
40

41
   #if BOOST_VERSION >= 107000
42
      #define GET_IO_SERVICE(s) (static_cast<boost::asio::io_context&>((s).get_executor().context()))
43
   #else
44
      #define GET_IO_SERVICE(s) ((s).get_io_service())
45
   #endif
46

47
namespace Botan_CLI {
48

49
namespace {
50

51
using boost::asio::ip::tcp;
52

53
inline void log_error(const char* msg) { std::cout << msg << std::endl; }
×
54

55
inline void log_exception(const char* where, const std::exception& e) {
×
56
   std::cout << where << ' ' << e.what() << std::endl;
×
57
}
×
58

59
class ServerStatus {
60
   public:
61
      ServerStatus(size_t max_clients) : m_max_clients(max_clients), m_clients_serviced(0) {}
1✔
62

63
      bool should_exit() const {
4✔
64
         if(m_max_clients == 0)
4✔
65
            return false;
66

67
         return clients_serviced() >= m_max_clients;
4✔
68
      }
69

70
      void client_serviced() { m_clients_serviced++; }
4✔
71

72
      size_t clients_serviced() const { return m_clients_serviced.load(); }
4✔
73

74
   private:
75
      size_t m_max_clients;
76
      std::atomic<size_t> m_clients_serviced;
77
};
78

79
/*
80
* This is an incomplete and highly buggy HTTP request parser. It is just
81
* barely sufficient to handle a GET request sent by a browser.
82
*/
83
class HTTP_Parser final {
8✔
84
   public:
85
      class Request {
86
         public:
87
            const std::string& verb() const { return m_verb; }
6✔
88

89
            const std::string& location() const { return m_location; }
4✔
90

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

93
            Request(const std::string& verb,
4✔
94
                    const std::string& location,
95
                    const std::map<std::string, std::string>& headers) :
4✔
96
                  m_verb(verb), m_location(location), m_headers(headers) {}
8✔
97

98
         private:
99
            std::string m_verb;
100
            std::string m_location;
101
            std::map<std::string, std::string> m_headers;
102
      };
103

104
      class Callbacks {
4✔
105
         public:
106
            virtual void handle_http_request(const Request& request) = 0;
107
            virtual ~Callbacks() = default;
×
108
      };
109

110
      HTTP_Parser(Callbacks& cb) : m_cb(cb) {}
4✔
111

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

115
         std::istringstream strm(m_req_buf);
4✔
116

117
         std::string http_version;
4✔
118
         std::string verb;
4✔
119
         std::string location;
4✔
120
         std::map<std::string, std::string> headers;
4✔
121

122
         strm >> verb >> location >> http_version;
4✔
123

124
         if(verb.empty() || location.empty())
4✔
125
            return;
×
126

127
         while(true) {
22✔
128
            std::string header_line;
22✔
129
            std::getline(strm, header_line);
22✔
130

131
            if(header_line == "\r") {
22✔
132
               continue;
8✔
133
            }
134

135
            auto delim = header_line.find(": ");
14✔
136
            if(delim == std::string::npos) {
14✔
137
               break;
138
            }
139

140
            const std::string hdr_name = header_line.substr(0, delim);
10✔
141
            const std::string hdr_val = header_line.substr(delim + 2, std::string::npos);
10✔
142

143
            headers[hdr_name] = hdr_val;
10✔
144

145
            if(headers.size() > 1024)
10✔
146
               throw Botan::Invalid_Argument("Too many HTTP headers sent in request");
×
147
         }
28✔
148

149
         if(verb != "" && location != "") {
4✔
150
            Request req(verb, location, headers);
4✔
151
            m_cb.handle_http_request(req);
4✔
152
            m_req_buf.clear();
4✔
153
         } else
4✔
154
            printf("ignoring\n");
4✔
155
      }
4✔
156

157
   private:
158
      Callbacks& m_cb;
159
      std::string m_req_buf;
160
};
161

162
static const size_t READBUF_SIZE = 4096;
163

164
class TLS_Asio_HTTP_Session final : public std::enable_shared_from_this<TLS_Asio_HTTP_Session>,
165
                                    public Botan::TLS::Callbacks,
166
                                    public HTTP_Parser::Callbacks {
167
   public:
168
      typedef std::shared_ptr<TLS_Asio_HTTP_Session> pointer;
169

170
      static pointer create(boost::asio::io_service& io,
4✔
171
                            std::shared_ptr<Botan::TLS::Session_Manager> session_manager,
172
                            std::shared_ptr<Botan::Credentials_Manager> credentials,
173
                            std::shared_ptr<Botan::TLS::Policy> policy) {
174
         auto session = std::make_shared<TLS_Asio_HTTP_Session>(io);
4✔
175

176
         // Defer the setup of the TLS server to make use of
177
         // shared_from_this() which wouldn't work in the c'tor.
178
         session->setup(session_manager, credentials, policy);
12✔
179

180
         return session;
4✔
181
      }
×
182

183
      tcp::socket& client_socket() { return m_client_socket; }
184

185
      void start() {
4✔
186
         m_c2s.resize(READBUF_SIZE);
4✔
187
         client_read(boost::system::error_code(), 0);  // start read loop
4✔
188
      }
4✔
189

190
      void stop() {
4✔
191
         m_tls->close();
4✔
192

193
         // Need to explicitly destroy the TLS::Server object to break the
194
         // circular ownership of shared_from_this() and the shared_ptr of
195
         // this kept inside the TLS::Channel.
196
         m_tls.reset();
4✔
197
      }
4✔
198

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

201
   private:
202
      void setup(std::shared_ptr<Botan::TLS::Session_Manager> session_manager,
4✔
203
                 std::shared_ptr<Botan::Credentials_Manager> credentials,
204
                 std::shared_ptr<Botan::TLS::Policy> policy) {
205
         m_tls = std::make_unique<Botan::TLS::Server>(shared_from_this(), session_manager, credentials, policy, m_rng);
4✔
206
      }
4✔
207

208
      void client_read(const boost::system::error_code& error, size_t bytes_transferred) {
20✔
209
         if(error) {
20✔
210
            return stop();
4✔
211
         }
212

213
         if(!m_tls) {
16✔
214
            log_error("Received client data after close");
×
215
            return;
×
216
         }
217

218
         try {
16✔
219
            m_tls->received_data(&m_c2s[0], bytes_transferred);
16✔
220
         } catch(Botan::Exception& e) {
×
221
            log_exception("TLS connection failed", e);
×
222
            return stop();
×
223
         }
×
224

225
         m_client_socket.async_read_some(boost::asio::buffer(&m_c2s[0], m_c2s.size()),
32✔
226
                                         m_strand.wrap(boost::bind(&TLS_Asio_HTTP_Session::client_read,
32✔
227
                                                                   shared_from_this(),
32✔
228
                                                                   boost::asio::placeholders::error,
229
                                                                   boost::asio::placeholders::bytes_transferred)));
230
      }
231

232
      void handle_client_write_completion(const boost::system::error_code& error) {
21✔
233
         if(error) {
21✔
234
            return stop();
×
235
         }
236

237
         m_s2c.clear();
21✔
238

239
         if(m_s2c_pending.empty() && (!m_tls || m_tls->is_closed_for_writing())) {
21✔
240
            m_client_socket.close();
4✔
241
         }
242
         tls_emit_data({});  // initiate another write if needed
21✔
243
      }
244

245
      std::string tls_server_choose_app_protocol(const std::vector<std::string>& /*client_protos*/) override {
×
246
         return "http/1.1";
×
247
      }
248

249
      void tls_record_received(uint64_t /*rec_no*/, std::span<const uint8_t> buf) override {
4✔
250
         if(!m_http_parser)
4✔
251
            m_http_parser.reset(new HTTP_Parser(*this));
4✔
252

253
         m_http_parser->consume_input(buf);
4✔
254
      }
4✔
255

256
      std::string summarize_request(const HTTP_Parser::Request& request) {
2✔
257
         std::ostringstream strm;
2✔
258

259
         strm << "Client " << client_socket().remote_endpoint().address().to_string() << " requested " << request.verb()
4✔
260
              << " " << request.location() << "\n";
4✔
261

262
         if(request.headers().empty() == false) {
2✔
263
            strm << "Client HTTP headers:\n";
2✔
264
            for(auto kv : request.headers())
6✔
265
               strm << " " << kv.first << ": " << kv.second << "\n";
4✔
266
         }
267

268
         return strm.str();
4✔
269
      }
2✔
270

271
      void handle_http_request(const HTTP_Parser::Request& request) override {
4✔
272
         std::ostringstream response;
4✔
273
         if(request.verb() == "GET") {
4✔
274
            if(request.location() == "/" || request.location() == "/status") {
2✔
275
               const std::string http_summary = summarize_request(request);
2✔
276

277
               const std::string report = m_connection_summary + m_session_summary + m_chello_summary + http_summary;
4✔
278

279
               response << "HTTP/1.0 200 OK\r\n";
2✔
280
               response << "Server: " << Botan::version_string() << "\r\n";
4✔
281
               response << "Content-Type: text/plain\r\n";
2✔
282
               response << "Content-Length: " << report.size() << "\r\n";
2✔
283
               response << "\r\n";
2✔
284

285
               response << report;
2✔
286
            } else {
4✔
287
               response << "HTTP/1.0 404 Not Found\r\n\r\n";
×
288
            }
289
         } else {
290
            response << "HTTP/1.0 405 Method Not Allowed\r\n\r\n";
2✔
291
         }
292

293
         const std::string response_str = response.str();
4✔
294
         m_tls->send(response_str);
4✔
295
         m_tls->close();
4✔
296
      }
4✔
297

298
      void tls_emit_data(std::span<const uint8_t> buf) override {
49✔
299
         if(!buf.empty()) {
49✔
300
            m_s2c_pending.insert(m_s2c_pending.end(), buf.begin(), buf.end());
28✔
301
         }
302

303
         // no write now active and we still have output pending
304
         if(m_s2c.empty() && !m_s2c_pending.empty()) {
49✔
305
            std::swap(m_s2c_pending, m_s2c);
21✔
306

307
            boost::asio::async_write(m_client_socket,
21✔
308
                                     boost::asio::buffer(&m_s2c[0], m_s2c.size()),
21✔
309
                                     m_strand.wrap(boost::bind(&TLS_Asio_HTTP_Session::handle_client_write_completion,
42✔
310
                                                               shared_from_this(),
42✔
311
                                                               boost::asio::placeholders::error)));
312
         }
313
      }
49✔
314

315
      void tls_session_activated() override {
4✔
316
         std::ostringstream strm;
4✔
317

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

320
         m_connection_summary = strm.str();
4✔
321
      }
4✔
322

323
      void tls_session_established(const Botan::TLS::Session_Summary& session) override {
4✔
324
         std::ostringstream strm;
4✔
325

326
         strm << "Version: " << session.version().to_string() << "\n";
8✔
327
         strm << "Ciphersuite: " << session.ciphersuite().to_string() << "\n";
8✔
328
         if(const auto& session_id = session.session_id(); !session_id.empty()) {
4✔
329
            strm << "SessionID: " << Botan::hex_encode(session_id.get()) << "\n";
8✔
330
         }
331
         if(!session.server_info().hostname().empty()) {
8✔
332
            strm << "SNI: " << session.server_info().hostname() << "\n";
12✔
333
         }
334

335
         m_session_summary = strm.str();
4✔
336
      }
4✔
337

338
      void tls_inspect_handshake_msg(const Botan::TLS::Handshake_Message& message) override {
34✔
339
         if(message.type() == Botan::TLS::Handshake_Type::ClientHello) {
34✔
340
            const Botan::TLS::Client_Hello& client_hello = dynamic_cast<const Botan::TLS::Client_Hello&>(message);
6✔
341

342
            std::ostringstream strm;
6✔
343

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

346
            strm << "Client offered following ciphersuites:\n";
6✔
347
            for(uint16_t suite_id : client_hello.ciphersuites()) {
74✔
348
               const auto ciphersuite = Botan::TLS::Ciphersuite::by_id(suite_id);
68✔
349

350
               strm << " - 0x" << std::hex << std::setfill('0') << std::setw(4) << suite_id << std::dec
68✔
351
                    << std::setfill(' ') << std::setw(0) << " ";
68✔
352

353
               if(ciphersuite && ciphersuite->valid())
68✔
354
                  strm << ciphersuite->to_string() << "\n";
186✔
355
               else if(suite_id == 0x00FF)
6✔
356
                  strm << "Renegotiation SCSV\n";
6✔
357
               else
358
                  strm << "Unknown ciphersuite\n";
×
359
            }
360

361
            m_chello_summary = strm.str();
6✔
362
         }
6✔
363
      }
34✔
364

365
      void tls_alert(Botan::TLS::Alert alert) override {
×
366
         if(alert.type() == Botan::TLS::Alert::CloseNotify) {
×
367
            m_tls->close();
×
368
         } else {
369
            std::cout << "Alert " << alert.type_string() << std::endl;
×
370
         }
371
      }
×
372

373
      boost::asio::io_service::strand m_strand;
374

375
      tcp::socket m_client_socket;
376

377
      std::shared_ptr<Botan::RandomNumberGenerator> m_rng;
378
      std::unique_ptr<Botan::TLS::Server> m_tls;
379
      std::string m_chello_summary;
380
      std::string m_connection_summary;
381
      std::string m_session_summary;
382
      std::unique_ptr<HTTP_Parser> m_http_parser;
383

384
      std::vector<uint8_t> m_c2s;
385
      std::vector<uint8_t> m_s2c;
386
      std::vector<uint8_t> m_s2c_pending;
387
};
388

389
class TLS_Asio_HTTP_Server final {
390
   public:
391
      typedef TLS_Asio_HTTP_Session session;
392

393
      TLS_Asio_HTTP_Server(boost::asio::io_service& io,
1✔
394
                           unsigned short port,
395
                           std::shared_ptr<Botan::Credentials_Manager> creds,
396
                           std::shared_ptr<Botan::TLS::Policy> policy,
397
                           std::shared_ptr<Botan::TLS::Session_Manager> session_mgr,
398
                           size_t max_clients) :
1✔
399
            m_acceptor(io, tcp::endpoint(tcp::v4(), port)),
1✔
400
            m_creds(creds),
1✔
401
            m_policy(policy),
1✔
402
            m_session_manager(session_mgr),
1✔
403
            m_status(max_clients) {
1✔
404
         serve_one_session();
1✔
405
      }
1✔
406

407
   private:
408
      void serve_one_session() {
4✔
409
         auto new_session = session::create(GET_IO_SERVICE(m_acceptor), m_session_manager, m_creds, m_policy);
20✔
410
         ;
4✔
411

412
         m_acceptor.async_accept(
8✔
413
            new_session->client_socket(),
4✔
414
            boost::bind(&TLS_Asio_HTTP_Server::handle_accept, this, new_session, boost::asio::placeholders::error));
12✔
415
      }
4✔
416

417
      void handle_accept(session::pointer new_session, const boost::system::error_code& error) {
4✔
418
         if(!error) {
4✔
419
            new_session->start();
4✔
420
            m_status.client_serviced();
4✔
421

422
            if(!m_status.should_exit()) {
4✔
423
               serve_one_session();
3✔
424
            }
425
         }
426
      }
4✔
427

428
      tcp::acceptor m_acceptor;
429

430
      std::shared_ptr<Botan::Credentials_Manager> m_creds;
431
      std::shared_ptr<Botan::TLS::Policy> m_policy;
432
      std::shared_ptr<Botan::TLS::Session_Manager> m_session_manager;
433
      ServerStatus m_status;
434
};
435

436
}
437

438
class TLS_HTTP_Server final : public Command {
439
   public:
440
      TLS_HTTP_Server() :
2✔
441
            Command(
442
               "tls_http_server server_cert server_key "
443
               "--port=443 --policy=default --threads=0 --max-clients=0 "
444
               "--session-db= --session-db-pass=") {}
4✔
445

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

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

450
      size_t thread_count() const {
1✔
451
         if(size_t t = get_arg_sz("threads"))
1✔
452
            return t;
453
         if(size_t t = Botan::OS::get_cpu_available())
1✔
454
            return t;
1✔
455
         return 2;
456
      }
457

458
      void go() override {
1✔
459
         const uint16_t listen_port = get_arg_u16("port");
1✔
460

461
         const std::string server_crt = get_arg("server_cert");
1✔
462
         const std::string server_key = get_arg("server_key");
1✔
463

464
         const size_t num_threads = thread_count();
1✔
465
         const size_t max_clients = get_arg_sz("max-clients");
1✔
466

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

469
         auto policy = load_tls_policy(get_arg("policy"));
2✔
470

471
         std::shared_ptr<Botan::TLS::Session_Manager> session_mgr;
1✔
472

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

475
         if(!sessions_db.empty()) {
1✔
476
   #if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER)
477
            const std::string sessions_passphrase = get_passphrase_arg("Session DB passphrase", "session-db-pass");
×
478
            session_mgr.reset(
×
479
               new Botan::TLS::Session_Manager_SQLite(sessions_passphrase, rng_as_shared(), sessions_db));
×
480
   #else
481
            throw CLI_Error_Unsupported("Sqlite3 support not available");
482
   #endif
483
         }
×
484

485
         if(!session_mgr) {
1✔
486
            session_mgr.reset(new Botan::TLS::Session_Manager_In_Memory(rng_as_shared()));
2✔
487
         }
488

489
         boost::asio::io_service io;
1✔
490

491
         TLS_Asio_HTTP_Server server(io, listen_port, creds, policy, session_mgr, max_clients);
3✔
492

493
         std::vector<std::shared_ptr<std::thread>> threads;
1✔
494

495
         // run forever... first thread is main calling io.run below
496
         for(size_t i = 2; i <= num_threads; ++i) {
2✔
497
            threads.push_back(std::make_shared<std::thread>([&io]() { io.run(); }));
2✔
498
         }
499

500
         io.run();
1✔
501

502
         for(size_t i = 0; i < threads.size(); ++i) {
2✔
503
            threads[i]->join();
1✔
504
         }
505
      }
6✔
506
};
507

508
BOTAN_REGISTER_COMMAND("tls_http_server", TLS_HTTP_Server);
2✔
509

510
}
511

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