Coverage Report

Created: 2026-12-01 06:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/pdns/pdns/dnsdistdist/tcpiohandler.cc
Line
Count
Source
1
/*
2
 * This file is part of PowerDNS or dnsdist.
3
 * Copyright -- PowerDNS.COM B.V. and its contributors
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of version 2 of the GNU General Public License as
7
 * published by the Free Software Foundation.
8
 *
9
 * In addition, for the avoidance of any doubt, permission is granted to
10
 * link this program with OpenSSL and to (re)distribute the binaries
11
 * produced as the result of such linking.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
 */
22
23
#include "config.h"
24
#include "dolog.hh"
25
#include "iputils.hh"
26
#include "lock.hh"
27
#include "logging.hh"
28
#include "tcpiohandler.hh"
29
30
const bool TCPIOHandler::s_disableConnectForUnitTests = false;
31
32
#ifdef HAVE_LIBSODIUM
33
#include <sodium.h>
34
#else
35
#include "credentials.hh"
36
#endif /* HAVE_LIBSODIUM */
37
38
#if defined(SSL_MODE_ASYNC) && defined(MOCK_SSL_ASYNC)
39
#include "libssl-async-mock.hh"
40
#endif
41
42
TLSCtx::tickets_key_added_hook TLSCtx::s_ticketsKeyAddedHook{nullptr};
43
44
#if defined(HAVE_DNS_OVER_TLS) || defined(HAVE_DNS_OVER_HTTPS)
45
static std::vector<std::vector<uint8_t>> getALPNVector(TLSFrontend::ALPN alpn, bool client)
46
0
{
47
0
  if (alpn == TLSFrontend::ALPN::DoT) {
48
    /* we want to set the ALPN to dot (RFC7858), if only to mitigate the ALPACA attack */
49
0
    return std::vector<std::vector<uint8_t>>{{'d', 'o', 't'}};
50
0
  }
51
0
  if (alpn == TLSFrontend::ALPN::DoH) {
52
0
    if (client) {
53
      /* we want to set the ALPN to h2, if only to mitigate the ALPACA attack */
54
0
      return std::vector<std::vector<uint8_t>>{{'h', '2'}};
55
0
    }
56
    /* For server contexts, we want to set the ALPN for DoH (note that h2o sets it own ALPN values):
57
       - HTTP/1.1 so that the OpenSSL callback ALPN accepts it, letting us later return a static response
58
       - HTTP/2
59
    */
60
0
    return std::vector<std::vector<uint8_t>>{{'h', '2'},{'h', 't', 't', 'p', '/', '1', '.', '1'}};
61
0
  }
62
0
  return {};
63
0
}
64
65
#ifdef HAVE_LIBSSL
66
67
namespace {
68
bool shouldDoVerboseLogging()
69
0
{
70
0
#ifdef DNSDIST
71
0
  return dnsdist::configuration::getCurrentRuntimeConfiguration().d_verbose;
72
#elif defined(RECURSOR)
73
  return false;
74
#else
75
  return true;
76
#endif
77
0
}
78
}
79
80
#include <openssl/conf.h>
81
#include <openssl/err.h>
82
#include <openssl/rand.h>
83
#include <openssl/ssl.h>
84
#include <openssl/x509v3.h>
85
86
#include "libssl.hh"
87
88
static void resetOpenSSLErrorState()
89
0
{
90
0
#if !defined(OPENSSL_VERSION_MAJOR) || OPENSSL_VERSION_MAJOR < 4
91
  /* this is really needed: before 4.0.0 SSL_get_error was looking at
92
     the per-thread (not per-connection!!) error queue, so an error
93
     could linger around and clobber unrelated connections.. */
94
0
  ERR_clear_error();
95
0
#endif
96
0
}
97
98
static int sni_server_name_callback(SSL* ssl, int* /* alert */, void* arg);
99
100
class OpenSSLFrontendContext
101
{
102
public:
103
0
  OpenSSLFrontendContext(const ComboAddress& addr, const TLSConfig& tlsConfig): d_ticketKeys(tlsConfig.d_numberOfTicketsKeys)
104
0
  {
105
0
    registerOpenSSLUser();
106
107
0
    auto [ctx, warnings] = libssl_init_server_context(tlsConfig);
108
0
    for (const auto& warning : warnings) {
109
0
#if defined(DNSDIST)
110
0
      SLOG(warnlog("%s", warning),
111
0
           dnsdist::logging::getTopLogger("openssl-frontend")->info(Logr::Warning, warning));
112
#else /* DNSDIST */
113
      warnlog("%s", warning);
114
#endif /* DNSDIST */
115
0
    }
116
    // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer): it cannot be initialized before calling libssl_init_server_context()
117
0
    d_ocspResponses = std::move(ctx.d_ocspResponses);
118
    // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer): it cannot be initialized before calling libssl_init_server_context()
119
0
    d_tlsCtx = std::move(ctx.d_defaultContext);
120
    // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer): it cannot be initialized before calling libssl_init_server_context()
121
0
    d_sniMap = std::move(ctx.d_sniMap);
122
0
    for (auto& entry : d_sniMap) {
123
0
      SSL_CTX_set_tlsext_servername_callback(entry.second.get(), &sni_server_name_callback); // NOLINT(cppcoreguidelines-pro-type-cstyle-cast)
124
0
    }
125
126
0
    if (!d_tlsCtx) {
127
0
      ERR_print_errors_fp(stderr);
128
0
      throw std::runtime_error("Error creating TLS context on " + addr.toStringWithPort());
129
0
    }
130
0
  }
131
132
  void cleanup()
133
0
  {
134
0
    d_tlsCtx.reset();
135
0
136
0
    unregisterOpenSSLUser();
137
0
  }
138
139
  OpenSSLTLSTicketKeysRing d_ticketKeys;
140
  std::map<int, std::string> d_ocspResponses;
141
  pdns::libssl::ServerContext::SNIToContextMap d_sniMap;
142
  std::shared_ptr<SSL_CTX> d_tlsCtx{nullptr};
143
  pdns::UniqueFilePtr d_keyLogFile{nullptr};
144
};
145
146
147
static int sni_server_name_callback(SSL* ssl, int* /* alert */, void* /* arg */)
148
0
{
149
0
  const auto* serverName = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
150
0
  if (serverName == nullptr) {
151
0
    return SSL_TLSEXT_ERR_NOACK;
152
0
  }
153
  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): OpenSSL's API
154
0
  auto* frontendCtx = reinterpret_cast<OpenSSLFrontendContext*>(libssl_get_ticket_key_callback_data(ssl));
155
0
  if (frontendCtx == nullptr) {
156
0
    return SSL_TLSEXT_ERR_OK;
157
0
  }
158
159
0
  auto serverNameView = std::string_view(serverName);
160
161
0
  auto mapIt = frontendCtx->d_sniMap.find(serverNameView);
162
0
  if (mapIt == frontendCtx->d_sniMap.end()) {
163
    /* keep the default certificate */
164
0
    return SSL_TLSEXT_ERR_OK;
165
0
  }
166
167
  /* if it fails there is nothing we can do,
168
     let's hope OpenSSL will fall back to the existing,
169
     default certificate*/
170
0
  SSL_set_SSL_CTX(ssl, mapIt->second.get());
171
0
  return SSL_TLSEXT_ERR_OK;
