File: tls_server_context_picotls.cc

package info (click to toggle)
ngtcp2 1.16.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,264 kB
  • sloc: ansic: 59,199; cpp: 18,676; sh: 4,449; makefile: 652
file content (373 lines) | stat: -rw-r--r-- 11,053 bytes parent folder | download | duplicates (2)
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
/*
 * ngtcp2
 *
 * Copyright (c) 2022 ngtcp2 contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
#include "tls_server_context_picotls.h"

#include <iostream>
#include <memory>
#include <algorithm>

#include <ngtcp2/ngtcp2_crypto_picotls.h>

#include <openssl/pem.h>
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
#  include <openssl/core_names.h>
#endif // OPENSSL_VERSION_NUMBER >= 0x30000000L

#include "server_base.h"
#include "tls_shared_picotls.h"
#include "template.h"

extern Config config;

namespace {
int on_client_hello_h3_cb(ptls_on_client_hello_t *self, ptls_t *ptls,
                          ptls_on_client_hello_parameters_t *params) {
  auto &negprotos = params->negotiated_protocols;

  for (size_t i = 0; i < negprotos.count; ++i) {
    auto &proto = negprotos.list[i];
    if (std::ranges::equal(H3_ALPN_V1.subspan(1),
                           std::span{proto.base, proto.len})) {
      if (ptls_set_negotiated_protocol(
            ptls, reinterpret_cast<char *>(proto.base), proto.len) != 0) {
        return -1;
      }

      return 0;
    }
  }

  return PTLS_ALERT_NO_APPLICATION_PROTOCOL;
}

ptls_on_client_hello_t on_client_hello_h3 = {on_client_hello_h3_cb};
} // namespace

namespace {
int on_client_hello_hq_cb(ptls_on_client_hello_t *self, ptls_t *ptls,
                          ptls_on_client_hello_parameters_t *params) {
  auto &negprotos = params->negotiated_protocols;

  for (size_t i = 0; i < negprotos.count; ++i) {
    auto &proto = negprotos.list[i];
    if (std::ranges::equal(HQ_ALPN_V1.subspan(1),
                           std::span{proto.base, proto.len})) {
      if (ptls_set_negotiated_protocol(
            ptls, reinterpret_cast<char *>(proto.base), proto.len) != 0) {
        return -1;
      }

      return 0;
    }
  }

  return PTLS_ALERT_NO_APPLICATION_PROTOCOL;
}

ptls_on_client_hello_t on_client_hello_hq = {on_client_hello_hq_cb};
} // namespace

namespace {
auto ticket_hmac = EVP_sha256();

std::span<const uint8_t> get_ticket_key_name() {
  static std::array<uint8_t, 16> key_name;
  ptls_openssl_random_bytes(key_name.data(), key_name.size());
  return key_name;
}

std::span<const uint8_t> get_ticket_key() {
  static std::array<uint8_t, 32> key;
  ptls_openssl_random_bytes(key.data(), key.size());
  return key;
}

std::span<const uint8_t> get_ticket_hmac_key() {
  static std::array<uint8_t, 32> hmac_key;
  ptls_openssl_random_bytes(hmac_key.data(), hmac_key.size());
  return hmac_key;
}
} // namespace

namespace {
int ticket_key_cb(unsigned char *key_name, unsigned char *iv,
                  EVP_CIPHER_CTX *ctx,
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
                  EVP_MAC_CTX *hctx,
#else  // OPENSSL_VERSION_NUMBER < 0x30000000L
                  HMAC_CTX *hctx,
#endif // OPENSSL_VERSION_NUMBER < 0x30000000L
                  int enc) {
  static const auto static_key_name = get_ticket_key_name();
  static const auto static_key = get_ticket_key();
  static const auto static_hmac_key = get_ticket_hmac_key();

  if (enc) {
    ptls_openssl_random_bytes(iv, EVP_MAX_IV_LENGTH);

    std::ranges::copy(static_key_name, key_name);

    if (!EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, static_key.data(),
                            iv)) {
      return 0;
    }
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
    auto params = std::to_array({
      OSSL_PARAM_construct_octet_string(
        OSSL_MAC_PARAM_KEY, const_cast<uint8_t *>(static_hmac_key.data()),
        static_hmac_key.size()),
      OSSL_PARAM_construct_utf8_string(
        OSSL_MAC_PARAM_DIGEST,
        const_cast<char *>(EVP_MD_get0_name(ticket_hmac)), 0),
      OSSL_PARAM_construct_end(),
    });
    if (!EVP_MAC_CTX_set_params(hctx, params.data())) {
      /* TODO Which value should we return on error? */
      return 0;
    }
