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

randombit / botan / 5230455705

10 Jun 2023 02:30PM UTC coverage: 91.715% (-0.03%) from 91.746%
5230455705

push

github

randombit
Merge GH #3584 Change clang-format AllowShortFunctionsOnASingleLine config from All to Inline

77182 of 84154 relevant lines covered (91.72%)

11975295.43 hits per line

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

87.5
/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) {
×
54
   std::cout << msg << std::endl;
×
55
}
56

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

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

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

69
         return clients_serviced() >= m_max_clients;
4✔
70
      }
71

72
      void client_serviced() { m_clients_serviced++; }
4✔
73

74
      size_t clients_serviced() const { return m_clients_serviced.load(); }
4✔
75

76
   private:
77
      size_t m_max_clients;
78
      std::atomic<size_t> m_clients_serviced;
79
};
80

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

91
            const std::string& location() const { return m_location; }
4✔
92

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

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

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

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

112
      HTTP_Parser(Callbacks& cb) : m_cb(cb) {}
4✔
113

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

117
         std::istringstream strm(m_req_buf);
4✔
118

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

124
         strm >> verb >> location >> http_version;
4✔
125

126
         if(verb.empty() || location.empty())
4✔
127
            return;
×
128

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

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

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

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

145
            headers[hdr_name] = hdr_val;
10✔
146

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

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

159
   private:
160
      Callbacks& m_cb;
161
      std::string m_req_buf;
162
};
163

164
static const size_t READBUF_SIZE = 4096;
165

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

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

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

182
         return session;
4✔
183
      }
×
184

185
      tcp::socket& client_socket() { return m_client_socket; }
186

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

192
      void stop() {
4✔
193
         m_tls->close();
4✔
194

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

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

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

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

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

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

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

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

239
         m_s2c.clear();
21✔
240

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

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

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

255
         m_http_parser->consume_input(buf);
4✔
256
      }
4✔
257

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

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

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

270
         return strm.str();
4✔
271
      }
2✔
272

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

279
               const std::string report = m_connection_summary + m_session_summary + m_chello_summary + http_summary;
4✔
280

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

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

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

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

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

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

317
      void tls_session_activated() override {
4✔
318
         std::ostringstream strm;
4✔
319

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

322
         m_connection_summary = strm.str();
4✔
323
      }
4✔
324

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

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

337
         m_session_summary = strm.str();
4✔
338
      }
4✔
339

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

344
            std::ostringstream strm;
6✔
345

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

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

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

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

363
            m_chello_summary = strm.str();
6✔
364
         }
6✔
365
      }
34✔
366

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

375
      boost::asio::io_service::strand m_strand;
376

377
      tcp::socket m_client_socket;
378

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

386
      std::vector<uint8_t> m_c2s;
387
      std::vector<uint8_t> m_s2c;
388
      std::vector<uint8_t> m_s2c_pending;
389
};
390

391
class TLS_Asio_HTTP_Server final {
392
   public:
393
      typedef TLS_Asio_HTTP_Session session;
394

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

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

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

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

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

430
      tcp::acceptor m_acceptor;
431

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

438
}  // namespace
439

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

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

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

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

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

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

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

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

471
         auto policy = load_tls_policy(get_arg("policy"));
2✔
472

473
         std::shared_ptr<Botan::TLS::Session_Manager> session_mgr;
1✔
474

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

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

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

491
         boost::asio::io_service io;
1✔
492

493
         TLS_Asio_HTTP_Server server(io, listen_port, creds, policy, session_mgr, max_clients);
3✔
494

495
         std::vector<std::shared_ptr<std::thread>> threads;
1✔
496

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

502
         io.run();
1✔
503

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

510
BOTAN_REGISTER_COMMAND("tls_http_server", TLS_HTTP_Server);
2✔
511

512
}  // namespace Botan_CLI
513

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