172
0
}
173
174
class OpenSSLSession : public TLSSession
175
{
176
public:
177
0
  OpenSSLSession(std::unique_ptr<SSL_SESSION, void(*)(SSL_SESSION*)>&& sess): d_sess(std::move(sess))
178
0
  {
179
0
  }
180
181
  std::unique_ptr<SSL_SESSION, void(*)(SSL_SESSION*)> getNative()
182
0
  {
183
0
    return std::move(d_sess);
184
0
  }
185
186
private:
187
  std::unique_ptr<SSL_SESSION, void(*)(SSL_SESSION*)> d_sess;
188
};
189
190
class OpenSSLTLSIOCtx;
191
192
class OpenSSLTLSConnection: public TLSConnection
193
{
194
public:
195
  /* server side connection */
196
0
  OpenSSLTLSConnection(int socket, const struct timeval& timeout, std::shared_ptr<const OpenSSLTLSIOCtx> tlsCtx, std::unique_ptr<SSL, void(*)(SSL*)>&& conn, [[maybe_unused]] bool asyncMode): d_tlsCtx(std::move(tlsCtx)), d_conn(std::move(conn)), d_timeout(timeout)
197
0
  {
198
0
    d_socket = socket;
199
200
0
    if (!d_conn) {
201
0
      VERBOSESLOG(infolog("Error creating TLS object"),
202
0
                  dnsdist::logging::getTopLogger("openssl-server-side")->info(Logr::Info, "Error creating server-side TLS object"));
203
0
      if (shouldDoVerboseLogging()) {
204
0
        ERR_print_errors_fp(stderr);
205
0
      }
206
0
      throw std::runtime_error("Error creating TLS object");
207
0
    }
208
209
0
    if (SSL_set_fd(d_conn.get(), d_socket) == 0) {
210
0
      throw std::runtime_error("Error assigning socket");
211
0
    }
212
213
0
    SSL_set_ex_data(d_conn.get(), getConnectionIndex(), this);
214
215
#if defined(SSL_MODE_ASYNC) && defined(MOCK_SSL_ASYNC)
216
    if (asyncMode) {
217
      d_mockAsyncEngine = std::make_unique<MockAsyncEngine>();
218
    }
219
#endif /* defined(SSL_MODE_ASYNC) && defined(MOCK_SSL_ASYNC) */
220
0
  }
221
222
  /* client-side connection */
223
0
  OpenSSLTLSConnection(std::string hostname, bool hostIsAddr, int socket, const struct timeval& timeout, std::shared_ptr<const OpenSSLTLSIOCtx> tlsCtx, std::unique_ptr<SSL, void(*)(SSL*)>&& conn): d_tlsCtx(std::move(tlsCtx)), d_conn(std::move(conn)), d_hostname(std::move(hostname)), d_timeout(timeout), d_isClient(true)
224
0
  {
225
0
    d_socket = socket;
226
227
0
    if (!d_conn) {
228
0
      VERBOSESLOG(infolog("Error creating TLS object"),
229
0
                  dnsdist::logging::getTopLogger("openssl-client-side")->info(Logr::Info, "Error creating client-side TLS object"));
230
0
      if (shouldDoVerboseLogging()) {
231
0
        ERR_print_errors_fp(stderr);
232
0
      }
233
0
      throw std::runtime_error("Error creating TLS object");
234
0
    }
235
236
0
    if (SSL_set_fd(d_conn.get(), d_socket) == 0) {
237
0
      throw std::runtime_error("Error assigning socket");
238
0
    }
239
240
    /* set outgoing Server Name Indication */
241
0
    if (!d_hostname.empty() && SSL_set_tlsext_host_name(d_conn.get(), d_hostname.c_str()) != 1) {
242
0
      throw std::runtime_error("Error setting TLS SNI to " + d_hostname);
243
0
    }
244
245
0
    if (hostIsAddr) {
246
0
      X509_VERIFY_PARAM *param = SSL_get0_param(d_conn.get());
247
      /* Enable automatic IP checks */
248
0
      X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
249
0
      if (X509_VERIFY_PARAM_set1_ip_asc(param, d_hostname.c_str()) != 1) {
250
0
        throw std::runtime_error("Error setting TLS IP for certificate validation");
251
0
      }
252
0
    }
253
0
    else {
254
0
      SSL_set_hostflags(d_conn.get(), X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
255
0
#if !defined(OPENSSL_VERSION_MAJOR) || OPENSSL_VERSION_MAJOR < 4
256
0
      auto ret = SSL_set1_host(d_conn.get(), d_hostname.c_str());
257
#else
258
      auto ret = SSL_set1_dnsname(d_conn.get(), d_hostname.c_str());
259
#endif
260
0
      if (ret != 1) {
261
0
        throw std::runtime_error("Error setting TLS hostname for certificate validation");
262
0
      }
263
0
    }
264
265
0
    SSL_set_ex_data(d_conn.get(), getConnectionIndex(), this);
266
0
  }
267
268
  std::vector<int> getAsyncFDs() override
269
0
  {
270
0
    std::vector<int> results;
271
0
#ifdef SSL_MODE_ASYNC
272
#ifdef MOCK_SSL_ASYNC
273
    if (d_mockAsyncEngine) {
274
      return d_mockAsyncEngine->getAsyncFDs();
275
    }
276
#endif /* MOCK_SSL_ASYNC */
277
0
    if (SSL_waiting_for_async(d_conn.get()) != 1) {
278
0
      return results;
279
0
    }
280
281
0
    std::array<OSSL_ASYNC_FD, 32> fds{};
282
0
    size_t numfds = fds.size();
283
0
    SSL_get_all_async_fds(d_conn.get(), nullptr, &numfds);
284
0
    if (numfds == 0) {
285
0
      return results;
286
0
    }
287
288
0
    SSL_get_all_async_fds(d_conn.get(), fds.data(), &numfds);
289
0
    results.reserve(numfds);
290
0
    for (size_t idx = 0; idx < numfds; idx++) {
291
0
      results.push_back(fds.at(idx));
292
0
    }
293
0
#endif
294
0
    return results;
295
0
  }
296
297
  [[nodiscard]] IOState convertIORequestToIOState(int res) const
298
0
  {
299
0
    int error = SSL_get_error(d_conn.get(), res);
300
0
    if (error == SSL_ERROR_WANT_READ) {
301
0
      return IOState::NeedRead;
302
0
    }
303
0
    if (error == SSL_ERROR_WANT_WRITE) {
304
0
      return IOState::NeedWrite;
305
0
    }
306
0
    if (error == SSL_ERROR_SYSCALL) {
307
0
      auto savederrno = errno;
308
0
      resetOpenSSLErrorState();
309
0
      if (savederrno == 0) {
310
0
        throw std::runtime_error("TLS connection closed by remote end");
311
0
      }
312
313
0
      throw std::runtime_error("Syscall error while processing TLS connection: " + stringerror(savederrno));
314
0
    }
315
0
    if (error == SSL_ERROR_ZERO_RETURN) {
316
0
      throw std::runtime_error("TLS connection closed by remote end");
317
0
    }
318
0
#ifdef SSL_MODE_ASYNC
319
0
    if (error == SSL_ERROR_WANT_ASYNC) {
320
0
      return IOState::Async;
321
0
    }
322
0
#endif
323
0
    else {
324
0
      if (shouldDoVerboseLogging()) {
325
0
        auto errorStr = libssl_get_error_string();
326
0
        resetOpenSSLErrorState();
327
0
        throw std::runtime_error("Error while processing TLS connection: (" + std::to_string(error) + ") " + errorStr);
328
0
      }
329
330
0
      resetOpenSSLErrorState();
331
0
      throw std::runtime_error("Error while processing TLS connection: " + std::to_string(error));
332
0
    }
333
0
  }
334
335
  void handleIORequest(int res, const struct timeval& timeout)
336
0
  {
337
0
    auto state = convertIORequestToIOState(res);
338
0
    if (state == IOState::NeedRead) {
339
0
      res = waitForData(d_socket, timeout);
340
0
      if (res == 0) {
341
0
        throw std::runtime_error("Timeout while reading from TLS connection");
342
0
      }
343
0
      if (res < 0) {
344
0
        throw std::runtime_error("Error waiting to read from TLS connection");
345
0
      }
346
0
    }
347
0
    else if (state == IOState::NeedWrite) {
348
0
      res = waitForRWData(d_socket, false, timeout);
349
0
      if (res == 0) {
350
0
        throw std::runtime_error("Timeout while writing to TLS connection");
351
0
      }
352
0
      if (res < 0) {
353
0
        throw std::runtime_error("Error waiting to write to TLS connection");
354
0
      }
355
0
    }
356
0
  }
357
358
  IOState tryConnect(bool fastOpen, const ComboAddress& remote) override
359
0
  {
360
    /* sorry */
361
0
    (void) fastOpen;
362
0
    (void) remote;
363
364
0
    resetOpenSSLErrorState();
365
0
    int res = SSL_connect(d_conn.get());
366
0
    if (res == 1) {
367
0
      return IOState::Done;
368
0
    }
369
0
    if (res < 0) {
370
0
      return convertIORequestToIOState(res);
371
0
    }
372
373
0
    throw std::runtime_error("Error establishing a TLS connection");
374
0
  }
375
376
  void connect(bool fastOpen, const ComboAddress& remote, const struct timeval &timeout) override
377
0
  {
378
    /* sorry */
379
0
    (void) fastOpen;
380
0
    (void) remote;
381
382
0
    struct timeval start{0,0};
383
0
    struct timeval remainingTime = timeout;
384
0
    if (timeout.tv_sec != 0 || timeout.tv_usec != 0) {
385
0
      gettimeofday(&start, nullptr);
386
0
    }
387
388
0
    resetOpenSSLErrorState();
389
0
    int res = 0;
390
0
    do {
391
0
      res = SSL_connect(d_conn.get());
392
0
      if (res < 0) {
393
0
        handleIORequest(res, remainingTime);
394
0
      }
395
396
0
      if (timeout.tv_sec != 0 || timeout.tv_usec != 0) {
397
0
        struct timeval now{};
398
0
        gettimeofday(&now, nullptr);
399
0
        struct timeval elapsed = now - start;
400
0
        if (now < start || remainingTime < elapsed) {
401
0
          throw runtime_error("Timeout while establishing TLS connection");
402
0
        }
403
0
        start = now;
404
0
        remainingTime = remainingTime - elapsed;
405
0
      }
406
0
    }
407
0
    while (res != 1);
408
0
  }
409
410
  IOState tryHandshake() override
411
0
  {
412
0
    if (isClient()) {
413
      /* In client mode, the handshake is initiated by the call to SSL_connect()
414
         done from connect()/tryConnect().
415
         In blocking mode it does not return before the handshake has been finished,
416
         and in non-blocking mode calling SSL_connect() once is enough for SSL_write()
417
         and SSL_read() to transparently continue to negotiate the connection after that
418
         (equivalent to doing SSL_set_connect_state() plus trying to write).
419
      */
420
0
      return IOState::Done;
421
0
    }
422
423
#if defined(SSL_MODE_ASYNC) && defined(MOCK_SSL_ASYNC)
424
    if (d_mockAsyncEngine && d_mockAsyncEngine->isInAsyncOperation()) {
425
      return IOState::Async;
426
    }
427
#endif
428
429
0
    resetOpenSSLErrorState();
430
    /* As explained above in the client-mode block, we only need to call SSL_accept() once
431
       for SSL_write() and SSL_read() to transparently continue to negotiate the connection after that.
432
       It is equivalent to calling SSL_set_accept_state() plus trying to read.
433
    */
434
0
    int res = SSL_accept(d_conn.get());
435
0
    if (res == 1) {
436
0
      return IOState::Done;
437
0
    }
438
0
    if (res < 0) {
439
0
      return convertIORequestToIOState(res);
440
0
    }
441
442
0
    throw std::runtime_error("Error accepting TLS connection");
443
0
  }
444
445
  void doHandshake() override
446
0
  {
447
0
    if (isClient()) {
448
      /* we are a client, nothing to do, see the non-blocking version */
449
0
      return;
450
0
    }
451
452
0
    resetOpenSSLErrorState();
453
0
    int res = 0;
454
0
    do {
455
0
      res = SSL_accept(d_conn.get());
456
0
      if (res < 0) {
457
0
        handleIORequest(res, d_timeout);
458
0
      }
459
0
    }
460
0
    while (res < 0);
461
462
0
    if (res != 1) {
463
0
      throw std::runtime_error("Error accepting TLS connection");
464
0
    }
465
0
  }
466
467
  IOState tryWrite(const PacketBuffer& buffer, size_t& pos, size_t toWrite) override
468
0
  {
469
0
    if (isClient() && !d_connected) {
470
0
      if (d_ktls) {
471
        /* work-around to get kTLS to be started, as we cannot do that until after the socket has been connected */
472
0
        SSL_set_fd(d_conn.get(), SSL_get_fd(d_conn.get()));
473
0
      }
474
0
    }
475
476
0
    resetOpenSSLErrorState();
477
0
    do {
478
0
      int res = SSL_write(d_conn.get(), &buffer.at(pos), static_cast<int>(toWrite - pos));
479
0
      if (res <= 0) {
480
0
        return convertIORequestToIOState(res);
481
0
      }
482
0
      pos += static_cast<size_t>(res);
483
0
    }
484
0
    while (pos < toWrite);
485
486
0
    if (!d_connected) {
487
0
      d_connected = true;
488
0
    }
489
490
0
    return IOState::Done;
491
0
  }
492
493
  IOState tryRead(PacketBuffer& buffer, size_t& pos, size_t toRead, bool allowIncomplete) override
494
0
  {
495
0
    resetOpenSSLErrorState();
496
0
    do {
497
0
      int res = SSL_read(d_conn.get(), &buffer.at(pos), static_cast<int>(toRead - pos));
498
0
      if (res <= 0) {
499
0
        return convertIORequestToIOState(res);
500
0
      }
501
0
      pos += static_cast<size_t>(res);
502
0
      if (allowIncomplete) {
503
0
        break;
504
0
      }
505
0
    }
506
0
    while (pos < toRead);
507
0
    return IOState::Done;
508
0
  }
509
510
  size_t read(void* buffer, size_t bufferSize, const struct timeval& readTimeout, const struct timeval& totalTimeout, bool allowIncomplete) override
511
0
  {
512
0
    size_t got = 0;
513
0
    struct timeval start = {0, 0};
514
0
    struct timeval remainingTime = totalTimeout;
515
0
    if (totalTimeout.tv_sec != 0 || totalTimeout.tv_usec != 0) {
516
0
      gettimeofday(&start, nullptr);
517
0
    }
518
519
0
    resetOpenSSLErrorState();
520
0
    do {
521
      // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast, cppcoreguidelines-pro-bounds-pointer-arithmetic)
522
0
      int res = SSL_read(d_conn.get(), (reinterpret_cast<char *>(buffer) + got), static_cast<int>(bufferSize - got));
523
0
      if (res <= 0) {
524
0
        handleIORequest(res, readTimeout);
525
0
      }
526
0
      else {
527
0
        got += static_cast<size_t>(res);
528
0
        if (allowIncomplete) {
529
0
          break;
530
0
        }
531
0
      }
532
533
0
      if (totalTimeout.tv_sec != 0 || totalTimeout.tv_usec != 0) {
534
0
        struct timeval now{};
535
0
        gettimeofday(&now, nullptr);
536
0
        struct timeval elapsed = now - start;
537
0
        if (now < start || remainingTime < elapsed) {
538
0
          throw runtime_error("Timeout while reading data");
539
0
        }
540
0
        start = now;
541
0
        remainingTime = remainingTime - elapsed;
542
0
      }
543
0
    }
544
0
    while (got < bufferSize);
545
546
0
    return got;
547
0
  }
548
549
  size_t write(const void* buffer, size_t bufferSize, const struct timeval& writeTimeout) override
550
0
  {
551
0
    size_t got = 0;
552
0
    resetOpenSSLErrorState();
553
0
    do {
554
      // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast, cppcoreguidelines-pro-bounds-pointer-arithmetic)
555
0
      int res = SSL_write(d_conn.get(), (reinterpret_cast<const char *>(buffer) + got), static_cast<int>(bufferSize - got));
556
0
      if (res <= 0) {
557
0
        handleIORequest(res, writeTimeout);
558
0
      }
559
0
      else {
560
0
        got += static_cast<size_t>(res);
561
0
      }
562
0
    }
563
0
    while (got < bufferSize);
564
565
0
    return got;
566
0
  }
567
568
  [[nodiscard]] bool isUsable() const override
569
0
  {
570
0
    if (!d_conn) {
571
0
      return false;
572
0
    }
573
574
0
    resetOpenSSLErrorState();
575
0
    char buf{};
576
0
    int res = SSL_peek(d_conn.get(), &buf, sizeof(buf));
577
0
    if (res > 0) {
578
0
      return true;
579
0
    }
580
0
    try {
581
0
      (void)convertIORequestToIOState(res);
582
0
      return true;
583
0
    }
584
0
    catch (...) {
585
0
      return false;
586
0
    }
587
588
0
    return false;
589
0
  }
590
591
  void close() override
592
0
  {
593
0
    if (d_conn) {
594
0
      SSL_shutdown(d_conn.get());
595
0
    }
596
0
  }
597
598
  [[nodiscard]] std::string getServerNameIndication() const override
599
0
  {
600
0
    if (d_conn) {
601
0
      const char* value = SSL_get_servername(d_conn.get(), TLSEXT_NAMETYPE_host_name);
602
0
      if (value != nullptr) {
603
0
        return value;
604
0
      }
605
0
    }
606
0
    return {};
607
0
  }
608
609
  [[nodiscard]] std::vector<uint8_t> getNextProtocol() const override
610
0
  {
611
0
    std::vector<uint8_t> result;
612
0
    if (!d_conn) {
613
0
      return result;
614
0
    }
615
616
0
    const unsigned char* alpn = nullptr;
617
0
    unsigned int alpnLen  = 0;
618
0
    if (alpn == nullptr) {
619
0
      SSL_get0_alpn_selected(d_conn.get(), &alpn, &alpnLen);
620
0
    }
621
0
    if (alpn != nullptr && alpnLen > 0) {
622
      // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
623
0
      result.insert(result.end(), alpn, alpn + alpnLen);
624
0
    }
625
0
    return result;
626
0
  }
627
628
  [[nodiscard]] std::pair<long, std::string> getVerifyResult() const override
629
0
  {
630
0
    if (d_conn) {
631
0
      auto errorCode = SSL_get_verify_result(d_conn.get());
632
0
      auto certPresented = errorCode != X509_V_OK;
633
0
      if (!certPresented) {
634
0
        auto* cert = SSL_get_peer_certificate(d_conn.get());
635
0
        if (cert != nullptr) {
636
0
          certPresented = true;
637
0
          X509_free(cert);
638
0
        }
639
0
      }
640
0
      if (!certPresented) {
641
0
        return {-1, "No certificate presented by peer"};
642
0
      }
643
0
      const auto* errorMsg = X509_verify_cert_error_string(errorCode);
644
0
      return {errorCode, errorMsg != nullptr ? errorMsg : "No details available"};
645
0
    }
646
0
    return {0, ""};
647
0
  }
648
649
  [[nodiscard]] LibsslTLSVersion getTLSVersion() const override
650
0
  {
651
0
    auto proto = SSL_version(d_conn.get());
652
0
    switch (proto) {
653
0
    case TLS1_VERSION:
654
0
      return LibsslTLSVersion::TLS10;
655
0
    case TLS1_1_VERSION:
656
0
      return LibsslTLSVersion::TLS11;
657
0
    case TLS1_2_VERSION:
658
0
      return LibsslTLSVersion::TLS12;
659
0
#ifdef TLS1_3_VERSION
660
0
    case TLS1_3_VERSION:
661
0
      return LibsslTLSVersion::TLS13;
662
0
#endif /* TLS1_3_VERSION */
663
0
    default:
664
0
      return LibsslTLSVersion::Unknown;
665
0
    }
666
0
  }
667
668
  [[nodiscard]] bool hasSessionBeenResumed() const override
669
0
  {
670
0
    if (d_conn) {
671
0
      return SSL_session_reused(d_conn.get()) != 0;
672
0
    }
673
0
    return false;
674
0
  }
675
676
  std::vector<std::unique_ptr<TLSSession>> getSessions() override
677
0
  {
678
0
    return std::move(d_tlsSessions);
679
0
  }
680
681
  void setSession(std::unique_ptr<TLSSession>& session) override
682
0
  {
683
0
    auto* sess = dynamic_cast<OpenSSLSession*>(session.get());
684
0
    if (sess == nullptr) {
685
0
      throw std::runtime_error("Unable to convert OpenSSL session");
686
0
    }
687
688
0
    auto native = sess->getNative();
689
0
    auto ret = SSL_set_session(d_conn.get(), native.get());
690
0
    if (ret != 1) {
691
0
      throw std::runtime_error("Error setting up session: " + libssl_get_error_string());
692
0
    }
693
0
    session.reset();
694
0
  }
695
696
  void addNewTicket(SSL_SESSION* session)
697
0
  {
698
0
    d_tlsSessions.push_back(std::make_unique<OpenSSLSession>(std::unique_ptr<SSL_SESSION, void (*)(SSL_SESSION*)>(session, SSL_SESSION_free)));
699
0
  }
700
701
  void enableKTLS()
702
0
  {
703
0
    d_ktls = true;
704
0
  }
705
706
  [[nodiscard]] bool isClient() const
707
0
  {
708
0
    return d_isClient;
709
0
  }
710
711
  static void generateConnectionIndexIfNeeded()
712
0
  {
713
0
    auto init = s_initTLSConnIndex.lock();
714
0
    if (*init) {
715
0
      return;
716
0
    }
717
718
    /* not initialized yet */
719
0
    s_tlsConnIndex = SSL_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
720
0
    if (s_tlsConnIndex == -1) {
721
0
      throw std::runtime_error("Error getting an index for TLS connection data");
722
0
    }
723
724
0
    *init = true;
725
0
  }
726
727
  static int getConnectionIndex()
728
0
  {
729
0
    return s_tlsConnIndex;
730
0
  }
731
732
private:
733
  static LockGuarded<bool> s_initTLSConnIndex;
734
  static int s_tlsConnIndex;
735
  std::vector<std::unique_ptr<TLSSession>> d_tlsSessions;
736
  const std::shared_ptr<const OpenSSLTLSIOCtx> d_tlsCtx; // we need to hold a reference to this to make sure that the context exists for as long as the connection, even if a reload happens in the meantime
737
  std::unique_ptr<SSL, void(*)(SSL*)> d_conn;
738
#if defined(SSL_MODE_ASYNC) && defined(MOCK_SSL_ASYNC)
739
  std::unique_ptr<MockAsyncEngine> d_mockAsyncEngine;
740
#endif
741
  const std::string d_hostname;
742
  const timeval d_timeout;
743
  bool d_connected{false};
744
  bool d_ktls{false};
745
  const bool d_isClient{false};
746
};
747
748
LockGuarded<bool> OpenSSLTLSConnection::s_initTLSConnIndex{false};
749
int OpenSSLTLSConnection::s_tlsConnIndex{-1};
750
751
class OpenSSLTLSIOCtx: public TLSCtx, public std::enable_shared_from_this<OpenSSLTLSIOCtx>
752
{
753
  struct Private
754
  {
755
    explicit Private() = default;
756
  };
757
758
public:
759
  static std::shared_ptr<OpenSSLTLSIOCtx> createServerSideContext(TLSFrontend& frontend)
760
0
  {
761
0
    return std::make_shared<OpenSSLTLSIOCtx>(frontend, Private());
762
0
  }
763
764
  static std::shared_ptr<OpenSSLTLSIOCtx> createClientSideContext(const TLSContextParameters& params)
765
0
  {
766
0
    return std::make_shared<OpenSSLTLSIOCtx>(params, Private());
767
0
  }
768
769
  /* server side context */
770
0
  OpenSSLTLSIOCtx(TLSFrontend& frontend, [[maybe_unused]] Private priv): d_alpnProtos(getALPNVector(frontend.d_alpn, false)), d_feContext(std::make_unique<OpenSSLFrontendContext>(frontend.d_addr, frontend.d_tlsConfig)), d_asyncMode(frontend.d_tlsConfig.d_asyncMode)
771
0
  {
772
0
    OpenSSLTLSConnection::generateConnectionIndexIfNeeded();
773
774
0
    d_ticketsKeyRotationDelay = frontend.d_tlsConfig.d_ticketsKeyRotationDelay;
775
776
0
    for (auto& entry : d_feContext->d_sniMap) {
777
0
      auto* ctx = entry.second.get();
778
0
      if (frontend.d_tlsConfig.d_enableTickets && frontend.d_tlsConfig.d_numberOfTicketsKeys > 0) {
779
        /* use our own ticket keys handler so we can rotate them */
780
0
#if OPENSSL_VERSION_MAJOR >= 3
781
0
        SSL_CTX_set_tlsext_ticket_key_evp_cb(ctx, &OpenSSLTLSIOCtx::ticketKeyCb);
782
#else
783
        SSL_CTX_set_tlsext_ticket_key_cb(ctx, &OpenSSLTLSIOCtx::ticketKeyCb);
784
#endif
785
0
        libssl_set_ticket_key_callback_data(ctx, d_feContext.get());
786
0
      }
787
788
0
#ifndef DISABLE_OCSP_STAPLING
789
0
      if (!d_feContext->d_ocspResponses.empty()) {
790
0
        SSL_CTX_set_tlsext_status_cb(ctx, &OpenSSLTLSIOCtx::ocspStaplingCb); // NOLINT(cppcoreguidelines-pro-type-cstyle-cast)
791
0
        SSL_CTX_set_tlsext_status_arg(ctx, &d_feContext->d_ocspResponses);
792
0
      }
793
0
#endif /* DISABLE_OCSP_STAPLING */
794
795
0
      if (frontend.d_tlsConfig.d_readAhead) {
796
0
        SSL_CTX_set_read_ahead(ctx, 1);
797
0
      }
798
799
0
      libssl_set_error_counters_callback(*ctx, &frontend.d_tlsCounters);
800
801
0
      libssl_set_alpn_select_callback(ctx, alpnServerSelectCallback, this);
802
803
0
      if (!frontend.d_tlsConfig.d_keyLogFile.empty()) {
804
0
        d_feContext->d_keyLogFile = libssl_set_key_log_file(ctx, frontend.d_tlsConfig.d_keyLogFile);
805
0
      }
806
0
    }
807
808
0
    try {
809
0
      if (frontend.d_tlsConfig.d_ticketKeyFile.empty()) {
810
0
        if (d_ticketsKeyRotationDelay == 0) {
811
0
          throw std::runtime_error("Trying to start a TLS frontend without any TLS session ticket encryption key loaded AND with rotation disabled!");
812
0
        }
813
0
        handleTicketsKeyRotation(time(nullptr));
814
0
      }
815
0
      else {
816
0
        OpenSSLTLSIOCtx::loadTicketsKeys(frontend.d_tlsConfig.d_ticketKeyFile);
817
0
      }
818
0
    }
819
0
    catch (const std::exception& e) {
820
0
      throw;
821
0
    }
822
0
  }
823
824
  /* client side context */
825
  OpenSSLTLSIOCtx(const TLSContextParameters& params, [[maybe_unused]] Private priv)
826
0
  {
827
0
    int sslOptions =
828
0
      SSL_OP_NO_SSLv2 |
829
0
      SSL_OP_NO_SSLv3 |
830
0
      SSL_OP_NO_COMPRESSION |
831
0
      SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
832
0
      SSL_OP_SINGLE_DH_USE |
833
0
      SSL_OP_SINGLE_ECDH_USE |
834
0
#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
835
0
      SSL_OP_IGNORE_UNEXPECTED_EOF |
836
0
#endif
837
0
      SSL_OP_CIPHER_SERVER_PREFERENCE;
838
0
    if (!params.d_enableRenegotiation) {
839
0
#ifdef SSL_OP_NO_RENEGOTIATION
840
0
      sslOptions |= SSL_OP_NO_RENEGOTIATION;
841
#elif defined(SSL_OP_NO_CLIENT_RENEGOTIATION)
842
      sslOptions |= SSL_OP_NO_CLIENT_RENEGOTIATION;
843
#endif
844
0
    }
845
846
0
    if (params.d_ktls) {
847
0
#ifdef SSL_OP_ENABLE_KTLS
848
0
      sslOptions |= SSL_OP_ENABLE_KTLS;
849
0
      d_ktls = true;
850
0
#endif /* SSL_OP_ENABLE_KTLS */
851
0
    }
852
853
0
    registerOpenSSLUser();
854
855
0
    OpenSSLTLSConnection::generateConnectionIndexIfNeeded();
856
857
0
    d_tlsCtx = std::shared_ptr<SSL_CTX>(SSL_CTX_new(TLS_client_method()), SSL_CTX_free);
858
0
    if (!d_tlsCtx) {
859
0
      ERR_print_errors_fp(stderr);
860
0
      throw std::runtime_error("Error creating TLS context");
861
0
    }
862
863
0
    SSL_CTX_set_options(d_tlsCtx.get(), sslOptions);
864
0
#if defined(SSL_CTX_set_ecdh_auto)
865
0
#if !defined(OPENSSL_VERSION_MAJOR) || OPENSSL_VERSION_MAJOR < 4
866
0
    SSL_CTX_set_ecdh_auto(d_tlsCtx.get(), 1);
867
0
#endif /* OPENSSL_VERSION_MAJOR < 4 */
868
0
#endif
869
870
0
    if (!params.d_ciphers.empty()) {
871
0
      if (SSL_CTX_set_cipher_list(d_tlsCtx.get(), params.d_ciphers.c_str()) != 1) {
872
0
        ERR_print_errors_fp(stderr);
873
0
        throw std::runtime_error("Error setting the cipher list to '" + params.d_ciphers + "' for the TLS context");
874
0
      }
875
0
    }
876
0
#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
877
0
    if (!params.d_ciphers13.empty()) {
878
0
      if (SSL_CTX_set_ciphersuites(d_tlsCtx.get(), params.d_ciphers13.c_str()) != 1) {
879
0
        ERR_print_errors_fp(stderr);
880
0
        throw std::runtime_error("Error setting the TLS 1.3 cipher list to '" + params.d_ciphers13 + "' for the TLS context");
881
0
      }
882
0
    }
883
0
#endif /* HAVE_SSL_CTX_SET_CIPHERSUITES */
884
885
0
  if (!params.d_ecdheCurves.empty()) {
886
0
    if (SSL_CTX_set1_groups_list(d_tlsCtx.get(), params.d_ecdheCurves.c_str()) != 1) { // NOLINT(cppcoreguidelines-pro-type-cstyle-cast)
887
0
      ERR_print_errors_fp(stderr);
888
0
      throw std::runtime_error("Failed to set the TLS ECDHE curve to '" + params.d_ecdheCurves + "' for the TLS context");
889
0
    }
890
0
  }
891
892
0
    if (params.d_validateCertificates) {
893
0
      if (params.d_caStore.empty())  {
894
0
        if (SSL_CTX_set_default_verify_paths(d_tlsCtx.get()) != 1) {
895
0
          throw std::runtime_error("Error adding the system's default trusted CAs");
896
0
        }
897
0
      } else {
898
0
        if (SSL_CTX_load_verify_locations(d_tlsCtx.get(), params.d_caStore.c_str(), nullptr) != 1) {
899
0
          throw std::runtime_error("Error adding the trusted CAs file " + params.d_caStore);
900
0
        }
901
0
      }
902
903
0
      SSL_CTX_set_verify(d_tlsCtx.get(), SSL_VERIFY_PEER, nullptr);
904
0
    }
905
906
    /* we need to set SSL_SESS_CACHE_CLIENT for the "new ticket" callback (below) to be called,
907
       but we don't want OpenSSL to cache the session itself so we set SSL_SESS_CACHE_NO_INTERNAL_STORE as well */
908
0
    SSL_CTX_set_session_cache_mode(d_tlsCtx.get(), SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
909
0
    SSL_CTX_sess_set_new_cb(d_tlsCtx.get(), &OpenSSLTLSIOCtx::newTicketFromServerCb);
910
911
0
    if (!params.d_keyLogFile.empty()) {
912
0
      d_keyLogFile = libssl_set_key_log_file(d_tlsCtx.get(), params.d_keyLogFile);
913
0
    }
914
915
0
    libssl_set_alpn_protos(d_tlsCtx.get(), getALPNVector(params.d_alpn, true));
916
917
0
    if (!params.d_client_certificate.empty()) {
918
0
      std::optional<std::string> key = std::nullopt;
919
0
      if (!params.d_client_certificate_key.empty()) {
920
0
        key = params.d_client_certificate_key;
921
0
      }
922
0
      std::optional<std::string> password = std::nullopt;
923
0
      if (!params.d_client_certificate_password.empty()) {
924
0
        password = params.d_client_certificate_password;
925
0
      }
926
0
      TLSCertKeyPair pair{params.d_client_certificate, std::move(key), std::move(password)};
927
0
      std::vector<int> keyTypes;
928
0
      libssl_setup_context_no_sni(d_tlsCtx.get(), pair, keyTypes);
929
0
    }
930
931
0
#ifdef SSL_MODE_RELEASE_BUFFERS
932
0
    if (params.d_releaseBuffers) {
933
0
      SSL_CTX_set_mode(d_tlsCtx.get(), SSL_MODE_RELEASE_BUFFERS);
934
0
    }
935
0
#endif
936
0
  }
937
938
  OpenSSLTLSIOCtx(const OpenSSLTLSIOCtx&) = delete;
939
  OpenSSLTLSIOCtx(OpenSSLTLSIOCtx&&) = delete;
940
  OpenSSLTLSIOCtx& operator=(const OpenSSLTLSIOCtx&) = delete;
941
  OpenSSLTLSIOCtx& operator=(OpenSSLTLSIOCtx&&) = delete;
942
943
  ~OpenSSLTLSIOCtx() override
944
0
  {
945
0
    d_tlsCtx.reset();
946
0
    unregisterOpenSSLUser();
947
0
  }
948
949
#if OPENSSL_VERSION_MAJOR >= 3
950
  // NOLINTNEXTLINE(*-avoid-c-arrays) it's the API 
951
  static int ticketKeyCb(SSL* ssl, unsigned char keyName[TLS_TICKETS_KEY_NAME_SIZE], unsigned char* ivec, EVP_CIPHER_CTX* ectx, EVP_MAC_CTX* hctx, int enc)
952
#else
953
  // NOLINTNEXTLINE(*-avoid-c-arrays) it's the API 
954
  static int ticketKeyCb(SSL* ssl, unsigned char keyName[TLS_TICKETS_KEY_NAME_SIZE], unsigned char* ivec, EVP_CIPHER_CTX* ectx, HMAC_CTX* hctx, int enc)
955
#endif
956
0
  {
957
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
958
0
    auto* ctx = reinterpret_cast<OpenSSLFrontendContext*>(libssl_get_ticket_key_callback_data(ssl));
959
0
    if (ctx == nullptr) {
960
0
      return -1;
961
0
    }
962
963
0
    int ret = libssl_ticket_key_callback(ssl, ctx->d_ticketKeys, keyName, ivec, ectx, hctx, enc);
964
0
    if (enc == 0) {
965
0
      if (ret == 0 || ret == 2) {
966
        // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
967
0
        auto* conn = reinterpret_cast<OpenSSLTLSConnection*>(SSL_get_ex_data(ssl, OpenSSLTLSConnection::getConnectionIndex()));
968
0
        if (conn != nullptr) {
969
0
          if (ret == 0) {
970
0
            conn->setUnknownTicketKey();
971
0
          }
972
0
          else if (ret == 2) {
973
0
            conn->setResumedFromInactiveTicketKey();
974
0
          }
975
0
        }
976
0
      }
977
0
    }
978
979
0
    return ret;
980
0
  }
981
982
#ifndef DISABLE_OCSP_STAPLING
983
  static int ocspStaplingCb(SSL* ssl, void* arg)
984
0
  {
985
0
    if (ssl == nullptr || arg == nullptr) {
986
0
      return SSL_TLSEXT_ERR_NOACK;
987
0
    }
988
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
989
0
    const auto* ocspMap = reinterpret_cast<std::map<int, std::string>*>(arg);
990
0
    return libssl_ocsp_stapling_callback(ssl, *ocspMap);
991
0
  }
992
#endif /* DISABLE_OCSP_STAPLING */
993
994
  static int newTicketFromServerCb(SSL* ssl, SSL_SESSION* session)
995
0
  {
996
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
997
0
    auto* conn = reinterpret_cast<OpenSSLTLSConnection*>(SSL_get_ex_data(ssl, OpenSSLTLSConnection::getConnectionIndex()));
998
0
    if (session == nullptr || conn == nullptr) {
999
0
      return 0;
1000
0
    }
1001
1002
0
    try {
1003
0
      conn->addNewTicket(session);
1004
0
    }
1005
    // NOLINTNEXTLINE(bugprone-empty-catch)
1006
0
    catch (...) {
1007
0
    }
1008
1009
0
    return 1;
1010
0
  }
1011
1012
  SSL_CTX* getOpenSSLContext() const
1013
0
  {
1014
0
    if (d_feContext) {
1015
0
      return d_feContext->d_tlsCtx.get();
1016
0
    }
1017
0
    return d_tlsCtx.get();
1018
0
  }
1019
1020
  std::unique_ptr<TLSConnection> getConnection(int socket, const struct timeval& timeout, time_t now) override
1021
0
  {
1022
0
    handleTicketsKeyRotation(now);
1023
1024
0
    return std::make_unique<OpenSSLTLSConnection>(socket, timeout, shared_from_this(), std::unique_ptr<SSL, void(*)(SSL*)>(SSL_new(getOpenSSLContext()), SSL_free), d_asyncMode);
1025
0
  }
1026
1027
  std::unique_ptr<TLSConnection> getClientConnection(const std::string& host, bool hostIsAddr, int socket, const struct timeval& timeout) override
1028
0
  {
1029
0
    auto conn = std::make_unique<OpenSSLTLSConnection>(host, hostIsAddr, socket, timeout, shared_from_this(), std::unique_ptr<SSL, void(*)(SSL*)>(SSL_new(getOpenSSLContext()), SSL_free));
1030
0
    if (d_ktls) {
1031
0
      conn->enableKTLS();
1032
0
    }
1033
0
    return conn;
1034
0
  }
1035
1036
  void rotateTicketsKey(time_t now) override
1037
0
  {
1038
0
    d_feContext->d_ticketKeys.rotateTicketsKey(now);
1039
1040
0
    if (d_ticketsKeyRotationDelay > 0) {
1041
0
      d_ticketsKeyNextRotation = now + d_ticketsKeyRotationDelay;
1042
0
    }
1043
0
  }
1044
1045
  void loadTicketsKeys(const std::string& keyFile) final
1046
0
  {
1047
0
    d_feContext->d_ticketKeys.loadTicketsKeys(keyFile);
1048
1049
0
    if (d_ticketsKeyRotationDelay > 0) {
1050
0
      d_ticketsKeyNextRotation = time(nullptr) + d_ticketsKeyRotationDelay;
1051
0
    }
1052
0
  }
1053
1054
  void loadTicketsKey(const std::string& key) final
1055
0
  {
1056
0
    d_feContext->d_ticketKeys.loadTicketsKey(key);
1057
1058
0
    if (d_ticketsKeyRotationDelay > 0) {
1059
0
      d_ticketsKeyNextRotation = time(nullptr) + d_ticketsKeyRotationDelay;
1060
0
    }
1061
0
  }
1062
1063
  size_t getTicketsKeysCount() override
1064
0
  {
1065
0
    return d_feContext->d_ticketKeys.getKeysCount();
1066
0
  }
1067
1068
  std::string getName() const override
1069
0
  {
1070
0
    return "openssl";
1071
0
  }
1072
1073
  bool isServerContext() const
1074
0
  {
1075
0
    return d_feContext != nullptr;
1076
0
  }
1077
1078
private:
1079
  /* called in a client context, if the client advertised more than one ALPN value and the server returned more than one as well, to select the one to use. */
1080
  static int alpnServerSelectCallback(SSL* /* ssl */, const unsigned char** out, unsigned char* outlen, const unsigned char* inBuffer, unsigned int inlen, void* arg)
1081
0
  {
1082
0
    if (arg == nullptr) {
1083
0
      return SSL_TLSEXT_ERR_ALERT_WARNING;
1084
0
    }
1085
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): OpenSSL's API
1086
0
    auto* obj = reinterpret_cast<OpenSSLTLSIOCtx*>(arg);
1087
1088
0
    const pdns::views::UnsignedCharView inView(inBuffer, inlen);
1089
    // Server preference algorithm as per RFC 7301 section 3.2
1090
0
    for (const auto& tentative : obj->d_alpnProtos) {
1091
0
      size_t pos = 0;
1092
0
      while (pos < inView.size()) {
1093
0
        size_t protoLen = inView.at(pos);
1094
0
        pos++;
1095
0
        if (protoLen > (inlen - pos)) {
1096
          /* something is very wrong */
1097
0
          return SSL_TLSEXT_ERR_ALERT_WARNING;
1098
0
        }
1099
1100
0
        if (tentative.size() == protoLen && memcmp(&inView.at(pos), tentative.data(), tentative.size()) == 0) {
1101
0
          *out = &inView.at(pos);
1102
0
          *outlen = protoLen;
1103
0
          return SSL_TLSEXT_ERR_OK;
1104
0
        }
1105
0
        pos += protoLen;
1106
0
      }
1107
0
    }
1108
1109
0
    return SSL_TLSEXT_ERR_NOACK;
1110
0
  }
1111
1112
  const std::vector<std::vector<uint8_t>> d_alpnProtos; // store the supported ALPN protocols, so that the server can select based on what the client sent
1113
  std::shared_ptr<SSL_CTX> d_tlsCtx{nullptr}; // client context, on a server-side the context is stored in d_feContext->d_tlsCtx
1114
  std::unique_ptr<OpenSSLFrontendContext> d_feContext{nullptr};
1115
  pdns::UniqueFilePtr d_keyLogFile{nullptr};
1116
  bool d_ktls{false};
1117
  bool d_asyncMode{false};
1118
};
1119
1120
#endif /* HAVE_LIBSSL */
1121
1122
#ifdef HAVE_GNUTLS
1123
#include <gnutls/gnutls.h>
1124
#include <gnutls/socket.h>
1125
#include <gnutls/x509.h>
1126
1127
static void safe_memory_lock([[maybe_unused]] void* data, [[maybe_unused]] size_t size)
1128
{
1129
#ifdef HAVE_LIBSODIUM
1130
  sodium_mlock(data, size);
1131
#endif
1132
}
1133
1134
static void safe_memory_release(void* data, size_t size)
1135
{
1136
#ifdef HAVE_LIBSODIUM
1137
  sodium_munlock(data, size);
1138
#else
1139
  SensitiveData::reallyClearContent(data, size);
1140
#endif
1141
}
1142
1143
class GnuTLSTicketsKey
1144
{
1145
public:
1146
  GnuTLSTicketsKey()
1147
  {
1148
    if (gnutls_session_ticket_key_generate(&d_key) != GNUTLS_E_SUCCESS) {
1149
      throw std::runtime_error("Error generating tickets key for TLS context");
1150
    }
1151
1152
    safe_memory_lock(d_key.data, d_key.size);
1153
  }
1154
1155
  GnuTLSTicketsKey(const std::string& key)
1156
  {
1157
    /* to be sure we are loading the correct amount of data, which
1158
       may change between versions, let's generate a correct key first */
1159
    if (gnutls_session_ticket_key_generate(&d_key) != GNUTLS_E_SUCCESS) {
1160
      throw std::runtime_error("Error generating tickets key (before parsing key file) for TLS context");
1161
    }
1162
1163
    safe_memory_lock(d_key.data, d_key.size);
1164
    if (key.size() != d_key.size) {
1165
      safe_memory_release(d_key.data, d_key.size);
1166
      gnutls_free(d_key.data);
1167
      d_key.data = nullptr;
1168
      throw std::runtime_error("Invalid GnuTLS ticket key size");
1169
    }
1170
    memcpy(d_key.data, key.data(), key.size());
1171
  }
1172
  GnuTLSTicketsKey(std::ifstream& file)
1173
  {
1174
    /* to be sure we are loading the correct amount of data, which
1175
       may change between versions, let's generate a correct key first */
1176
    if (gnutls_session_ticket_key_generate(&d_key) != GNUTLS_E_SUCCESS) {
1177
      throw std::runtime_error("Error generating tickets key (before parsing key file) for TLS context");
1178
    }
1179
1180
    safe_memory_lock(d_key.data, d_key.size);
1181
1182
    try {
1183
      file.read(reinterpret_cast<char*>(d_key.data), d_key.size);
1184
1185
      if (file.fail()) {
1186
        throw std::runtime_error("Invalid GnuTLS tickets key file");
1187
      }
1188
1189
    }
1190
    catch (const std::exception& e) {
1191
      safe_memory_release(d_key.data, d_key.size);
1192
      gnutls_free(d_key.data);
1193
      d_key.data = nullptr;
1194
      throw;
1195
    }
1196
  }
1197
  [[nodiscard]] std::string content() const
1198
  {
1199
    std::string result{};
1200
    if (d_key.data != nullptr && d_key.size > 0) {
1201
      // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
1202
      result.append(reinterpret_cast<const char*>(d_key.data), d_key.size);
1203
      safe_memory_lock(result.data(), result.size());
1204
    }
1205
    return result;
1206
  }
1207
1208
  ~GnuTLSTicketsKey()
1209
  {
1210
    if (d_key.data != nullptr && d_key.size > 0) {
1211
      safe_memory_release(d_key.data, d_key.size);
1212
    }
1213
    gnutls_free(d_key.data);
1214
    d_key.data = nullptr;
1215
  }
1216
  const gnutls_datum_t& getKey() const
1217
  {
1218
    return d_key;
1219
  }
1220
1221
private:
1222
  gnutls_datum_t d_key{nullptr, 0};
1223
};
1224
1225
class GnuTLSSession : public TLSSession
1226
{
1227
public:
1228
  GnuTLSSession(gnutls_datum_t& sess): d_sess(sess)
1229
  {
1230
    sess.data = nullptr;
1231
    sess.size = 0;
1232
  }
1233
1234
  ~GnuTLSSession() override
1235
  {
1236
    if (d_sess.data != nullptr && d_sess.size > 0) {
1237
      safe_memory_release(d_sess.data, d_sess.size);
1238
    }
1239
    gnutls_free(d_sess.data);
1240
    d_sess.data = nullptr;
1241
  }
1242
1243
  const gnutls_datum_t& getNative()
1244
  {
1245
    return d_sess;
1246
  }
1247
1248
private:
1249
  gnutls_datum_t d_sess{nullptr, 0};
1250
};
1251
1252
class GnuTLSConnection: public TLSConnection
1253
{
1254
public:
1255
  /* server side connection */
1256
  GnuTLSConnection(int socket, const struct timeval& timeout, std::shared_ptr<gnutls_certificate_credentials_st>& creds, const gnutls_priority_t priorityCache, std::shared_ptr<GnuTLSTicketsKey>& ticketsKey, bool enableTickets): d_creds(creds), d_ticketsKey(ticketsKey), d_conn(std::unique_ptr<gnutls_session_int, void(*)(gnutls_session_t)>(nullptr, gnutls_deinit))
1257
  {
1258
    unsigned int sslOptions = GNUTLS_SERVER | GNUTLS_NONBLOCK;
1259
#ifdef GNUTLS_NO_SIGNAL
1260
    sslOptions |= GNUTLS_NO_SIGNAL;
1261
#endif
1262
1263
    d_socket = socket;
1264
1265
    gnutls_session_t conn;
1266
    if (gnutls_init(&conn, sslOptions) != GNUTLS_E_SUCCESS) {
1267
      throw std::runtime_error("Error creating TLS connection");
1268
    }
1269
1270
    d_conn = std::unique_ptr<gnutls_session_int, void(*)(gnutls_session_t)>(conn, gnutls_deinit);
1271
    conn = nullptr;
1272
1273
    if (gnutls_credentials_set(d_conn.get(), GNUTLS_CRD_CERTIFICATE, d_creds.get()) != GNUTLS_E_SUCCESS) {
1274
      throw std::runtime_error("Error setting certificate and key to TLS connection");
1275
    }
1276
1277
    if (gnutls_priority_set(d_conn.get(), priorityCache) != GNUTLS_E_SUCCESS) {
1278
      throw std::runtime_error("Error setting ciphers to TLS connection");
1279
    }
1280
1281
    if (enableTickets && d_ticketsKey) {
1282
      const gnutls_datum_t& key = d_ticketsKey->getKey();
1283
      if (gnutls_session_ticket_enable_server(d_conn.get(), &key) != GNUTLS_E_SUCCESS) {
1284
        throw std::runtime_error("Error setting the tickets key to TLS connection");
1285
      }
1286
    }
1287
1288
    gnutls_transport_set_int(d_conn.get(), d_socket);
1289
1290
    /* timeouts are in milliseconds */
1291
    gnutls_handshake_set_timeout(d_conn.get(), timeout.tv_sec * 1000 + timeout.tv_usec / 1000);
1292
    gnutls_record_set_timeout(d_conn.get(), timeout.tv_sec * 1000 + timeout.tv_usec / 1000);
1293
  }
1294
1295
  /* client-side connection */
1296
  GnuTLSConnection(const std::string& host, int socket, const struct timeval& timeout, std::shared_ptr<gnutls_certificate_credentials_st>& creds, const gnutls_priority_t priorityCache, bool validateCerts): d_creds(creds), d_conn(std::unique_ptr<gnutls_session_int, void(*)(gnutls_session_t)>(nullptr, gnutls_deinit)), d_host(host), d_client(true)
1297
  {
1298
    unsigned int sslOptions = GNUTLS_CLIENT | GNUTLS_NONBLOCK;
1299
#ifdef GNUTLS_NO_SIGNAL
1300
    sslOptions |= GNUTLS_NO_SIGNAL;
1301
#endif
1302
1303
    d_socket = socket;
1304
1305
    gnutls_session_t conn;
1306
    if (gnutls_init(&conn, sslOptions) != GNUTLS_E_SUCCESS) {
1307
      throw std::runtime_error("Error creating TLS connection");
1308
    }
1309
1310
    d_conn = std::unique_ptr<gnutls_session_int, void(*)(gnutls_session_t)>(conn, gnutls_deinit);
1311
    conn = nullptr;
1312
1313
    int rc = gnutls_credentials_set(d_conn.get(), GNUTLS_CRD_CERTIFICATE, d_creds.get());
1314
    if (rc != GNUTLS_E_SUCCESS) {
1315
      throw std::runtime_error("Error setting certificate and key to TLS connection: " + std::string(gnutls_strerror(rc)));
1316
    }
1317
1318
    rc = gnutls_priority_set(d_conn.get(), priorityCache);
1319
    if (rc != GNUTLS_E_SUCCESS) {
1320
      throw std::runtime_error("Error setting ciphers to TLS connection: " + std::string(gnutls_strerror(rc)));
1321
    }
1322
1323
    gnutls_transport_set_int(d_conn.get(), d_socket);
1324
1325
    /* timeouts are in milliseconds */
1326
    gnutls_handshake_set_timeout(d_conn.get(),  timeout.tv_sec * 1000 + timeout.tv_usec / 1000);
1327
    gnutls_record_set_timeout(d_conn.get(),  timeout.tv_sec * 1000 + timeout.tv_usec / 1000);
1328
1329
#ifdef HAVE_GNUTLS_SESSION_SET_VERIFY_CERT
1330
    if (validateCerts && !d_host.empty()) {
1331
      gnutls_session_set_verify_cert(d_conn.get(), d_host.c_str(), GNUTLS_VERIFY_ALLOW_UNSORTED_CHAIN);
1332
      rc = gnutls_server_name_set(d_conn.get(), GNUTLS_NAME_DNS, d_host.c_str(), d_host.size());
1333
      if (rc != GNUTLS_E_SUCCESS) {
1334
        throw std::runtime_error("Error setting the SNI value to '" + d_host + "' on TLS connection: " + std::string(gnutls_strerror(rc)));
1335
      }
1336
    }
1337
#else
1338
    /* no hostname validation for you */
1339
#endif
1340
1341
    /* allow access to our data in the callbacks */
1342
    gnutls_session_set_ptr(d_conn.get(), this);
1343
    gnutls_handshake_set_hook_function(d_conn.get(), GNUTLS_HANDSHAKE_NEW_SESSION_TICKET, GNUTLS_HOOK_POST, newTicketFromServerCb);
1344
  }
1345
1346
  /* The callback prototype changed in 3.4.0. */
1347
#if GNUTLS_VERSION_NUMBER >= 0x030400
1348
  static int newTicketFromServerCb(gnutls_session_t session, unsigned int htype, unsigned post, unsigned int /* incoming */, const gnutls_datum_t* /* msg */)
1349
#else
1350
  static int newTicketFromServerCb(gnutls_session_t session, unsigned int htype, unsigned post, unsigned int /* incoming */)
1351
#endif /* GNUTLS_VERSION_NUMBER >= 0x030400 */
1352
  {
1353
    if (htype != GNUTLS_HANDSHAKE_NEW_SESSION_TICKET || post != GNUTLS_HOOK_POST || session == nullptr) {
1354
      return 0;
1355
    }
1356
1357
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): GnuTLS API
1358
    auto* conn = reinterpret_cast<GnuTLSConnection*>(gnutls_session_get_ptr(session));
1359
    if (conn == nullptr) {
1360
      return 0;
1361
    }
1362
1363
    gnutls_datum_t sess{nullptr, 0};
1364
    auto ret = gnutls_session_get_data2(session, &sess);
1365
    /* GnuTLS returns a 'fake' ticket of 4 bytes set to zero when there is no ticket available */
1366
    if (ret != GNUTLS_E_SUCCESS || sess.size <= 4) {
1367
      if (sess.data != nullptr) {
1368
        gnutls_free(sess.data);
1369
      }
1370
      return 0;
1371
    }
1372
    conn->d_tlsSessions.push_back(std::make_unique<GnuTLSSession>(sess));
1373
    return 0;
1374
  }
1375
1376
  IOState tryConnect(bool fastOpen, [[maybe_unused]] const ComboAddress& remote) override
1377
  {
1378
    int ret = 0;
1379
1380
    if (fastOpen) {
1381
#ifdef HAVE_GNUTLS_TRANSPORT_SET_FASTOPEN
1382
      gnutls_transport_set_fastopen(d_conn.get(), d_socket, const_cast<struct sockaddr*>(reinterpret_cast<const struct sockaddr*>(&remote)), remote.getSocklen(), 0);
1383
#endif
1384
    }
1385
1386
    do {
1387
      ret = gnutls_handshake(d_conn.get());
1388
      if (ret == GNUTLS_E_SUCCESS) {
1389
        d_handshakeDone = true;
1390
        return IOState::Done;
1391
      }
1392
      else if (ret == GNUTLS_E_AGAIN) {
1393
        int direction = gnutls_record_get_direction(d_conn.get());
1394
        return direction == 0 ? IOState::NeedRead : IOState::NeedWrite;
1395
      }
1396
      else if (gnutls_error_is_fatal(ret) || ret == GNUTLS_E_WARNING_ALERT_RECEIVED) {
1397
        throw std::runtime_error("Error establishing a new connection: " + std::string(gnutls_strerror(ret)));
1398
      }
1399
    } while (ret == GNUTLS_E_INTERRUPTED);
1400
1401
    throw std::runtime_error("Error establishing a new connection: " + std::string(gnutls_strerror(ret)));
1402
  }
1403
1404
  void connect(bool fastOpen, const ComboAddress& remote, const struct timeval& timeout) override
1405
  {
1406
    struct timeval start = {0, 0};
1407
    struct timeval remainingTime = timeout;
1408
    if (timeout.tv_sec != 0 || timeout.tv_usec != 0) {
1409
      gettimeofday(&start, nullptr);
1410
    }
1411
1412
    IOState state;
1413
    do {
1414
      state = tryConnect(fastOpen, remote);
1415
      if (state == IOState::Done) {
1416
        return;
1417
      }
1418
      else if (state == IOState::NeedRead) {
1419
        int result = waitForData(d_socket, remainingTime);
1420
        if (result <= 0) {
1421
          throw std::runtime_error("Error reading from TLS connection: " + std::to_string(result));
1422
        }
1423
      }
1424
      else if (state == IOState::NeedWrite) {
1425
        int result = waitForRWData(d_socket, false, remainingTime);
1426
        if (result <= 0) {
1427
          throw std::runtime_error("Error reading from TLS connection: " + std::to_string(result));
1428
        }
1429
      }
1430
1431
      if (timeout.tv_sec != 0 || timeout.tv_usec != 0) {
1432
        struct timeval now;
1433
        gettimeofday(&now, nullptr);
1434
        struct timeval elapsed = now - start;
1435
        if (now < start || remainingTime < elapsed) {
1436
          throw runtime_error("Timeout while establishing TLS connection");
1437
        }
1438
        start = now;
1439
        remainingTime = remainingTime - elapsed;
1440
      }
1441
    }
1442
    while (state != IOState::Done);
1443
  }
1444
1445
  void doHandshake() override
1446
  {
1447
    int ret = 0;
1448
    do {
1449
      ret = gnutls_handshake(d_conn.get());
1450
      if (gnutls_error_is_fatal(ret) || ret == GNUTLS_E_WARNING_ALERT_RECEIVED) {
1451
        if (d_client) {
1452
          throw std::runtime_error("Error establishing a new connection: " + std::string(gnutls_strerror(ret)));
1453
        }
1454
        else {
1455
          throw std::runtime_error("Error accepting a new connection: " + std::string(gnutls_strerror(ret)));
1456
        }
1457
      }
1458
    }
1459
    while (ret != GNUTLS_E_SUCCESS && ret == GNUTLS_E_INTERRUPTED);
1460
1461
    d_handshakeDone = true;
1462
  }
1463
1464
  IOState tryHandshake() override
1465
  {
1466
    int ret = 0;
1467
1468
    do {
1469
      ret = gnutls_handshake(d_conn.get());
1470
      if (ret == GNUTLS_E_SUCCESS) {
1471
        d_handshakeDone = true;
1472
        return IOState::Done;
1473
      }
1474
      else if (ret == GNUTLS_E_AGAIN) {
1475
        int direction = gnutls_record_get_direction(d_conn.get());
1476
        return direction == 0 ? IOState::NeedRead : IOState::NeedWrite;
1477
      }
1478
      else if (gnutls_error_is_fatal(ret) || ret == GNUTLS_E_WARNING_ALERT_RECEIVED) {
1479
        if (d_client) {
1480
          std::string error;
1481
#ifdef HAVE_GNUTLS_SESSION_GET_VERIFY_CERT_STATUS
1482
          if (ret == GNUTLS_E_CERTIFICATE_VERIFICATION_ERROR) {
1483
            gnutls_datum_t out;
1484
            if (gnutls_certificate_verification_status_print(gnutls_session_get_verify_cert_status(d_conn.get()), gnutls_certificate_type_get(d_conn.get()), &out, 0) == 0) {
1485
              error = " (" + std::string(reinterpret_cast<const char*>(out.data)) + ")";
1486
              gnutls_free(out.data);
1487
            }
1488
          }
1489
#endif /* HAVE_GNUTLS_SESSION_GET_VERIFY_CERT_STATUS */
1490
          throw std::runtime_error("Error accepting a new connection: " + std::string(gnutls_strerror(ret)) + error);
1491
        }
1492
        else {
1493
          throw std::runtime_error("Error establishing a new connection: " + std::string(gnutls_strerror(ret)));
1494
        }
1495
      }
1496
    } while (ret == GNUTLS_E_INTERRUPTED);
1497
1498
    if (d_client) {
1499
      throw std::runtime_error("Error establishinging a new connection: " + std::string(gnutls_strerror(ret)));
1500
    }
1501
    else {
1502
      throw std::runtime_error("Error accepting a new connection: " + std::string(gnutls_strerror(ret)));
1503
    }
1504
  }
1505
1506
  IOState tryWrite(const PacketBuffer& buffer, size_t& pos, size_t toWrite) override
1507
  {
1508
    if (!d_handshakeDone) {
1509
      /* As opposed to OpenSSL, GnuTLS will not transparently finish the handshake for us,
1510
         we need to keep calling gnutls_handshake() until the handshake has been finished. */
1511
      auto state = tryHandshake();
1512
      if (state != IOState::Done) {
1513
        return state;
1514
      }
1515
    }
1516
1517
    do {
1518
      ssize_t res = gnutls_record_send(d_conn.get(), reinterpret_cast<const char *>(&buffer.at(pos)), toWrite - pos);
1519
      if (res == 0) {
1520
        throw std::runtime_error("Error writing to TLS connection");
1521
      }
1522
      else if (res > 0) {
1523
        pos += static_cast<size_t>(res);
1524
      }
1525
      else if (res < 0) {
1526
        if (gnutls_error_is_fatal(res)) {
1527
          throw std::runtime_error("Fatal error writing to TLS connection: " + std::string(gnutls_strerror(res)));
1528
        }
1529
        else if (res == GNUTLS_E_AGAIN) {
1530
          return IOState::NeedWrite;
1531
        }
1532
        VERBOSESLOG(infolog("Warning, non-fatal error while writing to TLS connection: %s", gnutls_strerror(res)),
1533
                    dnsdist::logging::getTopLogger("gnutls")->error(Logr::Info, gnutls_strerror(res), "Non-fatal error while writing to TLS connection", "tls.provider", Logging::Loggable("GnuTLS")));
1534
      }
1535
    }
1536
    while (pos < toWrite);
1537
    return IOState::Done;
1538
  }
1539
1540
  IOState tryRead(PacketBuffer& buffer, size_t& pos, size_t toRead, bool allowIncomplete) override
1541
  {
1542
    if (!d_handshakeDone) {
1543
      /* As opposed to OpenSSL, GnuTLS will not transparently finish the handshake for us,
1544
         we need to keep calling gnutls_handshake() until the handshake has been finished. */
1545
      auto state = tryHandshake();
1546
      if (state != IOState::Done) {
1547
        return state;
1548
      }
1549
    }
1550
1551
    do {
1552
      ssize_t res = gnutls_record_recv(d_conn.get(), reinterpret_cast<char *>(&buffer.at(pos)), toRead - pos);
1553
      if (res == 0) {
1554
        throw std::runtime_error("EOF while reading from TLS connection");
1555
      }
1556
      else if (res > 0) {
1557
        pos += static_cast<size_t>(res);
1558
        if (allowIncomplete) {
1559
          break;
1560
        }
1561
      }
1562
      else if (res < 0) {
1563
        if (gnutls_error_is_fatal(res)) {
1564
          throw std::runtime_error("Fatal error reading from TLS connection: " + std::string(gnutls_strerror(res)));
1565
        }
1566
        else if (res == GNUTLS_E_AGAIN) {
1567
          return IOState::NeedRead;
1568
        }
1569
        VERBOSESLOG(infolog("Warning, non-fatal error while writing to TLS connection: %s", gnutls_strerror(res)),
1570
                    dnsdist::logging::getTopLogger("gnutls")->error(Logr::Info, gnutls_strerror(res), "Non-fatal error while writing to TLS connection", "tls.provider", Logging::Loggable("GnuTLS")));
1571
      }
1572
    }
1573
    while (pos < toRead);
1574
    return IOState::Done;
1575
  }
1576
1577
  size_t read(void* buffer, size_t bufferSize, const struct timeval& readTimeout, const struct timeval& totalTimeout, bool allowIncomplete) override
1578
  {
1579
    size_t got = 0;
1580
    struct timeval start{0,0};
1581
    struct timeval  remainingTime = totalTimeout;
1582
    if (totalTimeout.tv_sec != 0 || totalTimeout.tv_usec != 0) {
1583
      gettimeofday(&start, nullptr);
1584
    }
1585
1586
    do {
1587
      ssize_t res = gnutls_record_recv(d_conn.get(), (reinterpret_cast<char *>(buffer) + got), bufferSize - got);
1588
      if (res == 0) {
1589
        throw std::runtime_error("EOF while reading from TLS connection");
1590
      }
1591
      else if (res > 0) {
1592
        got += static_cast<size_t>(res);
1593
        if (allowIncomplete) {
1594
          break;
1595
        }
1596
      }
1597
      else if (res < 0) {
1598
        if (gnutls_error_is_fatal(res)) {
1599
          throw std::runtime_error("Fatal error reading from TLS connection: " + std::string(gnutls_strerror(res)));
1600
        }
1601
        else if (res == GNUTLS_E_AGAIN) {
1602
          int result = waitForData(d_socket, readTimeout);
1603
          if (result <= 0) {
1604
            throw std::runtime_error("Error while waiting to read from TLS connection: " + std::to_string(result));
1605
          }
1606
        }
1607
        else {
1608
          VERBOSESLOG(infolog("Non-fatal error while reading from TLS connection: %s", gnutls_strerror(res)),
1609
                      dnsdist::logging::getTopLogger("gnutls")->error(Logr::Info, gnutls_strerror(res), "Non-fatal error while reading from TLS connection", "tls.provider", Logging::Loggable("GnuTLS")));
1610
        }
1611
      }
1612
1613
      if (totalTimeout.tv_sec != 0 || totalTimeout.tv_usec != 0) {
1614
        struct timeval now;
1615
        gettimeofday(&now, nullptr);
1616
        struct timeval elapsed = now - start;
1617
        if (now < start || remainingTime < elapsed) {
1618
          throw runtime_error("Timeout while reading data");
1619
        }
1620
        start = now;
1621
        remainingTime = remainingTime - elapsed;
1622
      }
1623
    }
1624
    while (got < bufferSize);
1625
1626
    return got;
1627
  }
1628
1629
  size_t write(const void* buffer, size_t bufferSize, const struct timeval& writeTimeout) override
1630
  {
1631
    size_t got = 0;
1632
1633
    do {
1634
      ssize_t res = gnutls_record_send(d_conn.get(), (reinterpret_cast<const char *>(buffer) + got), bufferSize - got);
1635
      if (res == 0) {
1636
        throw std::runtime_error("Error writing to TLS connection");
1637
      }
1638
      else if (res > 0) {
1639
        got += static_cast<size_t>(res);
1640
      }
1641
      else if (res < 0) {
1642
        if (gnutls_error_is_fatal(res)) {
1643
          throw std::runtime_error("Fatal error writing to TLS connection: " + std::string(gnutls_strerror(res)));
1644
        }
1645
        else if (res == GNUTLS_E_AGAIN) {
1646
          int result = waitForRWData(d_socket, false, writeTimeout);
1647
          if (result <= 0) {
1648
            throw std::runtime_error("Error waiting to write to TLS connection: " + std::to_string(result));
1649
          }
1650
        }
1651
        else {
1652
          VERBOSESLOG(infolog("Non-fatal error while writing to TLS connection: %s", gnutls_strerror(res)),
1653
                      dnsdist::logging::getTopLogger("gnutls")->error(Logr::Info, gnutls_strerror(res), "Non-fatal error while writing to TLS connection", "tls.provider", Logging::Loggable("GnuTLS")));
1654
        }
1655
      }
1656
    }
1657
    while (got < bufferSize);
1658
1659
    return got;
1660
  }
1661
1662
  bool isUsable() const override
1663
  {
1664
    if (!d_conn) {
1665
      return false;
1666
    }
1667
1668
    /* as far as I can tell we can't peek so we cannot do better */
1669
    return isTCPSocketUsable(d_socket);
1670
  }
1671
1672
  std::string getServerNameIndication() const override
1673
  {
1674
    if (d_conn) {
1675
      unsigned int type;
1676
      size_t name_len = 256;
1677
      std::string sni;
1678
      sni.resize(name_len);
1679
1680
      int res = gnutls_server_name_get(d_conn.get(), const_cast<char*>(sni.c_str()), &name_len, &type, 0);
1681
      if (res == GNUTLS_E_SUCCESS) {
1682
        sni.resize(name_len);
1683
        return sni;
1684
      }
1685
    }
1686
    return std::string();
1687
  }
1688
1689
  std::vector<uint8_t> getNextProtocol() const override
1690
  {
1691
    std::vector<uint8_t> result;
1692
    if (!d_conn) {
1693
      return result;
1694
    }
1695
    gnutls_datum_t next;
1696
    if (gnutls_alpn_get_selected_protocol(d_conn.get(), &next) != GNUTLS_E_SUCCESS) {
1697
      return result;
1698
    }
1699
    result.insert(result.end(), next.data, next.data + next.size);
1700
    return result;
1701
  }
1702
1703
  LibsslTLSVersion getTLSVersion() const override
1704
  {
1705
    auto proto = gnutls_protocol_get_version(d_conn.get());
1706
    switch (proto) {
1707
    case GNUTLS_TLS1_0:
1708
      return LibsslTLSVersion::TLS10;
1709
    case GNUTLS_TLS1_1:
1710
      return LibsslTLSVersion::TLS11;
1711
    case GNUTLS_TLS1_2:
1712
      return LibsslTLSVersion::TLS12;
1713
#if GNUTLS_VERSION_NUMBER >= 0x030603
1714
    case GNUTLS_TLS1_3:
1715
      return LibsslTLSVersion::TLS13;
1716
#endif /* GNUTLS_VERSION_NUMBER >= 0x030603 */
1717
    default:
1718
      return LibsslTLSVersion::Unknown;
1719
    }
1720
  }
1721
1722
  [[nodiscard]] std::pair<long, std::string> getVerifyResult() const override
1723
  {
1724
    if (d_conn) {
1725
      auto status = gnutls_session_get_verify_cert_status(d_conn.get());
1726
      gnutls_datum_t out{};
1727
      if (gnutls_certificate_verification_status_print(status, GNUTLS_CRT_X509, &out, 0) == 0) {
1728
        auto errString = std::string(reinterpret_cast<const char*>(out.data), out.size); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast) It's the API
1729
        gnutls_free(out.data);
1730
        return {status, errString};
1731
      }
1732
      return {status, ""};
1733
    }
1734
    return {0, ""};
1735
  }