#else  // OPENSSL_VERSION_NUMBER < 0x30000000L
    if (!HMAC_Init_ex(hctx, static_hmac_key.data(),
                      static_cast<int>(static_hmac_key.size()), ticket_hmac,
                      nullptr)) {
      return 0;
    }
#endif // OPENSSL_VERSION_NUMBER < 0x30000000L

    return 1;
  }

  if (!std::ranges::equal(std::span{key_name, static_key_name.size()},
                          static_key_name)) {
    return 0;
  }

  if (!EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, static_key.data(),
                          iv)) {
    return 0;
  }
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
  auto params = std::to_array({
    OSSL_PARAM_construct_octet_string(
      OSSL_MAC_PARAM_KEY, const_cast<uint8_t *>(static_hmac_key.data()),
      static_hmac_key.size()),
    OSSL_PARAM_construct_utf8_string(
      OSSL_MAC_PARAM_DIGEST, const_cast<char *>(EVP_MD_get0_name(ticket_hmac)),
      0),
    OSSL_PARAM_construct_end(),
  });
  if (!EVP_MAC_CTX_set_params(hctx, params.data())) {
    /* TODO Which value should we return on error? */
    return 0;
  }
#else  // OPENSSL_VERSION_NUMBER < 0x30000000L
  if (!HMAC_Init_ex(hctx, static_hmac_key.data(),
                    static_cast<int>(static_hmac_key.size()), ticket_hmac,
                    nullptr)) {
    return 0;
  }
#endif // OPENSSL_VERSION_NUMBER < 0x30000000L

  return 1;
}
} // namespace

namespace {
int encrypt_ticket_cb(ptls_encrypt_ticket_t *encrypt_ticket, ptls_t *ptls,
                      int is_encrypt, ptls_buffer_t *dst, ptls_iovec_t src) {
  int rv;
  auto conn_ref =
    static_cast<ngtcp2_crypto_conn_ref *>(*ptls_get_data_ptr(ptls));
  auto conn = conn_ref->get_conn(conn_ref);
  uint32_t ver;

  if (is_encrypt) {
    ver = htonl(ngtcp2_conn_get_negotiated_version(conn));
    // TODO Replace std::make_unique with
    // std::make_unique_for_overwrite when it is available.
    auto buf = std::make_unique<uint8_t[]>(src.len + sizeof(ver));
    auto p = std::ranges::copy_n(src.base, as_signed(src.len), buf.get()).out;
    p = std::ranges::copy_n(reinterpret_cast<uint8_t *>(&ver), sizeof(ver), p)
          .out;

    src.base = buf.get();
    src.len = as_unsigned(p - buf.get());

#if OPENSSL_VERSION_NUMBER >= 0x30000000L
    rv = ptls_openssl_encrypt_ticket_evp(dst, src, ticket_key_cb);
#else  // OPENSSL_VERSION_NUMBER < 0x30000000L
    rv = ptls_openssl_encrypt_ticket(dst, src, ticket_key_cb);
#endif // OPENSSL_VERSION_NUMBER < 0x30000000L
    if (rv != 0) {
      return -1;
    }

    return 0;
  }

#if OPENSSL_VERSION_NUMBER >= 0x30000000L
  rv = ptls_openssl_decrypt_ticket_evp(dst, src, ticket_key_cb);
#else  // OPENSSL_VERSION_NUMBER < 0x30000000L
  rv = ptls_openssl_decrypt_ticket(dst, src, ticket_key_cb);
#endif // OPENSSL_VERSION_NUMBER < 0x30000000L
  if (rv != 0) {
    return -1;
  }

  if (dst->off < sizeof(ver)) {
    return -1;
  }

  memcpy(&ver, dst->base + dst->off - sizeof(ver), sizeof(ver));

  if (ngtcp2_conn_get_client_chosen_version(conn) != ntohl(ver)) {
    return -1;
  }

  dst->off -= sizeof(ver);

  return 0;
}

ptls_encrypt_ticket_t encrypt_ticket = {encrypt_ticket_cb};
} // namespace

