aboutsummaryrefslogtreecommitdiffstats
path: root/src/cli/tls_server.cpp
blob: 0a133cffdd7eef025f6123926debfda073570ee3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
/*
* TLS echo server using BSD sockets
* (C) 2014 Jack Lloyd
*     2017 René Korthaus, Rohde & Schwarz Cybersecurity
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "cli.h"
#include "sandbox.h"

#if defined(BOTAN_HAS_TLS) && defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) && \
   (defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2))

#if defined(SO_USER_COOKIE)
#define SOCKET_ID 1
#else
#define SOCKET_ID 0
#endif

#include <botan/tls_server.h>
#include <botan/tls_policy.h>
#include <botan/hex.h>
#include <botan/internal/os_utils.h>

#include <list>
#include <fstream>

#include "credentials.h"
#include "socket_utils.h"

namespace Botan_CLI {

class TLS_Server final : public Command, public Botan::TLS::Callbacks
   {
   public:
#if SOCKET_ID
      TLS_Server() : Command("tls_server cert key --port=443 --type=tcp --policy= --dump-traces= --max-clients=0 --socket-id=0")
#else
      TLS_Server() : Command("tls_server cert key --port=443 --type=tcp --policy= --dump-traces= --max-clients=0")
#endif
         {
         init_sockets();
         }

      ~TLS_Server()
         {
         stop_sockets();
         }

      std::string group() const override
         {
         return "tls";
         }

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

      void go() override
         {
         const std::string server_crt = get_arg("cert");
         const std::string server_key = get_arg("key");
         const uint16_t port = get_arg_u16("port");
         const size_t max_clients = get_arg_sz("max-clients");
         const std::string transport = get_arg("type");
         const std::string dump_traces_to = get_arg("dump-traces");
#if SOCKET_ID
         m_socket_id = get_arg_sz("socket-id");
#endif

         if(transport != "tcp" && transport != "udp")
            {
            throw CLI_Usage_Error("Invalid transport type '" + transport + "' for TLS");
            }

         m_is_tcp = (transport == "tcp");

         std::unique_ptr<Botan::TLS::Policy> policy;
         const std::string policy_file = get_arg("policy");
         if(policy_file.size() > 0)
            {
            std::ifstream policy_stream(policy_file);
            if(!policy_stream.good())
               {
               error_output() << "Failed reading policy file\n";
               return;
               }
            policy.reset(new Botan::TLS::Text_Policy(policy_stream));
            }

         if(!policy)
            {
            policy.reset(new Botan::TLS::Policy);
            }

         Botan::TLS::Session_Manager_In_Memory session_manager(rng()); // TODO sqlite3

         Basic_Credentials_Manager creds(rng(), server_crt, server_key);

         output() << "Listening for new connections on " << transport << " port " << port << std::endl;

         if(!m_sandbox.init())
            {
            error_output() << "Failed sandboxing\n";
            return;
            }

         int server_fd = make_server_socket(port);
         size_t clients_served = 0;

         while(true)
            {
            if(max_clients > 0 && clients_served >= max_clients)
               break;

            if(m_is_tcp)
               {
               m_socket = ::accept(server_fd, nullptr, nullptr);
               }
            else
               {
               struct sockaddr_in from;
               socklen_t from_len = sizeof(sockaddr_in);

               void* peek_buf = nullptr;
               size_t peek_len = 0;

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

               if(::recvfrom(server_fd, static_cast<char*>(peek_buf), peek_len, MSG_PEEK, reinterpret_cast<struct sockaddr*>(&from), &from_len) != 0)
                  {
                  throw CLI_Error("Could not peek next packet");
                  }

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

            clients_served++;

            Botan::TLS::Server server(
               *this,
               session_manager,
               creds,
               *policy,
               rng(),
               m_is_tcp == false);

            std::unique_ptr<std::ostream> dump_stream;

            if(!dump_traces_to.empty())
               {
               uint64_t timestamp = Botan::OS::get_high_resolution_clock();
               const std::string dump_file =
                  dump_traces_to + "/tls_" + std::to_string(timestamp) + ".bin";
               dump_stream.reset(new std::ofstream(dump_file.c_str()));
               }

            try
               {
               while(!server.is_closed())
                  {
                  try
                     {
                     uint8_t buf[4 * 1024] = { 0 };
                     ssize_t got = ::read(m_socket, buf, sizeof(buf));

                     if(got == -1)
                        {
                        error_output() << "Error in socket read - " << std::strerror(errno) << std::endl;
                        break;
                        }

                     if(got == 0)
                        {
                        error_output() << "EOF on socket" << std::endl;
                        break;
                        }

                     if(dump_stream)
                        {
                        dump_stream->write(reinterpret_cast<const char*>(buf), got);
                        }

                     server.received_data(buf, got);

                     while(server.is_active() && !m_pending_output.empty())
                        {
                        std::string output = m_pending_output.front();
                        m_pending_output.pop_front();
                        server.send(output);

                        if(output == "quit\n")
                           {
                           server.close();
                           }
                        }
                     }
                  catch(std::exception& e)
                     {
                     error_output() << "Connection problem: " << e.what() << std::endl;
                     if(m_is_tcp)
                        {
                        ::close(m_socket);
                        m_socket = -1;
                        }
                     }
                  }
               }
            catch(Botan::Exception& e)
               {
               error_output() << "Connection failed: " << e.what() << "\n";
               }

            if(m_is_tcp)
               {
               ::close(m_socket);
               m_socket = -1;
               }
            }

         ::close(server_fd);
         }
   private:
      int make_server_socket(uint16_t port)
         {
         const int type = m_is_tcp ? SOCK_STREAM : SOCK_DGRAM;

         int fd = ::socket(PF_INET, type, 0);
         if(fd == -1)
            {
            throw CLI_Error("Unable to acquire socket");
            }

         sockaddr_in socket_info;
         Botan::clear_mem(&socket_info, 1);
         socket_info.sin_family = AF_INET;
         socket_info.sin_port = htons(port);

         // FIXME: support limiting listeners
         socket_info.sin_addr.s_addr = INADDR_ANY;

         if(::bind(fd, reinterpret_cast<struct sockaddr*>(&socket_info), sizeof(struct sockaddr)) != 0)
            {
            ::close(fd);
            throw CLI_Error("server bind failed");
            }

         if(m_is_tcp)
            {
            if(::listen(fd, 100) != 0)
               {
               ::close(fd);
               throw CLI_Error("listen failed");
               }
            }
         if(m_socket_id > 0)
            {
#if SOCKET_ID
            // Other oses could have other means to trace sockets
#if defined(SO_USER_COOKIE)
            if(::setsockopt(fd, SOL_SOCKET, SO_USER_COOKIE, reinterpret_cast<const void *>(&m_socket_id), sizeof(m_socket_id)) != 0)
               {
               // Failed but not world-ending issue
               output() << "set socket cookie id failed" << std::endl;
               }
#endif
#endif
            }
         return fd;
         }

      bool tls_session_established(const Botan::TLS::Session& session) override
         {
         output() << "Handshake complete, " << session.version().to_string()
                  << " using " << session.ciphersuite().to_string() << std::endl;

         if(!session.session_id().empty())
            {
            output() << "Session ID " << Botan::hex_encode(session.session_id()) << std::endl;
            }

         if(!session.session_ticket().empty())
            {
            output() << "Session ticket " << Botan::hex_encode(session.session_ticket()) << std::endl;
            }

         return true;
         }

      void tls_record_received(uint64_t, const uint8_t input[], size_t input_len) override
         {
         for(size_t i = 0; i != input_len; ++i)
            {
            const char c = static_cast<char>(input[i]);
            m_line_buf += c;
            if(c == '\n')
               {
               m_pending_output.push_back(m_line_buf);
               m_line_buf.clear();
               }
            }
         }

      void tls_emit_data(const uint8_t buf[], size_t length) override
         {
         if(m_is_tcp)
            {
            ssize_t sent = ::send(m_socket, buf, length, MSG_NOSIGNAL);

            if(sent == -1)
               {
               error_output() << "Error writing to socket - " << std::strerror(errno) << std::endl;
               }
            else if(sent != static_cast<ssize_t>(length))
               {
               error_output() << "Packet of length " << length << " truncated to " << sent << std::endl;
               }
            }
         else
            {
            while(length)
               {
               ssize_t sent = ::send(m_socket, buf, length, MSG_NOSIGNAL);

               if(sent == -1)
                  {
                  if(errno == EINTR)
                     {
                     sent = 0;
                     }
                  else
                     {
                     throw CLI_Error("Socket write failed");
                     }
                  }

               buf += sent;
               length -= sent;
               }
            }
         }

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

      std::string tls_server_choose_app_protocol(const std::vector<std::string>&) override
         {
         // we ignore whatever the client sends here
         return "echo/0.1";
         }

      int m_socket = -1;
      bool m_is_tcp = false;
      uint32_t m_socket_id = 0;
      std::string m_line_buf;
      std::list<std::string> m_pending_output;
      Sandbox m_sandbox;
   };

BOTAN_REGISTER_COMMAND("tls_server", TLS_Server);

}

#endif