1736
1737
  bool hasSessionBeenResumed() const override
1738
  {
1739
    if (d_conn) {
1740
      return gnutls_session_is_resumed(d_conn.get()) != 0;
1741
    }
1742
    return false;
1743
  }
1744
1745
  std::vector<std::unique_ptr<TLSSession>> getSessions() override
1746
  {
1747
    return std::move(d_tlsSessions);
1748
  }
1749
1750
  void setSession(std::unique_ptr<TLSSession>& session) override
1751
  {
1752
    auto sess = dynamic_cast<GnuTLSSession*>(session.get());
1753
    if (!sess) {
1754
      throw std::runtime_error("Unable to convert GnuTLS session");
1755
    }
1756
1757
    auto native = sess->getNative();
1758
    auto ret = gnutls_session_set_data(d_conn.get(), native.data, native.size);
1759
    if (ret != GNUTLS_E_SUCCESS) {
1760
      throw std::runtime_error("Error setting up GnuTLS session: " + std::string(gnutls_strerror(ret)));
1761
    }
1762
    session.reset();
1763
  }
1764
1765
  void close() override
1766
  {
1767
    if (d_conn) {
1768
      gnutls_bye(d_conn.get(), GNUTLS_SHUT_RDWR);
1769
    }
1770
  }
1771
1772
  bool setALPNProtos(const std::vector<std::vector<uint8_t>>& protos)