namespace {
ptls_key_exchange_algorithm_t *key_exchanges[] = {
#if PTLS_OPENSSL_HAVE_X25519
  &ptls_openssl_x25519,
#endif // PTLS_OPENSSL_X25519
  &ptls_openssl_secp256r1,
  &ptls_openssl_secp384r1,
  &ptls_openssl_secp521r1,
#if PTLS_OPENSSL_HAVE_X25519MLKEM768
  &ptls_openssl_x25519mlkem768,
#endif // PTLS_OPENSSL_HAVE_X25519MLKEM768
  nullptr,
};
} // namespace

namespace {
ptls_cipher_suite_t *cipher_suites[] = {
  &ptls_openssl_aes128gcmsha256,
  &ptls_openssl_aes256gcmsha384,
#if PTLS_OPENSSL_HAVE_CHACHA20_POLY1305
  &ptls_openssl_chacha20poly1305sha256,
#endif // PTLS_OPENSSL_CHACHA20POLY1305SHA256
  nullptr,
};
} // namespace

TLSServerContext::TLSServerContext()
    : ctx_{
          .random_bytes = ptls_openssl_random_bytes,
          .get_time = &ptls_get_time,
          .key_exchanges = key_exchanges,
          .cipher_suites = cipher_suites,
          .ticket_lifetime = 86400,
          .require_dhe_on_psk = 1,
          .server_cipher_preference = 1,
          .encrypt_ticket = &encrypt_ticket,
      },
      sign_cert_{}
{}

TLSServerContext::~TLSServerContext() {
  if (sign_cert_.key) {
    ptls_openssl_dispose_sign_certificate(&sign_cert_);
  }

  for (size_t i = 0; i < ctx_.certificates.count; ++i) {
    free(ctx_.certificates.list[i].base);
  }
  free(ctx_.certificates.list);
}

ptls_context_t *TLSServerContext::get_native_handle() { return &ctx_; }

int TLSServerContext::init(const char *private_key_file, const char *cert_file,
                           AppProtocol app_proto) {
  switch (app_proto) {
  case AppProtocol::H3:
    ctx_.on_client_hello = &on_client_hello_h3;

    break;
  case AppProtocol::HQ:
    ctx_.on_client_hello = &on_client_hello_hq;

    break;
  };

  if (ngtcp2_crypto_picotls_configure_server_context(&ctx_) != 0) {
    std::cerr << "ngtcp2_crypto_picotls_configure_server_context failed"
              << std::endl;
    return -1;
  }

  if (ptls_load_certificates(&ctx_, cert_file) != 0) {
    std::cerr << "ptls_load_certificates failed" << std::endl;
    return -1;
  }

  if (load_private_key(private_key_file) != 0) {
    return -1;
  }

  if (config.verify_client) {
    ctx_.require_client_authentication = 1;
  }

  return 0;
}

int TLSServerContext::load_private_key(const char *private_key_file) {
  auto fp = fopen(private_key_file, "rb");
  if (fp == nullptr) {
    std::cerr << "Could not open private key file " << private_key_file << ": "
              << strerror(errno) << std::endl;
    return -1;
  }

  auto fp_d = defer(fclose, fp);

  auto pkey = PEM_read_PrivateKey(fp, nullptr, nullptr, nullptr);
  if (pkey == nullptr) {
    std::cerr << "Could not read private key file " << private_key_file
              << std::endl;
    return -1;
  }

  auto pkey_d = defer(EVP_PKEY_free, pkey);

  if (ptls_openssl_init_sign_certificate(&sign_cert_, pkey) != 0) {
    std::cerr << "ptls_openssl_init_sign_certificate failed" << std::endl;
    return -1;
  }

  ctx_.sign_certificate = &sign_cert_.super;

  return 0;
}

void TLSServerContext::enable_keylog() { ctx_.log_event = &log_event; }