1773
  {
1774
    std::vector<gnutls_datum_t> values;
1775
    values.reserve(protos.size());
1776
    for (const auto& proto : protos) {
1777
      gnutls_datum_t value;
1778
      value.data = const_cast<uint8_t*>(proto.data());
1779
      value.size = proto.size();
1780
      values.push_back(value);
1781
    }
1782
    unsigned int flags = 0;
1783
#if GNUTLS_VERSION_NUMBER >= 0x030500
1784
    flags |= GNUTLS_ALPN_MANDATORY;
1785
#elif defined(GNUTLS_ALPN_MAND)
1786
    flags |= GNUTLS_ALPN_MAND;
1787
#endif
1788
    return gnutls_alpn_set_protocols(d_conn.get(), values.data(), values.size(), flags);
1789
  }
1790
1791
  std::vector<int> getAsyncFDs() override
1792
  {
1793
    return {};
1794
  }
1795
1796
private:
1797
  std::shared_ptr<gnutls_certificate_credentials_st> d_creds;
1798
  std::shared_ptr<GnuTLSTicketsKey> d_ticketsKey;
1799
  std::unique_ptr<gnutls_session_int, void(*)(gnutls_session_t)> d_conn;
1800
  std::vector<std::unique_ptr<TLSSession>> d_tlsSessions;
1801
  std::string d_host;
1802
  const bool d_client{false};
1803
  bool d_handshakeDone{false};
1804
};
1805
1806
class GnuTLSIOCtx: public TLSCtx
1807
{
1808
public:
1809
  /* server side context */
1810
  GnuTLSIOCtx(TLSFrontend& frontend): d_protos(getALPNVector(frontend.d_alpn, false)), d_enableTickets(frontend.d_tlsConfig.d_enableTickets)
1811
  {
1812
    int rc = 0;
1813
    d_ticketsKeyRotationDelay = frontend.d_tlsConfig.d_ticketsKeyRotationDelay;
1814
1815
    gnutls_certificate_credentials_t creds;
1816
    rc = gnutls_certificate_allocate_credentials(&creds);
1817
    if (rc != GNUTLS_E_SUCCESS) {
1818
      throw std::runtime_error("Error allocating credentials for TLS context on " + frontend.d_addr.toStringWithPort() + ": " + gnutls_strerror(rc));
1819
    }
1820
1821
    d_creds = std::shared_ptr<gnutls_certificate_credentials_st>(creds, gnutls_certificate_free_credentials);
1822
    creds = nullptr;
1823
1824
    for (const auto& pair : frontend.d_tlsConfig.d_certKeyPairs) {
1825
      rc = gnutls_certificate_set_x509_key_file(d_creds.get(), pair.d_cert.c_str(), pair.d_key->c_str(), GNUTLS_X509_FMT_PEM);
1826
      if (rc != GNUTLS_E_SUCCESS) {
1827
        throw std::runtime_error("Error loading certificate ('" + pair.d_cert + "') and key ('" + pair.d_key.value() + "') for TLS context on " + frontend.d_addr.toStringWithPort() + ": " + gnutls_strerror(rc));
1828
      }
1829
    }
1830
1831
#ifndef DISABLE_OCSP_STAPLING
1832
    size_t count = 0;
1833
    for (const auto& file : frontend.d_tlsConfig.d_ocspFiles) {
1834
      rc = gnutls_certificate_set_ocsp_status_request_file(d_creds.get(), file.c_str(), count);
1835
      if (rc != GNUTLS_E_SUCCESS) {
1836
#if defined(DNSDIST)
1837
        SLOG(warnlog("Error loading OCSP response from file '%s' for certificate ('%s') and key ('%s') for TLS context on %s: %s", file, frontend.d_tlsConfig.d_certKeyPairs.at(count).d_cert, frontend.d_tlsConfig.d_certKeyPairs.at(count).d_key.value(), frontend.d_addr.toStringWithPort(), gnutls_strerror(rc)),
1838
             dnsdist::logging::getTopLogger("gnutls")->error(Logr::Warning, gnutls_strerror(rc), "Error loading OCSP response for TLS context", "tls.provider", Logging::Loggable("GnuTLS"), "frontend.address", Logging::Loggable(frontend.d_addr), "tls.ocsp_file", Logging::Loggable(file), "tls.certificate_file", Logging::Loggable(frontend.d_tlsConfig.d_certKeyPairs.at(count).d_cert), "tls.key_file", Logging::Loggable(frontend.d_tlsConfig.d_certKeyPairs.at(count).d_key.value())));
1839
#else /* DNSDIST */
1840
        warnlog("Error loading OCSP response from file '%s' for certificate ('%s') and key ('%s') for TLS context on %s: %s", file, frontend.d_tlsConfig.d_certKeyPairs.at(count).d_cert, frontend.d_tlsConfig.d_certKeyPairs.at(count).d_key.value(), frontend.d_addr.toStringWithPort(), gnutls_strerror(rc));
1841
#endif /* DNSDIST */
1842
      }
1843
      ++count;
1844
    }
1845
#endif /* DISABLE_OCSP_STAPLING */
1846
1847
#if GNUTLS_VERSION_NUMBER >= 0x030600
1848
    rc = gnutls_certificate_set_known_dh_params(d_creds.get(), GNUTLS_SEC_PARAM_HIGH);
1849
    if (rc != GNUTLS_E_SUCCESS) {
1850
      throw std::runtime_error("Error setting DH params for TLS context on " + frontend.d_addr.toStringWithPort() + ": " + gnutls_strerror(rc));
1851
    }
1852
#endif
1853
1854
    rc = gnutls_priority_init(&d_priorityCache, frontend.d_tlsConfig.d_ciphers.empty() ? "NORMAL" : frontend.d_tlsConfig.d_ciphers.c_str(), nullptr);
1855
    if (rc != GNUTLS_E_SUCCESS) {
1856
      throw std::runtime_error("Error setting up TLS cipher preferences to '" + frontend.d_tlsConfig.d_ciphers + "' (" + gnutls_strerror(rc) + ") on " + frontend.d_addr.toStringWithPort());
1857
    }
1858
1859
    try {
1860
      if (frontend.d_tlsConfig.d_ticketKeyFile.empty()) {
1861
        if (d_ticketsKeyRotationDelay == 0) {
1862
          throw std::runtime_error("Trying to start a TLS frontend without any TLS session ticket encryption key loaded AND with rotation disabled!");
1863
        }
1864
        handleTicketsKeyRotation(time(nullptr));
1865
      }
1866
      else {
1867
        GnuTLSIOCtx::loadTicketsKeys(frontend.d_tlsConfig.d_ticketKeyFile);
1868
      }
1869
    }
1870
    catch(const std::runtime_error& e) {
1871
      throw std::runtime_error("Error generating tickets key for TLS context on " + frontend.d_addr.toStringWithPort() + ": " + e.what());
1872
    }
1873
  }
1874
1875
  /* client side context */
1876
  GnuTLSIOCtx(const TLSContextParameters& params): d_protos(getALPNVector(params.d_alpn, true)), d_contextParameters(std::make_unique<TLSContextParameters>(params)), d_validateCerts(params.d_validateCertificates)
1877
  {
1878
    int rc = 0;
1879
1880
    gnutls_certificate_credentials_t creds;
1881
    rc = gnutls_certificate_allocate_credentials(&creds);
1882
    if (rc != GNUTLS_E_SUCCESS) {
1883
      throw std::runtime_error("Error allocating credentials for TLS context: " + std::string(gnutls_strerror(rc)));
1884
    }
1885
1886
    d_creds = std::shared_ptr<gnutls_certificate_credentials_st>(creds, gnutls_certificate_free_credentials);
1887
    creds = nullptr;
1888
1889
    if (params.d_validateCertificates) {
1890
      if (params.d_caStore.empty()) {
1891
#if GNUTLS_VERSION_NUMBER >= 0x030700 && GNUTLS_VERSION_NUMBER < 0x030703
1892
        /* see https://gitlab.com/gnutls/gnutls/-/issues/1277 */
1893
        std::cerr<<"Warning: GnuTLS 3.7.0 - 3.7.2 have a memory leak when validating server certificates in some configurations (PKCS11 support enabled, and a default PKCS11 trust store), please consider upgrading GnuTLS, using the OpenSSL provider for outgoing connections, or explicitly setting a CA store"<<std::endl;
1894
#endif /* GNUTLS_VERSION_NUMBER >= 0x030700 && GNUTLS_VERSION_NUMBER < 0x030703 */
1895
        rc = gnutls_certificate_set_x509_system_trust(d_creds.get());
1896
        if (rc < 0) {
1897
          throw std::runtime_error("Error adding the system's default trusted CAs: " + std::string(gnutls_strerror(rc)));
1898
        }
1899
      }
1900
      else {
1901
        rc = gnutls_certificate_set_x509_trust_file(d_creds.get(), params.d_caStore.c_str(), GNUTLS_X509_FMT_PEM);
1902
        if (rc < 0) {
1903
          throw std::runtime_error("Error adding '" + params.d_caStore + "' to the trusted CAs: " + std::string(gnutls_strerror(rc)));
1904
        }
1905
      }
1906
    }
1907
1908
    rc = gnutls_priority_init(&d_priorityCache, params.d_ciphers.empty() ? "NORMAL" : params.d_ciphers.c_str(), nullptr);
1909
    if (rc != GNUTLS_E_SUCCESS) {
1910
      throw std::runtime_error("Error setting up TLS cipher preferences to 'NORMAL' (" + std::string(gnutls_strerror(rc)) + ")");
1911
    }
1912
  }
1913
1914
  ~GnuTLSIOCtx() override
1915
  {
1916
    d_creds.reset();
1917
1918
    if (d_priorityCache) {
1919
      gnutls_priority_deinit(d_priorityCache);
1920
    }
1921
  }
1922
1923
  std::unique_ptr<TLSConnection> getConnection(int socket, const struct timeval& timeout, time_t now) override
1924
  {
1925
    handleTicketsKeyRotation(now);
1926
1927
    std::shared_ptr<GnuTLSTicketsKey> ticketsKey;
1928
    {
1929
      ticketsKey = *(d_ticketsKey.read_lock());
1930
    }
1931
1932
    auto connection = std::make_unique<GnuTLSConnection>(socket, timeout, d_creds, d_priorityCache, ticketsKey, d_enableTickets);
1933
    if (!d_protos.empty()) {
1934
      connection->setALPNProtos(d_protos);
1935
    }
1936
    return connection;
1937
  }
1938
1939
  static std::shared_ptr<gnutls_certificate_credentials_st> getPerThreadCredentials(bool validate, const std::string& caStore)
1940
  {
1941
    static thread_local std::map<std::pair<bool, std::string>, std::shared_ptr<gnutls_certificate_credentials_st>> t_credentials;
1942
    auto& entry = t_credentials[{validate, caStore}];
1943
    if (!entry) {
1944
      gnutls_certificate_credentials_t creds;
1945
      int rc = gnutls_certificate_allocate_credentials(&creds);
1946
      if (rc != GNUTLS_E_SUCCESS) {
1947
        throw std::runtime_error("Error allocating credentials for TLS context: " + std::string(gnutls_strerror(rc)));
1948
      }
1949
1950
      entry = std::shared_ptr<gnutls_certificate_credentials_st>(creds, gnutls_certificate_free_credentials);
1951
      creds = nullptr;
1952
1953
      if (validate) {
1954
        if (caStore.empty()) {
1955
          rc = gnutls_certificate_set_x509_system_trust(entry.get());
1956
          if (rc < 0) {
1957
            throw std::runtime_error("Error adding the system's default trusted CAs: " + std::string(gnutls_strerror(rc)));
1958
          }
1959
        }
1960
        else {
1961
          rc = gnutls_certificate_set_x509_trust_file(entry.get(), caStore.c_str(), GNUTLS_X509_FMT_PEM);
1962
          if (rc < 0) {
1963
            throw std::runtime_error("Error adding '" + caStore + "' to the trusted CAs: " + std::string(gnutls_strerror(rc)));
1964
          }
1965
        }
1966
      }
1967
    }
1968
    return entry;
1969
  }
1970
1971
  std::unique_ptr<TLSConnection> getClientConnection(const std::string& host, bool, int socket, const struct timeval& timeout) override
1972
  {
1973
    auto creds = getPerThreadCredentials(d_contextParameters->d_validateCertificates, d_contextParameters->d_caStore);
1974
    auto connection = std::make_unique<GnuTLSConnection>(host, socket, timeout, creds, d_priorityCache, d_validateCerts);
1975
    if (!d_protos.empty()) {
1976
      connection->setALPNProtos(d_protos);
1977
    }
1978
    return connection;
1979
  }
1980
1981
  void addTicketsKey(time_t now, std::shared_ptr<GnuTLSTicketsKey>&& newKey)
1982
  {
1983
    if (!d_enableTickets) {
1984
      return;
1985
    }
1986
1987
    {
1988
      *(d_ticketsKey.write_lock()) = std::move(newKey);
1989
    }
1990
1991
    if (d_ticketsKeyRotationDelay > 0) {
1992
      d_ticketsKeyNextRotation = now + d_ticketsKeyRotationDelay;
1993
    }
1994
1995
    if (TLSCtx::hasTicketsKeyAddedHook()) {
1996
      auto ticketsKey = *(d_ticketsKey.read_lock());
1997
      auto content = ticketsKey->content();
1998
      TLSCtx::getTicketsKeyAddedHook()(content);
1999
      safe_memory_release(content.data(), content.size());
2000
    }
2001
  }
2002
  void rotateTicketsKey(time_t now) override
2003
  {
2004
    if (!d_enableTickets) {
2005
      return;
2006
    }
2007
2008
    auto newKey = std::make_shared<GnuTLSTicketsKey>();
2009
    addTicketsKey(now, std::move(newKey));
2010
  }
2011
  void loadTicketsKey(const std::string& key) final
2012
  {
2013
    if (!d_enableTickets) {
2014
      return;
2015
    }
2016
2017
    auto newKey = std::make_shared<GnuTLSTicketsKey>(key);
2018
    addTicketsKey(time(nullptr), std::move(newKey));
2019
  }
2020
2021
  void loadTicketsKeys(const std::string& keyFile) final
2022
  {
2023
    if (!d_enableTickets) {
2024
      return;
2025
    }
2026
2027
    std::ifstream file(keyFile);
2028
    auto newKey = std::make_shared<GnuTLSTicketsKey>(file);
2029
    addTicketsKey(time(nullptr), std::move(newKey));
2030
    file.close();
2031
  }
2032
2033
  size_t getTicketsKeysCount() override
2034
  {
2035
    return *(d_ticketsKey.read_lock()) != nullptr ? 1 : 0;
2036
  }
2037
2038
  std::string getName() const override
2039
  {
2040
    return "gnutls";
2041
  }
2042
2043
private:
2044
  /* client context parameters */
2045
  std::shared_ptr<gnutls_certificate_credentials_st> d_creds;
2046
  const std::vector<std::vector<uint8_t>> d_protos;
2047
  std::unique_ptr<TLSContextParameters> d_contextParameters{nullptr};
2048
  gnutls_priority_t d_priorityCache{nullptr};
2049
  SharedLockGuarded<std::shared_ptr<GnuTLSTicketsKey>> d_ticketsKey{nullptr};
2050
  bool d_enableTickets{true};
2051
  bool d_validateCerts{true};
2052
};
2053
2054
#endif /* HAVE_GNUTLS */
2055
2056
#endif /* HAVE_DNS_OVER_TLS || HAVE_DNS_OVER_HTTPS */
2057
2058
bool TLSFrontend::setupTLS()
2059
0
{
2060
0
#if defined(HAVE_DNS_OVER_TLS) || defined(HAVE_DNS_OVER_HTTPS)
2061
0
  std::shared_ptr<TLSCtx> newCtx{nullptr};
2062
0
  if (d_parentFrontend) {
2063
0
    newCtx = d_parentFrontend->getContext();
2064
0
    if (newCtx) {
2065
0
      std::atomic_store_explicit(&d_ctx, std::move(newCtx), std::memory_order_release);
2066
0
      return true;
2067
0
    }
2068
0
  }
2069
2070
  /* get the "best" available provider */
2071
#if defined(HAVE_GNUTLS)
2072
  if (d_provider == "gnutls") {
2073
    newCtx = std::make_shared<GnuTLSIOCtx>(*this);
2074
  }
2075
#endif /* HAVE_GNUTLS */
2076
0
#if defined(HAVE_LIBSSL)
2077
0
  if (d_provider == "openssl") {
2078
0
    newCtx = OpenSSLTLSIOCtx::createServerSideContext(*this);
2079
0
  }
2080
0
#endif /* HAVE_LIBSSL */
2081
2082
0
  if (!newCtx) {
2083
0
#if defined(HAVE_LIBSSL)
2084
0
    newCtx = OpenSSLTLSIOCtx::createServerSideContext(*this);
2085
#elif defined(HAVE_GNUTLS)
2086
    newCtx = std::make_shared<GnuTLSIOCtx>(*this);
2087
#else
2088
#error "TLS support needed but neither libssl nor GnuTLS were selected"
2089
#endif
2090
0
  }
2091
2092
0
  std::atomic_store_explicit(&d_ctx, std::move(newCtx), std::memory_order_release);
2093
0
#endif /* HAVE_DNS_OVER_TLS || HAVE_DNS_OVER_HTTPS */
2094
0
  return true;
2095
0
}
2096
2097
std::shared_ptr<TLSCtx> getTLSContext([[maybe_unused]] const TLSContextParameters& params)
2098
0
{
2099
0
#ifdef HAVE_DNS_OVER_TLS
2100
  /* get the "best" available provider */
2101
0
  if (!params.d_provider.empty()) {
2102
#if defined(HAVE_GNUTLS)
2103
    if (params.d_provider == "gnutls") {
2104
      return std::make_shared<GnuTLSIOCtx>(params);
2105
    }
2106
#endif /* HAVE_GNUTLS */
2107
0
#if defined(HAVE_LIBSSL)
2108
0
    if (params.d_provider == "openssl") {
2109
0
      return OpenSSLTLSIOCtx::createClientSideContext(params);
2110
0
    }
2111
0
#endif /* HAVE_LIBSSL */
2112
0
  }
2113
2114
0
#if defined(HAVE_LIBSSL)
2115
0
  return OpenSSLTLSIOCtx::createClientSideContext(params);
2116
#elif defined(HAVE_GNUTLS)
2117
  return std::make_shared<GnuTLSIOCtx>(params);
2118
#else
2119
#error "DNS over TLS support needed but neither libssl nor GnuTLS were selected"
2120
#endif
2121
2122
0
#endif /* HAVE_DNS_OVER_TLS */
2123
0
  return nullptr;
2124
0
}