GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_common.cc Lines: 519 682 76.1 %
Date: 2022-06-16 04:15:44 Branches: 281 487 57.7 %

Line Branch Exec Source
1
#include "base_object-inl.h"
2
#include "env-inl.h"
3
#include "node_buffer.h"
4
#include "node_crypto.h"
5
#include "crypto/crypto_common.h"
6
#include "node.h"
7
#include "node_internals.h"
8
#include "node_url.h"
9
#include "string_bytes.h"
10
#include "memory_tracker-inl.h"
11
#include "v8.h"
12
13
#include <openssl/ec.h>
14
#include <openssl/ecdh.h>
15
#include <openssl/evp.h>
16
#include <openssl/pem.h>
17
#include <openssl/x509v3.h>
18
#include <openssl/hmac.h>
19
#include <openssl/rand.h>
20
#include <openssl/pkcs12.h>
21
22
#include <string>
23
#include <unordered_map>
24
25
namespace node {
26
27
using v8::Array;
28
using v8::ArrayBuffer;
29
using v8::ArrayBufferView;
30
using v8::BackingStore;
31
using v8::Context;
32
using v8::EscapableHandleScope;
33
using v8::Integer;
34
using v8::Local;
35
using v8::MaybeLocal;
36
using v8::NewStringType;
37
using v8::Object;
38
using v8::String;
39
using v8::Undefined;
40
using v8::Value;
41
42
namespace crypto {
43
static constexpr int kX509NameFlagsMultiline =
44
    ASN1_STRFLGS_ESC_2253 |
45
    ASN1_STRFLGS_ESC_CTRL |
46
    ASN1_STRFLGS_UTF8_CONVERT |
47
    XN_FLAG_SEP_MULTILINE |
48
    XN_FLAG_FN_SN;
49
50
static constexpr int kX509NameFlagsRFC2253WithinUtf8JSON =
51
    XN_FLAG_RFC2253 &
52
    ~ASN1_STRFLGS_ESC_MSB &
53
    ~ASN1_STRFLGS_ESC_CTRL;
54
55
900
X509Pointer SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert) {
56
900
  X509_STORE* store = SSL_CTX_get_cert_store(ctx);
57
  DeleteFnPtr<X509_STORE_CTX, X509_STORE_CTX_free> store_ctx(
58
1800
      X509_STORE_CTX_new());
59
900
  X509Pointer result;
60
  X509* issuer;
61
1800
  if (store_ctx.get() != nullptr &&
62

1800
      X509_STORE_CTX_init(store_ctx.get(), store, nullptr, nullptr) == 1 &&
63
900
      X509_STORE_CTX_get1_issuer(&issuer, store_ctx.get(), cert) == 1) {
64
430
    result.reset(issuer);
65
  }
66
900
  return result;
67
}
68
69
void LogSecret(
70
    const SSLPointer& ssl,
71
    const char* name,
72
    const unsigned char* secret,
73
    size_t secretlen) {
74
  auto keylog_cb = SSL_CTX_get_keylog_callback(SSL_get_SSL_CTX(ssl.get()));
75
  unsigned char crandom[32];
76
77
  if (keylog_cb == nullptr ||
78
      SSL_get_client_random(ssl.get(), crandom, 32) != 32) {
79
    return;
80
  }
81
82
  std::string line = name;
83
  line += " " + StringBytes::hex_encode(
84
      reinterpret_cast<const char*>(crandom), 32);
85
  line += " " + StringBytes::hex_encode(
86
      reinterpret_cast<const char*>(secret), secretlen);
87
  keylog_cb(ssl.get(), line.c_str());
88
}
89
90
bool SetALPN(const SSLPointer& ssl, const std::string& alpn) {
91
  return SSL_set_alpn_protos(
92
      ssl.get(),
93
      reinterpret_cast<const uint8_t*>(alpn.c_str()),
94
      alpn.length()) == 0;
95
}
96
97
40
bool SetALPN(const SSLPointer& ssl, Local<Value> alpn) {
98
40
  if (!alpn->IsArrayBufferView())
99
    return false;
100
40
  ArrayBufferViewContents<unsigned char> protos(alpn.As<ArrayBufferView>());
101
40
  return SSL_set_alpn_protos(ssl.get(), protos.data(), protos.length()) == 0;
102
}
103
104
4
MaybeLocal<Value> GetSSLOCSPResponse(
105
    Environment* env,
106
    SSL* ssl,
107
    Local<Value> default_value) {
108
  const unsigned char* resp;
109
4
  int len = SSL_get_tlsext_status_ocsp_resp(ssl, &resp);
110
4
  if (resp == nullptr)
111
2
    return default_value;
112
113
  Local<Value> ret;
114
  MaybeLocal<Object> maybe_buffer =
115
2
      Buffer::Copy(env, reinterpret_cast<const char*>(resp), len);
116
117
2
  if (!maybe_buffer.ToLocal(&ret))
118
    return MaybeLocal<Value>();
119
120
2
  return ret;
121
}
122
123
114
bool SetTLSSession(
124
    const SSLPointer& ssl,
125
    const SSLSessionPointer& session) {
126

114
  return session != nullptr && SSL_set_session(ssl.get(), session.get()) == 1;
127
}
128
129
114
SSLSessionPointer GetTLSSession(const unsigned char* buf, size_t length) {
130
114
  return SSLSessionPointer(d2i_SSL_SESSION(nullptr, &buf, length));
131
}
132
133
964
long VerifyPeerCertificate(  // NOLINT(runtime/int)
134
    const SSLPointer& ssl,
135
    long def) {  // NOLINT(runtime/int)
136
964
  long err = def;  // NOLINT(runtime/int)
137
964
  if (X509* peer_cert = SSL_get_peer_certificate(ssl.get())) {
138
938
    X509_free(peer_cert);
139
938
    err = SSL_get_verify_result(ssl.get());
140
  } else {
141
26
    const SSL_CIPHER* curr_cipher = SSL_get_current_cipher(ssl.get());
142
26
    const SSL_SESSION* sess = SSL_get_session(ssl.get());
143
    // Allow no-cert for PSK authentication in TLS1.2 and lower.
144
    // In TLS1.3 check that session was reused because TLS1.3 PSK
145
    // looks like session resumption.
146

56
    if (SSL_CIPHER_get_auth_nid(curr_cipher) == NID_auth_psk ||
147
30
        (SSL_SESSION_get_protocol_version(sess) == TLS1_3_VERSION &&
148
6
         SSL_session_reused(ssl.get()))) {
149
7
      return X509_V_OK;
150
    }
151
  }
152
957
  return err;
153
}
154
155
12
bool UseSNIContext(
156
    const SSLPointer& ssl, BaseObjectPtr<SecureContext> context) {
157
12
  SSL_CTX* ctx = context->ctx().get();
158
12
  X509* x509 = SSL_CTX_get0_certificate(ctx);
159
12
  EVP_PKEY* pkey = SSL_CTX_get0_privatekey(ctx);
160
  STACK_OF(X509)* chain;
161
162
12
  int err = SSL_CTX_get0_chain_certs(ctx, &chain);
163
12
  if (err == 1) err = SSL_use_certificate(ssl.get(), x509);
164
12
  if (err == 1) err = SSL_use_PrivateKey(ssl.get(), pkey);
165

12
  if (err == 1 && chain != nullptr) err = SSL_set1_chain(ssl.get(), chain);
166
12
  return err == 1;
167
}
168
169
const char* GetClientHelloALPN(const SSLPointer& ssl) {
170
  const unsigned char* buf;
171
  size_t len;
172
  size_t rem;
173
174
  if (!SSL_client_hello_get0_ext(
175
          ssl.get(),
176
          TLSEXT_TYPE_application_layer_protocol_negotiation,
177
          &buf,
178
          &rem) ||
179
      rem < 2) {
180
    return nullptr;
181
  }
182
183
  len = (buf[0] << 8) | buf[1];
184
  if (len + 2 != rem) return nullptr;
185
  return reinterpret_cast<const char*>(buf + 3);
186
}
187
188
const char* GetClientHelloServerName(const SSLPointer& ssl) {
189
  const unsigned char* buf;
190
  size_t len;
191
  size_t rem;
192
193
  if (!SSL_client_hello_get0_ext(
194
          ssl.get(),
195
          TLSEXT_TYPE_server_name,
196
          &buf,
197
          &rem) || rem <= 2) {
198
    return nullptr;
199
  }
200
201
  len = (*buf << 8) | *(buf + 1);
202
  if (len + 2 != rem)
203
    return nullptr;
204
  rem = len;
205
206
  if (rem == 0 || *(buf + 2) != TLSEXT_NAMETYPE_host_name) return nullptr;
207
  rem--;
208
  if (rem <= 2)
209
    return nullptr;
210
  len = (*(buf + 3) << 8) | *(buf + 4);
211
  if (len + 2 > rem)
212
    return nullptr;
213
  return reinterpret_cast<const char*>(buf + 5);
214
}
215
216
2435
const char* GetServerName(SSL* ssl) {
217
2435
  return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
218
}
219
220
bool SetGroups(SecureContext* sc, const char* groups) {
221
  return SSL_CTX_set1_groups_list(sc->ctx().get(), groups) == 1;
222
}
223
224
468
const char* X509ErrorCode(long err) {  // NOLINT(runtime/int)
225
468
  const char* code = "UNSPECIFIED";
226
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
227







468
  switch (err) {
228
    // if you modify anything in here, *please* update the respective section in
229
    // doc/api/tls.md as well
230
19
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
231
1
    CASE_X509_ERR(UNABLE_TO_GET_CRL)
232
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
233
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
234
    CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
235
    CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
236
    CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
237
    CASE_X509_ERR(CERT_NOT_YET_VALID)
238
    CASE_X509_ERR(CERT_HAS_EXPIRED)
239
    CASE_X509_ERR(CRL_NOT_YET_VALID)
240
    CASE_X509_ERR(CRL_HAS_EXPIRED)
241
    CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
242
    CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
243
    CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
244
    CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
245
    CASE_X509_ERR(OUT_OF_MEM)
246
241
    CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
247
17
    CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
248
4
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
249
183
    CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
250
    CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
251
1
    CASE_X509_ERR(CERT_REVOKED)
252
    CASE_X509_ERR(INVALID_CA)
253
    CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
254
1
    CASE_X509_ERR(INVALID_PURPOSE)
255
    CASE_X509_ERR(CERT_UNTRUSTED)
256
    CASE_X509_ERR(CERT_REJECTED)
257
    CASE_X509_ERR(HOSTNAME_MISMATCH)
258
  }
259
#undef CASE_X509_ERR
260
468
  return code;
261
}
262
263
MaybeLocal<Value> GetValidationErrorReason(Environment* env, int err) {
264
  if (err == 0)
265
    return Undefined(env->isolate());
266
  const char* reason = X509_verify_cert_error_string(err);
267
  return OneByteString(env->isolate(), reason);
268
}
269
270
MaybeLocal<Value> GetValidationErrorCode(Environment* env, int err) {
271
  if (err == 0)
272
    return Undefined(env->isolate());
273
  return OneByteString(env->isolate(), X509ErrorCode(err));
274
}
275
276
12
MaybeLocal<Value> GetCert(Environment* env, const SSLPointer& ssl) {
277
12
  ClearErrorOnReturn clear_error_on_return;
278
12
  X509* cert = SSL_get_certificate(ssl.get());
279
12
  if (cert == nullptr)
280
2
    return Undefined(env->isolate());
281
282
11
  MaybeLocal<Object> maybe_cert = X509ToObject(env, cert);
283
11
  return maybe_cert.FromMaybe<Value>(Local<Value>());
284
}
285
286
5022
Local<Value> ToV8Value(Environment* env, const BIOPointer& bio) {
287
  BUF_MEM* mem;
288
5022
  BIO_get_mem_ptr(bio.get(), &mem);
289
  MaybeLocal<String> ret =
290
      String::NewFromUtf8(
291
          env->isolate(),
292
5022
          mem->data,
293
          NewStringType::kNormal,
294
5022
          mem->length);
295
5022
  CHECK_EQ(BIO_reset(bio.get()), 1);
296
5022
  return ret.FromMaybe(Local<Value>());
297
}
298
299
namespace {
300
template <typename T>
301
47216
bool Set(
302
    Local<Context> context,
303
    Local<Object> target,
304
    Local<Value> name,
305
    MaybeLocal<T> maybe_value) {
306
  Local<Value> value;
307
47216
  if (!maybe_value.ToLocal(&value))
308
    return false;
309
310
  // Undefined is ignored, but still considered successful
311
94432
  if (value->IsUndefined())
312
7130
    return true;
313
314
80172
  return !target->Set(context, name, value).IsNothing();
315
}
316
317
template <const char* (*getstr)(const SSL_CIPHER* cipher)>
318
318
MaybeLocal<Value> GetCipherValue(Environment* env, const SSL_CIPHER* cipher) {
319
318
  if (cipher == nullptr)
320
    return Undefined(env->isolate());
321
322
636
  return OneByteString(env->isolate(), getstr(cipher));
323
}
324
325
constexpr auto GetCipherName = GetCipherValue<SSL_CIPHER_get_name>;
326
constexpr auto GetCipherStandardName = GetCipherValue<SSL_CIPHER_standard_name>;
327
constexpr auto GetCipherVersion = GetCipherValue<SSL_CIPHER_get_version>;
328
329
449
StackOfX509 CloneSSLCerts(X509Pointer&& cert,
330
                          const STACK_OF(X509)* const ssl_certs) {
331
898
  StackOfX509 peer_certs(sk_X509_new(nullptr));
332
449
  if (cert)
333
    sk_X509_push(peer_certs.get(), cert.release());
334
1240
  for (int i = 0; i < sk_X509_num(ssl_certs); i++) {
335
791
    X509Pointer cert(X509_dup(sk_X509_value(ssl_certs, i)));
336

791
    if (!cert || !sk_X509_push(peer_certs.get(), cert.get()))
337
      return StackOfX509();
338
    // `cert` is now managed by the stack.
339
791
    cert.release();
340
  }
341
449
  return peer_certs;
342
}
343
344
449
MaybeLocal<Object> AddIssuerChainToObject(
345
    X509Pointer* cert,
346
    Local<Object> object,
347
    StackOfX509&& peer_certs,
348
    Environment* const env) {
349
449
  Local<Context> context = env->isolate()->GetCurrentContext();
350
449
  cert->reset(sk_X509_delete(peer_certs.get(), 0));
351
  for (;;) {
352
    int i;
353
454
    for (i = 0; i < sk_X509_num(peer_certs.get()); i++) {
354
342
      X509* ca = sk_X509_value(peer_certs.get(), i);
355
342
      if (X509_check_issued(ca, cert->get()) != X509_V_OK)
356
2
        continue;
357
358
      Local<Object> ca_info;
359
340
      MaybeLocal<Object> maybe_ca_info = X509ToObject(env, ca);
360
340
      if (!maybe_ca_info.ToLocal(&ca_info))
361
        return MaybeLocal<Object>();
362
363
680
      if (!Set<Object>(context, object, env->issuercert_string(), ca_info))
364
        return MaybeLocal<Object>();
365
340
      object = ca_info;
366
367
      // NOTE: Intentionally freeing cert that is not used anymore.
368
      // Delete cert and continue aggregating issuers.
369
340
      cert->reset(sk_X509_delete(peer_certs.get(), i));
370
340
      break;
371
    }
372
373
    // Issuer not found, break out of the loop.
374
452
    if (i == sk_X509_num(peer_certs.get()))
375
449
      break;
376
3
  }
377
449
  return MaybeLocal<Object>(object);
378
}
379
380
449
MaybeLocal<Object> GetLastIssuedCert(
381
    X509Pointer* cert,
382
    const SSLPointer& ssl,
383
    Local<Object> issuer_chain,
384
    Environment* const env) {
385
449
  Local<Context> context = env->isolate()->GetCurrentContext();
386
821
  while (X509_check_issued(cert->get(), cert->get()) != X509_V_OK) {
387
373
    X509Pointer ca;
388
373
    if (!(ca = SSL_CTX_get_issuer(SSL_get_SSL_CTX(ssl.get()), cert->get())))
389
      break;
390
391
    Local<Object> ca_info;
392
373
    MaybeLocal<Object> maybe_ca_info = X509ToObject(env, ca.get());
393
373
    if (!maybe_ca_info.ToLocal(&ca_info))
394
      return MaybeLocal<Object>();
395
396
746
    if (!Set<Object>(context, issuer_chain, env->issuercert_string(), ca_info))
397
      return MaybeLocal<Object>();
398
373
    issuer_chain = ca_info;
399
400
    // For self-signed certificates whose keyUsage field does not include
401
    // keyCertSign, X509_check_issued() will return false. Avoid going into an
402
    // infinite loop by checking if SSL_CTX_get_issuer() returned the same
403
    // certificate.
404
373
    if (cert->get() == ca.get()) break;
405
406
    // Delete previous cert and continue aggregating issuers.
407
372
    *cert = std::move(ca);
408
  }
409
449
  return MaybeLocal<Object>(issuer_chain);
410
}
411
412
3699
void AddFingerprintDigest(
413
    const unsigned char* md,
414
    unsigned int md_size,
415
    char fingerprint[3 * EVP_MAX_MD_SIZE]) {
416
  unsigned int i;
417
3699
  const char hex[] = "0123456789ABCDEF";
418
419
146727
  for (i = 0; i < md_size; i++) {
420
143028
    fingerprint[3*i] = hex[(md[i] & 0xf0) >> 4];
421
143028
    fingerprint[(3*i)+1] = hex[(md[i] & 0x0f)];
422
143028
    fingerprint[(3*i)+2] = ':';
423
  }
424
425
  DCHECK_GT(md_size, 0);
426
3699
  fingerprint[(3 * (md_size - 1)) + 2] = '\0';
427
3699
}
428
429
template <const char* (*nid2string)(int nid)>
430
188
MaybeLocal<Value> GetCurveName(Environment* env, const int nid) {
431
188
  const char* name = nid2string(nid);
432
  return name != nullptr ?
433
      MaybeLocal<Value>(OneByteString(env->isolate(), name)) :
434
376
      MaybeLocal<Value>(Undefined(env->isolate()));
435
}
436
437
47
MaybeLocal<Value> GetECPubKey(
438
    Environment* env,
439
    const EC_GROUP* group,
440
    const ECPointer& ec) {
441
47
  const EC_POINT* pubkey = EC_KEY_get0_public_key(ec.get());
442
47
  if (pubkey == nullptr)
443
    return Undefined(env->isolate());
444
445
47
  return ECPointToBuffer(
446
      env,
447
      group,
448
      pubkey,
449
47
      EC_KEY_get_conv_form(ec.get()),
450
94
      nullptr).FromMaybe(Local<Object>());
451
}
452
453
47
MaybeLocal<Value> GetECGroup(
454
    Environment* env,
455
    const EC_GROUP* group,
456
    const ECPointer& ec) {
457
47
  if (group == nullptr)
458
    return Undefined(env->isolate());
459
460
47
  int bits = EC_GROUP_order_bits(group);
461
47
  if (bits <= 0)
462
    return Undefined(env->isolate());
463
464
94
  return Integer::New(env->isolate(), bits);
465
}
466
467
1185
MaybeLocal<Object> GetPubKey(Environment* env, const RSAPointer& rsa) {
468
1185
  int size = i2d_RSA_PUBKEY(rsa.get(), nullptr);
469
1185
  CHECK_GE(size, 0);
470
471
2370
  std::unique_ptr<BackingStore> bs;
472
  {
473
1185
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
474
1185
    bs = ArrayBuffer::NewBackingStore(env->isolate(), size);
475
  }
476
477
1185
  unsigned char* serialized = reinterpret_cast<unsigned char*>(bs->Data());
478
1185
  CHECK_GE(i2d_RSA_PUBKEY(rsa.get(), &serialized), 0);
479
480
1185
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
481
2370
  return Buffer::New(env, ab, 0, ab->ByteLength()).FromMaybe(Local<Object>());
482
}
483
484
1185
MaybeLocal<Value> GetExponentString(
485
    Environment* env,
486
    const BIOPointer& bio,
487
    const BIGNUM* e) {
488
1185
  uint64_t exponent_word = static_cast<uint64_t>(BN_get_word(e));
489
1185
  BIO_printf(bio.get(), "0x%" PRIx64, exponent_word);
490
2370
  return ToV8Value(env, bio);
491
}
492
493
1185
Local<Value> GetBits(Environment* env, const BIGNUM* n) {
494
2370
  return Integer::New(env->isolate(), BN_num_bits(n));
495
}
496
497
1185
MaybeLocal<Value> GetModulusString(
498
    Environment* env,
499
    const BIOPointer& bio,
500
    const BIGNUM* n) {
501
1185
  BN_print(bio.get(), n);
502
2370
  return ToV8Value(env, bio);
503
}
504
}  // namespace
505
506
1234
MaybeLocal<Object> GetRawDERCertificate(Environment* env, X509* cert) {
507
1234
  int size = i2d_X509(cert, nullptr);
508
509
2468
  std::unique_ptr<BackingStore> bs;
510
  {
511
1234
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
512
1234
    bs = ArrayBuffer::NewBackingStore(env->isolate(), size);
513
  }
514
515
1234
  unsigned char* serialized = reinterpret_cast<unsigned char*>(bs->Data());
516
1234
  CHECK_GE(i2d_X509(cert, &serialized), 0);
517
518
1234
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
519
2468
  return Buffer::New(env, ab, 0, ab->ByteLength()).FromMaybe(Local<Object>());
520
}
521
522
1235
MaybeLocal<Value> GetSerialNumber(Environment* env, X509* cert) {
523
1235
  if (ASN1_INTEGER* serial_number = X509_get_serialNumber(cert)) {
524
1235
    BignumPointer bn(ASN1_INTEGER_to_BN(serial_number, nullptr));
525
1235
    if (bn) {
526
1235
      char* data = BN_bn2hex(bn.get());
527
1235
      ByteSource buf = ByteSource::Allocated(data, strlen(data));
528
2470
      if (buf) return OneByteString(env->isolate(), buf.data<unsigned char>());
529
    }
530
  }
531
532
  return Undefined(env->isolate());
533
}
534
535
1233
MaybeLocal<Value> GetKeyUsage(Environment* env, X509* cert) {
536
  StackOfASN1 eku(static_cast<STACK_OF(ASN1_OBJECT)*>(
537
2466
      X509_get_ext_d2i(cert, NID_ext_key_usage, nullptr, nullptr)));
538
1233
  if (eku) {
539
9
    const int count = sk_ASN1_OBJECT_num(eku.get());
540
9
    MaybeStackBuffer<Local<Value>, 16> ext_key_usage(count);
541
    char buf[256];
542
543
9
    int j = 0;
544
20
    for (int i = 0; i < count; i++) {
545
11
      if (OBJ_obj2txt(buf,
546
                      sizeof(buf),
547
22
                      sk_ASN1_OBJECT_value(eku.get(), i), 1) >= 0) {
548
22
        ext_key_usage[j++] = OneByteString(env->isolate(), buf);
549
      }
550
    }
551
552
18
    return Array::New(env->isolate(), ext_key_usage.out(), count);
553
  }
554
555
2448
  return Undefined(env->isolate());
556
}
557
558
3699
MaybeLocal<Value> GetFingerprintDigest(
559
    Environment* env,
560
    const EVP_MD* method,
561
    X509* cert) {
562
  unsigned char md[EVP_MAX_MD_SIZE];
563
  unsigned int md_size;
564
  char fingerprint[EVP_MAX_MD_SIZE * 3];
565
566
3699
  if (X509_digest(cert, method, md, &md_size)) {
567
3699
    AddFingerprintDigest(md, md_size, fingerprint);
568
7398
    return OneByteString(env->isolate(), fingerprint);
569
  }
570
  return Undefined(env->isolate());
571
}
572
573
1233
MaybeLocal<Value> GetValidTo(
574
    Environment* env,
575
    X509* cert,
576
    const BIOPointer& bio) {
577
1233
  ASN1_TIME_print(bio.get(), X509_get0_notAfter(cert));
578
2466
  return ToV8Value(env, bio);
579
}
580
581
1233
MaybeLocal<Value> GetValidFrom(
582
    Environment* env,
583
    X509* cert,
584
    const BIOPointer& bio) {
585
1233
  ASN1_TIME_print(bio.get(), X509_get0_notBefore(cert));
586
2466
  return ToV8Value(env, bio);
587
}
588
589
224
static inline bool IsSafeAltName(const char* name, size_t length, bool utf8) {
590
5013
  for (size_t i = 0; i < length; i++) {
591
4835
    char c = name[i];
592
4835
    switch (c) {
593
25
    case '"':
594
    case '\\':
595
      // These mess with encoding rules.
596
      // Fall through.
597
    case ',':
598
      // Commas make it impossible to split the list of subject alternative
599
      // names unambiguously, which is why we have to escape.
600
      // Fall through.
601
    case '\'':
602
      // Single quotes are unlikely to appear in any legitimate values, but they
603
      // could be used to make a value look like it was escaped (i.e., enclosed
604
      // in single/double quotes).
605
25
      return false;
606
4810
    default:
607
4810
      if (utf8) {
608
        // In UTF8 strings, we require escaping for any ASCII control character,
609
        // but NOT for non-ASCII characters. Note that all bytes of any code
610
        // point that consists of more than a single byte have their MSB set.
611

319
        if (static_cast<unsigned char>(c) < ' ' || c == '\x7f') {
612
7
          return false;
613
        }
614
      } else {
615
        // Check if the char is a control character or non-ASCII character. Note
616
        // that char may or may not be a signed type. Regardless, non-ASCII
617
        // values will always be outside of this range.
618

4491
        if (c < ' ' || c > '~') {
619
14
          return false;
620
        }
621
      }
622
    }
623
  }
624
178
  return true;
625
}
626
627
224
static inline void PrintAltName(const BIOPointer& out, const char* name,
628
                                size_t length, bool utf8,
629
                                const char* safe_prefix) {
630
224
  if (IsSafeAltName(name, length, utf8)) {
631
    // For backward-compatibility, append "safe" names without any
632
    // modifications.
633
178
    if (safe_prefix != nullptr) {
634
10
      BIO_printf(out.get(), "%s:", safe_prefix);
635
    }
636
178
    BIO_write(out.get(), name, length);
637
  } else {
638
    // If a name is not "safe", we cannot embed it without special
639
    // encoding. This does not usually happen, but we don't want to hide
640
    // it from the user either. We use JSON compatible escaping here.
641
46
    BIO_write(out.get(), "\"", 1);
642
46
    if (safe_prefix != nullptr) {
643
9
      BIO_printf(out.get(), "%s:", safe_prefix);
644
    }
645
1601
    for (size_t j = 0; j < length; j++) {
646
1555
      char c = static_cast<char>(name[j]);
647
1555
      if (c == '\\') {
648
10
        BIO_write(out.get(), "\\\\", 2);
649
1545
      } else if (c == '"') {
650
4
        BIO_write(out.get(), "\\\"", 2);
651


1541
      } else if ((c >= ' ' && c != ',' && c <= '~') || (utf8 && (c & 0x80))) {
652
        // Note that the above condition explicitly excludes commas, which means
653
        // that those are encoded as Unicode escape sequences in the "else"
654
        // block. That is not strictly necessary, and Node.js itself would parse
655
        // it correctly either way. We only do this to account for third-party
656
        // code that might be splitting the string at commas (as Node.js itself
657
        // used to do).
658
1483
        BIO_write(out.get(), &c, 1);
659
      } else {
660
        // Control character or non-ASCII character. We treat everything as
661
        // Latin-1, which corresponds to the first 255 Unicode code points.
662
58
        const char hex[] = "0123456789abcdef";
663
58
        char u[] = { '\\', 'u', '0', '0', hex[(c & 0xf0) >> 4], hex[c & 0x0f] };
664
58
        BIO_write(out.get(), u, sizeof(u));
665
      }
666
    }
667
46
    BIO_write(out.get(), "\"", 1);
668
  }
669
224
}
670
671
198
static inline void PrintLatin1AltName(const BIOPointer& out,
672
                                      const ASN1_IA5STRING* name,
673
                                      const char* safe_prefix = nullptr) {
674
198
  PrintAltName(out, reinterpret_cast<const char*>(name->data), name->length,
675
               false, safe_prefix);
676
198
}
677
678
12
static inline void PrintUtf8AltName(const BIOPointer& out,
679
                                    const ASN1_UTF8STRING* name,
680
                                    const char* safe_prefix = nullptr) {
681
12
  PrintAltName(out, reinterpret_cast<const char*>(name->data), name->length,
682
               true, safe_prefix);
683
12
}
684
685
// This function emulates the behavior of i2v_GENERAL_NAME in a safer and less
686
// ambiguous way. "othername:" entries use the GENERAL_NAME_print format.
687
252
static bool PrintGeneralName(const BIOPointer& out, const GENERAL_NAME* gen) {
688
252
  if (gen->type == GEN_DNS) {
689
25
    ASN1_IA5STRING* name = gen->d.dNSName;
690
25
    BIO_write(out.get(), "DNS:", 4);
691
    // Note that the preferred name syntax (see RFCs 5280 and 1034) with
692
    // wildcards is a subset of what we consider "safe", so spec-compliant DNS
693
    // names will never need to be escaped.
694
25
    PrintLatin1AltName(out, name);
695
227
  } else if (gen->type == GEN_EMAIL) {
696
4
    ASN1_IA5STRING* name = gen->d.rfc822Name;
697
4
    BIO_write(out.get(), "email:", 6);
698
4
    PrintLatin1AltName(out, name);
699
223
  } else if (gen->type == GEN_URI) {
700
162
    ASN1_IA5STRING* name = gen->d.uniformResourceIdentifier;
701
162
    BIO_write(out.get(), "URI:", 4);
702
    // The set of "safe" names was designed to include just about any URI,
703
    // with a few exceptions, most notably URIs that contains commas (see
704
    // RFC 2396). In other words, most legitimate URIs will not require
705
    // escaping.
706
162
    PrintLatin1AltName(out, name);
707
61
  } else if (gen->type == GEN_DIRNAME) {
708
    // Earlier versions of Node.js used X509_NAME_oneline to print the X509_NAME
709
    // object. The format was non standard and should be avoided. The use of
710
    // X509_NAME_oneline is discouraged by OpenSSL but was required for backward
711
    // compatibility. Conveniently, X509_NAME_oneline produced ASCII and the
712
    // output was unlikely to contains commas or other characters that would
713
    // require escaping. However, it SHOULD NOT produce ASCII output since an
714
    // RFC5280 AttributeValue may be a UTF8String.
715
    // Newer versions of Node.js have since switched to X509_NAME_print_ex to
716
    // produce a better format at the cost of backward compatibility. The new
717
    // format may contain Unicode characters and it is likely to contain commas,
718
    // which require escaping. Fortunately, the recently safeguarded function
719
    // PrintAltName handles all of that safely.
720
14
    BIO_printf(out.get(), "DirName:");
721
14
    BIOPointer tmp(BIO_new(BIO_s_mem()));
722
14
    CHECK(tmp);
723
14
    if (X509_NAME_print_ex(tmp.get(),
724
14
                           gen->d.dirn,
725
                           0,
726
14
                           kX509NameFlagsRFC2253WithinUtf8JSON) < 0) {
727
      return false;
728
    }
729
14
    char* oline = nullptr;
730
14
    long n_bytes = BIO_get_mem_data(tmp.get(), &oline);  // NOLINT(runtime/int)
731
14
    CHECK_GE(n_bytes, 0);
732

14
    CHECK_IMPLIES(n_bytes != 0, oline != nullptr);
733
14
    PrintAltName(out, oline, static_cast<size_t>(n_bytes), true, nullptr);
734
47
  } else if (gen->type == GEN_IPADD) {
735
17
    BIO_printf(out.get(), "IP Address:");
736
17
    const ASN1_OCTET_STRING* ip = gen->d.ip;
737
17
    const unsigned char* b = ip->data;
738
17
    if (ip->length == 4) {
739
11
      BIO_printf(out.get(), "%d.%d.%d.%d", b[0], b[1], b[2], b[3]);
740
6
    } else if (ip->length == 16) {
741
18
      for (unsigned int j = 0; j < 8; j++) {
742
16
        uint16_t pair = (b[2 * j] << 8) | b[2 * j + 1];
743
16
        BIO_printf(out.get(), (j == 0) ? "%X" : ":%X", pair);
744
      }
745
    } else {
746
#if OPENSSL_VERSION_MAJOR >= 3
747
4
      BIO_printf(out.get(), "<invalid length=%d>", ip->length);
748
#else
749
      BIO_printf(out.get(), "<invalid>");
750
#endif
751
    }
752
30
  } else if (gen->type == GEN_RID) {
753
    // Unlike OpenSSL's default implementation, never print the OID as text and
754
    // instead always print its numeric representation.
755
    char oline[256];
756
4
    OBJ_obj2txt(oline, sizeof(oline), gen->d.rid, true);
757
4
    BIO_printf(out.get(), "Registered ID:%s", oline);
758
26
  } else if (gen->type == GEN_OTHERNAME) {
759
    // The format that is used here is based on OpenSSL's implementation of
760
    // GENERAL_NAME_print (as of OpenSSL 3.0.1). Earlier versions of Node.js
761
    // instead produced the same format as i2v_GENERAL_NAME, which was somewhat
762
    // awkward, especially when passed to translatePeerCertificate.
763
26
    bool unicode = true;
764
26
    const char* prefix = nullptr;
765
    // OpenSSL 1.1.1 does not support othername in GENERAL_NAME_print and may
766
    // not define these NIDs.
767
#if OPENSSL_VERSION_MAJOR >= 3
768
26
    int nid = OBJ_obj2nid(gen->d.otherName->type_id);
769

26
    switch (nid) {
770
      case NID_id_on_SmtpUTF8Mailbox:
771
        prefix = "SmtpUTF8Mailbox";
772
        break;
773
12
      case NID_XmppAddr:
774
12
        prefix = "XmppAddr";
775
12
        break;
776
9
      case NID_SRVName:
777
9
        prefix = "SRVName";
778
9
        unicode = false;
779
9
        break;
780
      case NID_ms_upn:
781
        prefix = "UPN";
782
        break;
783
      case NID_NAIRealm:
784
        prefix = "NAIRealm";
785
        break;
786
    }
787
#endif  // OPENSSL_VERSION_MAJOR >= 3
788
26
    int val_type = gen->d.otherName->value->type;
789

26
    if (prefix == nullptr ||
790
12
        (unicode && val_type != V_ASN1_UTF8STRING) ||
791

21
        (!unicode && val_type != V_ASN1_IA5STRING)) {
792
7
      BIO_printf(out.get(), "othername:<unsupported>");
793
    } else {
794
19
      BIO_printf(out.get(), "othername:");
795
19
      if (unicode) {
796
12
        PrintUtf8AltName(out, gen->d.otherName->value->value.utf8string,
797
                         prefix);
798
      } else {
799
7
        PrintLatin1AltName(out, gen->d.otherName->value->value.ia5string,
800
                           prefix);
801
      }
802
    }
803
  } else if (gen->type == GEN_X400) {
804
    // TODO(tniessen): this is what OpenSSL does, implement properly instead
805
    BIO_printf(out.get(), "X400Name:<unsupported>");
806
  } else if (gen->type == GEN_EDIPARTY) {
807
    // TODO(tniessen): this is what OpenSSL does, implement properly instead
808
    BIO_printf(out.get(), "EdiPartyName:<unsupported>");
809
  } else {
810
    // This is safe because X509V3_EXT_d2i would have returned nullptr in this
811
    // case already.
812
    UNREACHABLE();
813
  }
814
815
252
  return true;
816
}
817
818
75
bool SafeX509SubjectAltNamePrint(const BIOPointer& out, X509_EXTENSION* ext) {
819
75
  const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
820
75
  CHECK(method == X509V3_EXT_get_nid(NID_subject_alt_name));
821
822
75
  GENERAL_NAMES* names = static_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(ext));
823
75
  if (names == nullptr)
824
    return false;
825
826
75
  bool ok = true;
827
828
162
  for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) {
829
87
    GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);
830
831
87
    if (i != 0)
832
12
      BIO_write(out.get(), ", ", 2);
833
834
87
    if (!(ok = PrintGeneralName(out, gen))) {
835
      break;
836
    }
837
  }
838
75
  sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
839
840
75
  return ok;
841
}
842
843
86
bool SafeX509InfoAccessPrint(const BIOPointer& out, X509_EXTENSION* ext) {
844
86
  const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
845
86
  CHECK(method == X509V3_EXT_get_nid(NID_info_access));
846
847
  AUTHORITY_INFO_ACCESS* descs =
848
86
      static_cast<AUTHORITY_INFO_ACCESS*>(X509V3_EXT_d2i(ext));
849
86
  if (descs == nullptr)
850
    return false;
851
852
86
  bool ok = true;
853
854
251
  for (int i = 0; i < sk_ACCESS_DESCRIPTION_num(descs); i++) {
855
165
    ACCESS_DESCRIPTION* desc = sk_ACCESS_DESCRIPTION_value(descs, i);
856
857
165
    if (i != 0)
858
79
      BIO_write(out.get(), "\n", 1);
859
860
    char objtmp[80];
861
165
    i2t_ASN1_OBJECT(objtmp, sizeof(objtmp), desc->method);
862
165
    BIO_printf(out.get(), "%s - ", objtmp);
863
165
    if (!(ok = PrintGeneralName(out, desc->location))) {
864
      break;
865
    }
866
  }
867
86
  sk_ACCESS_DESCRIPTION_pop_free(descs, ACCESS_DESCRIPTION_free);
868
869
#if OPENSSL_VERSION_MAJOR < 3
870
  BIO_write(out.get(), "\n", 1);
871
#endif
872
873
86
  return ok;
874
}
875
876
1266
v8::MaybeLocal<v8::Value> GetSubjectAltNameString(
877
    Environment* env,
878
    const BIOPointer& bio,
879
    X509* cert) {
880
1266
  int index = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
881
1266
  if (index < 0)
882
2382
    return Undefined(env->isolate());
883
884
75
  X509_EXTENSION* ext = X509_get_ext(cert, index);
885
75
  CHECK_NOT_NULL(ext);
886
887
75
  if (!SafeX509SubjectAltNamePrint(bio, ext)) {
888
    CHECK_EQ(BIO_reset(bio.get()), 1);
889
    return v8::Null(env->isolate());
890
  }
891
892
150
  return ToV8Value(env, bio);
893
}
894
895
1238
v8::MaybeLocal<v8::Value> GetInfoAccessString(
896
    Environment* env,
897
    const BIOPointer& bio,
898
    X509* cert) {
899
1238
  int index = X509_get_ext_by_NID(cert, NID_info_access, -1);
900
1238
  if (index < 0)
901
2304
    return Undefined(env->isolate());
902
903
86
  X509_EXTENSION* ext = X509_get_ext(cert, index);
904
86
  CHECK_NOT_NULL(ext);
905
906
86
  if (!SafeX509InfoAccessPrint(bio, ext)) {
907
    CHECK_EQ(BIO_reset(bio.get()), 1);
908
    return v8::Null(env->isolate());
909
  }
910
911
172
  return ToV8Value(env, bio);
912
}
913
914
11
MaybeLocal<Value> GetIssuerString(
915
    Environment* env,
916
    const BIOPointer& bio,
917
    X509* cert) {
918
11
  X509_NAME* issuer_name = X509_get_issuer_name(cert);
919
11
  if (X509_NAME_print_ex(
920
          bio.get(),
921
          issuer_name,
922
          0,
923
11
          kX509NameFlagsMultiline) <= 0) {
924
    CHECK_EQ(BIO_reset(bio.get()), 1);
925
    return Undefined(env->isolate());
926
  }
927
928
22
  return ToV8Value(env, bio);
929
}
930
931
13
MaybeLocal<Value> GetSubject(
932
    Environment* env,
933
    const BIOPointer& bio,
934
    X509* cert) {
935
13
  if (X509_NAME_print_ex(
936
          bio.get(),
937
13
          X509_get_subject_name(cert),
938
          0,
939
13
          kX509NameFlagsMultiline) <= 0) {
940
    CHECK_EQ(BIO_reset(bio.get()), 1);
941
    return Undefined(env->isolate());
942
  }
943
944
26
  return ToV8Value(env, bio);
945
}
946
947
template <X509_NAME* get_name(const X509*)>
948
4928
static MaybeLocal<Value> GetX509NameObject(Environment* env, X509* cert) {
949
4928
  X509_NAME* name = get_name(cert);
950
4928
  CHECK_NOT_NULL(name);
951
952
4928
  int cnt = X509_NAME_entry_count(name);
953
4928
  CHECK_GE(cnt, 0);
954
955
  Local<Object> result =
956
9856
      Object::New(env->isolate(), Null(env->isolate()), nullptr, nullptr, 0);
957
4928
  if (result.IsEmpty()) {
958
    return MaybeLocal<Value>();
959
  }
960
961
36010
  for (int i = 0; i < cnt; i++) {
962
31082
    X509_NAME_ENTRY* entry = X509_NAME_get_entry(name, i);
963
31082
    CHECK_NOT_NULL(entry);
964
965
    // We intentionally ignore the value of X509_NAME_ENTRY_set because the
966
    // representation as an object does not allow grouping entries into sets
967
    // anyway, and multi-value RDNs are rare, i.e., the vast majority of
968
    // Relative Distinguished Names contains a single type-value pair only.
969
31082
    const ASN1_OBJECT* type = X509_NAME_ENTRY_get_object(entry);
970
31082
    const ASN1_STRING* value = X509_NAME_ENTRY_get_data(entry);
971
972
    // If OpenSSL knows the type, use the short name of the type as the key, and
973
    // the numeric representation of the type's OID otherwise.
974
31082
    int type_nid = OBJ_obj2nid(type);
975
    char type_buf[80];
976
    const char* type_str;
977
31082
    if (type_nid != NID_undef) {
978
31082
      type_str = OBJ_nid2sn(type_nid);
979
31082
      CHECK_NOT_NULL(type_str);
980
    } else {
981
      OBJ_obj2txt(type_buf, sizeof(type_buf), type, true);
982
      type_str = type_buf;
983
    }
984
985
    Local<String> v8_name;
986
62164
    if (!String::NewFromUtf8(env->isolate(), type_str).ToLocal(&v8_name)) {
987
      return MaybeLocal<Value>();
988
    }
989
990
    // The previous implementation used X509_NAME_print_ex, which escapes some
991
    // characters in the value. The old implementation did not decode/unescape
992
    // values correctly though, leading to ambiguous and incorrect
993
    // representations. The new implementation only converts to Unicode and does
994
    // not escape anything.
995
    unsigned char* value_str;
996
31082
    int value_str_size = ASN1_STRING_to_UTF8(&value_str, value);
997
31082
    if (value_str_size < 0) {
998
      return Undefined(env->isolate());
999
    }
1000
1001
    Local<String> v8_value;
1002
31082
    if (!String::NewFromUtf8(env->isolate(),
1003
                             reinterpret_cast<const char*>(value_str),
1004
                             NewStringType::kNormal,
1005
31082
                             value_str_size).ToLocal(&v8_value)) {
1006
      OPENSSL_free(value_str);
1007
      return MaybeLocal<Value>();
1008
    }
1009
1010
31082
    OPENSSL_free(value_str);
1011
1012
    // For backward compatibility, we only create arrays if multiple values
1013
    // exist for the same key. That is not great but there is not much we can
1014
    // change here without breaking things. Note that this creates nested data
1015
    // structures, yet still does not allow representing Distinguished Names
1016
    // accurately.
1017
    bool multiple;
1018
62164
    if (!result->HasOwnProperty(env->context(), v8_name).To(&multiple)) {
1019
      return MaybeLocal<Value>();
1020
31082
    } else if (multiple) {
1021
      Local<Value> accum;
1022
120
      if (!result->Get(env->context(), v8_name).ToLocal(&accum)) {
1023
        return MaybeLocal<Value>();
1024
      }
1025
60
      if (!accum->IsArray()) {
1026
88
        accum = Array::New(env->isolate(), &accum, 1);
1027
88
        if (result->Set(env->context(), v8_name, accum).IsNothing()) {
1028
          return MaybeLocal<Value>();
1029
        }
1030
      }
1031
60
      Local<Array> array = accum.As<Array>();
1032
120
      if (array->Set(env->context(), array->Length(), v8_value).IsNothing()) {
1033
        return MaybeLocal<Value>();
1034
      }
1035
62044
    } else if (result->Set(env->context(), v8_name, v8_value).IsNothing()) {
1036
      return MaybeLocal<Value>();
1037
    }
1038
  }
1039
1040
4928
  return result;
1041
}
1042
1043
template <MaybeLocal<Value> (*Get)(Environment* env, const SSL_CIPHER* cipher)>
1044
318
MaybeLocal<Value> GetCurrentCipherValue(Environment* env,
1045
                                        const SSLPointer& ssl) {
1046
318
  return Get(env, SSL_get_current_cipher(ssl.get()));
1047
}
1048
1049
MaybeLocal<Array> GetClientHelloCiphers(
1050
    Environment* env,
1051
    const SSLPointer& ssl) {
1052
  EscapableHandleScope scope(env->isolate());
1053
  const unsigned char* buf;
1054
  size_t len = SSL_client_hello_get0_ciphers(ssl.get(), &buf);
1055
  size_t count = len / 2;
1056
  MaybeStackBuffer<Local<Value>, 16> ciphers(count);
1057
  int j = 0;
1058
  for (size_t n = 0; n < len; n += 2) {
1059
    const SSL_CIPHER* cipher = SSL_CIPHER_find(ssl.get(), buf);
1060
    buf += 2;
1061
    Local<Object> obj = Object::New(env->isolate());
1062
    if (!Set(env->context(),
1063
             obj,
1064
             env->name_string(),
1065
             GetCipherName(env, cipher)) ||
1066
        !Set(env->context(),
1067
             obj,
1068
             env->standard_name_string(),
1069
             GetCipherStandardName(env, cipher)) ||
1070
        !Set(env->context(),
1071
             obj,
1072
             env->version_string(),
1073
             GetCipherVersion(env, cipher))) {
1074
      return MaybeLocal<Array>();
1075
    }
1076
    ciphers[j++] = obj;
1077
  }
1078
  Local<Array> ret = Array::New(env->isolate(), ciphers.out(), count);
1079
  return scope.Escape(ret);
1080
}
1081
1082
1083
53
MaybeLocal<Object> GetCipherInfo(Environment* env, const SSLPointer& ssl) {
1084
53
  if (SSL_get_current_cipher(ssl.get()) == nullptr)
1085
    return MaybeLocal<Object>();
1086
53
  EscapableHandleScope scope(env->isolate());
1087
53
  Local<Object> info = Object::New(env->isolate());
1088
1089
106
  if (!Set<Value>(env->context(),
1090
                  info,
1091
                  env->name_string(),
1092
53
                  GetCurrentCipherValue<GetCipherName>(env, ssl)) ||
1093
106
      !Set<Value>(env->context(),
1094
                  info,
1095
                  env->standard_name_string(),
1096
106
                  GetCurrentCipherValue<GetCipherStandardName>(env, ssl)) ||
1097

159
      !Set<Value>(env->context(),
1098
                  info,
1099
                  env->version_string(),
1100
                  GetCurrentCipherValue<GetCipherVersion>(env, ssl))) {
1101
    return MaybeLocal<Object>();
1102
  }
1103
1104
53
  return scope.Escape(info);
1105
}
1106
1107
891
MaybeLocal<Object> GetEphemeralKey(Environment* env, const SSLPointer& ssl) {
1108
891
  CHECK_EQ(SSL_is_server(ssl.get()), 0);
1109
  EVP_PKEY* raw_key;
1110
1111
891
  EscapableHandleScope scope(env->isolate());
1112
891
  Local<Object> info = Object::New(env->isolate());
1113
891
  if (!SSL_get_server_tmp_key(ssl.get(), &raw_key))
1114
30
    return scope.Escape(info);
1115
1116
861
  Local<Context> context = env->context();
1117
1722
  crypto::EVPKeyPointer key(raw_key);
1118
1119
861
  int kid = EVP_PKEY_id(key.get());
1120
861
  int bits = EVP_PKEY_bits(key.get());
1121
861
  switch (kid) {
1122
7
    case EVP_PKEY_DH:
1123
28
      if (!Set<String>(context, info, env->type_string(), env->dh_string()) ||
1124

28
          !Set<Integer>(context,
1125
               info,
1126
               env->size_string(),
1127
               Integer::New(env->isolate(), bits))) {
1128
        return MaybeLocal<Object>();
1129
      }
1130
7
      break;
1131
854
    case EVP_PKEY_EC:
1132
    case EVP_PKEY_X25519:
1133
    case EVP_PKEY_X448:
1134
      {
1135
        const char* curve_name;
1136
854
        if (kid == EVP_PKEY_EC) {
1137
10
          ECKeyPointer ec(EVP_PKEY_get1_EC_KEY(key.get()));
1138
5
          int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec.get()));
1139
5
          curve_name = OBJ_nid2sn(nid);
1140
        } else {
1141
849
          curve_name = OBJ_nid2sn(kid);
1142
        }
1143
2562
        if (!Set<String>(context,
1144
                         info,
1145
                         env->type_string(),
1146
854
                         env->ecdh_string()) ||
1147
2562
            !Set<String>(context,
1148
                info,
1149
                env->name_string(),
1150
1708
                OneByteString(env->isolate(), curve_name)) ||
1151

3416
            !Set<Integer>(context,
1152
                 info,
1153
                 env->size_string(),
1154
                 Integer::New(env->isolate(), bits))) {
1155
          return MaybeLocal<Object>();
1156
854
        }
1157
      }
1158
854
      break;
1159
  }
1160
1161
861
  return scope.Escape(info);
1162
}
1163
1164
73
MaybeLocal<Object> ECPointToBuffer(Environment* env,
1165
                                   const EC_GROUP* group,
1166
                                   const EC_POINT* point,
1167
                                   point_conversion_form_t form,
1168
                                   const char** error) {
1169
73
  size_t len = EC_POINT_point2oct(group, point, form, nullptr, 0, nullptr);
1170
73
  if (len == 0) {
1171
    if (error != nullptr) *error = "Failed to get public key length";
1172
    return MaybeLocal<Object>();
1173
  }
1174
1175
73
  std::unique_ptr<BackingStore> bs;
1176
  {
1177
73
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
1178
73
    bs = ArrayBuffer::NewBackingStore(env->isolate(), len);
1179
  }
1180
1181
146
  len = EC_POINT_point2oct(group,
1182
                           point,
1183
                           form,
1184
73
                           reinterpret_cast<unsigned char*>(bs->Data()),
1185
                           bs->ByteLength(),
1186
                           nullptr);
1187
73
  if (len == 0) {
1188
    if (error != nullptr) *error = "Failed to get public key";
1189
    return MaybeLocal<Object>();
1190
  }
1191
1192
73
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
1193
146
  return Buffer::New(env, ab, 0, ab->ByteLength()).FromMaybe(Local<Object>());
1194
}
1195
1196
497
MaybeLocal<Value> GetPeerCert(
1197
    Environment* env,
1198
    const SSLPointer& ssl,
1199
    bool abbreviated,
1200
    bool is_server) {
1201
497
  ClearErrorOnReturn clear_error_on_return;
1202
  Local<Object> result;
1203
  MaybeLocal<Object> maybe_cert;
1204
1205
  // NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain`
1206
  // contains the `peer_certificate`, but on server it doesn't.
1207
994
  X509Pointer cert(is_server ? SSL_get_peer_certificate(ssl.get()) : nullptr);
1208
497
  STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(ssl.get());
1209


497
  if (!cert && (ssl_certs == nullptr || sk_X509_num(ssl_certs) == 0))
1210
10
    return Undefined(env->isolate());
1211
1212
  // Short result requested.
1213
492
  if (abbreviated) {
1214
    maybe_cert =
1215
43
        X509ToObject(env, cert ? cert.get() : sk_X509_value(ssl_certs, 0));
1216
86
    return maybe_cert.ToLocal(&result) ? result : MaybeLocal<Value>();
1217
  }
1218
1219
898
  StackOfX509 peer_certs = CloneSSLCerts(std::move(cert), ssl_certs);
1220
449
  if (peer_certs == nullptr)
1221
    return Undefined(env->isolate());
1222
1223
  // First and main certificate.
1224
898
  X509Pointer first_cert(sk_X509_value(peer_certs.get(), 0));
1225
449
  CHECK(first_cert);
1226
449
  maybe_cert = X509ToObject(env, first_cert.release());
1227
449
  if (!maybe_cert.ToLocal(&result))
1228
    return MaybeLocal<Value>();
1229
1230
  Local<Object> issuer_chain;
1231
  MaybeLocal<Object> maybe_issuer_chain;
1232
1233
  maybe_issuer_chain =
1234
      AddIssuerChainToObject(
1235
          &cert,
1236
          result,
1237
449
          std::move(peer_certs),
1238
449
          env);
1239
449
  if (!maybe_issuer_chain.ToLocal(&issuer_chain))
1240
    return MaybeLocal<Value>();
1241
1242
  maybe_issuer_chain =
1243
      GetLastIssuedCert(
1244
          &cert,
1245
          ssl,
1246
          issuer_chain,
1247
449
          env);
1248
1249
  issuer_chain.Clear();
1250
449
  if (!maybe_issuer_chain.ToLocal(&issuer_chain))
1251
    return MaybeLocal<Value>();
1252
1253
  // Last certificate should be self-signed.
1254
897
  if (X509_check_issued(cert.get(), cert.get()) == X509_V_OK &&
1255

1345
      !Set<Object>(env->context(),
1256
           issuer_chain,
1257
           env->issuercert_string(),
1258
           issuer_chain)) {
1259
    return MaybeLocal<Value>();
1260
  }
1261
1262
449
  return result;
1263
}
1264
1265
1232
MaybeLocal<Object> X509ToObject(
1266
    Environment* env,
1267
    X509* cert) {
1268
1232
  EscapableHandleScope scope(env->isolate());
1269
1232
  Local<Context> context = env->context();
1270
1232
  Local<Object> info = Object::New(env->isolate());
1271
1272
2464
  BIOPointer bio(BIO_new(BIO_s_mem()));
1273
1232
  CHECK(bio);
1274
1275
2464
  if (!Set<Value>(context,
1276
                  info,
1277
                  env->subject_string(),
1278
1232
                  GetX509NameObject<X509_get_subject_name>(env, cert)) ||
1279
2464
      !Set<Value>(context,
1280
                  info,
1281
                  env->issuer_string(),
1282
1232
                  GetX509NameObject<X509_get_issuer_name>(env, cert)) ||
1283
2464
      !Set<Value>(context,
1284
                  info,
1285
                  env->subjectaltname_string(),
1286
2464
                  GetSubjectAltNameString(env, bio, cert)) ||
1287

3696
      !Set<Value>(context,
1288
                  info,
1289
                  env->infoaccess_string(),
1290
                  GetInfoAccessString(env, bio, cert))) {
1291
    return MaybeLocal<Object>();
1292
  }
1293
1294
2464
  EVPKeyPointer pkey(X509_get_pubkey(cert));
1295
1232
  RSAPointer rsa;
1296
1232
  ECPointer ec;
1297
1232
  if (pkey) {
1298
1232
    switch (EVP_PKEY_id(pkey.get())) {
1299
1185
      case EVP_PKEY_RSA:
1300
1185
        rsa.reset(EVP_PKEY_get1_RSA(pkey.get()));
1301
1185
        break;
1302
47
      case EVP_PKEY_EC:
1303
47
        ec.reset(EVP_PKEY_get1_EC_KEY(pkey.get()));
1304
47
        break;
1305
    }
1306
  }
1307
1308
1232
  if (rsa) {
1309
    const BIGNUM* n;
1310
    const BIGNUM* e;
1311
1185
    RSA_get0_key(rsa.get(), &n, &e, nullptr);
1312
2370
    if (!Set<Value>(context,
1313
                    info,
1314
                    env->modulus_string(),
1315
1185
                    GetModulusString(env, bio, n)) ||
1316
3555
        !Set<Value>(context, info, env->bits_string(), GetBits(env, n)) ||
1317
2370
        !Set<Value>(context,
1318
                    info,
1319
                    env->exponent_string(),
1320
2370
                    GetExponentString(env, bio, e)) ||
1321

3555
        !Set<Object>(context,
1322
                     info,
1323
                     env->pubkey_string(),
1324
                     GetPubKey(env, rsa))) {
1325
      return MaybeLocal<Object>();
1326
    }
1327
47
  } else if (ec) {
1328
47
    const EC_GROUP* group = EC_KEY_get0_group(ec.get());
1329
1330
94
    if (!Set<Value>(context,
1331
                    info,
1332
                    env->bits_string(),
1333
94
                    GetECGroup(env, group, ec)) ||
1334

141
        !Set<Value>(context,
1335
                    info,
1336
                    env->pubkey_string(),
1337
                    GetECPubKey(env, group, ec))) {
1338
      return MaybeLocal<Object>();
1339
    }
1340
1341
47
    const int nid = EC_GROUP_get_curve_name(group);
1342
47
    if (nid != 0) {
1343
      // Curve is well-known, get its OID and NIST nick-name (if it has one).
1344
1345
94
      if (!Set<Value>(context,
1346
                      info,
1347
                      env->asn1curve_string(),
1348
94
                      GetCurveName<OBJ_nid2sn>(env, nid)) ||
1349

141
          !Set<Value>(context,
1350
                      info,
1351
                      env->nistcurve_string(),
1352
                      GetCurveName<EC_curve_nid2nist>(env, nid))) {
1353
        return MaybeLocal<Object>();
1354
      }
1355
    } else {
1356
      // Unnamed curves can be described by their mathematical properties,
1357
      // but aren't used much (at all?) with X.509/TLS. Support later if needed.
1358
    }
1359
  }
1360
1361
  // pkey, rsa, and ec pointers are no longer needed.
1362
1232
  pkey.reset();
1363
1232
  rsa.reset();
1364
1232
  ec.reset();
1365
1366
2464
  if (!Set<Value>(context,
1367
                  info,
1368
                  env->valid_from_string(),
1369
2464
                  GetValidFrom(env, cert, bio)) ||
1370

3696
      !Set<Value>(context,
1371
                  info,
1372
                  env->valid_to_string(),
1373
                  GetValidTo(env, cert, bio))) {
1374
    return MaybeLocal<Object>();
1375
  }
1376
1377
  // bio is no longer needed
1378
1232
  bio.reset();
1379
1380
2464
  if (!Set<Value>(context,
1381
                  info,
1382
                  env->fingerprint_string(),
1383
1232
                  GetFingerprintDigest(env, EVP_sha1(), cert)) ||
1384
2464
      !Set<Value>(context,
1385
                  info,
1386
                  env->fingerprint256_string(),
1387
1232
                  GetFingerprintDigest(env, EVP_sha256(), cert)) ||
1388
2464
      !Set<Value>(context,
1389
                  info,
1390
                  env->fingerprint512_string(),
1391
1232
                  GetFingerprintDigest(env, EVP_sha512(), cert)) ||
1392
2464
      !Set<Value>(context,
1393
                  info,
1394
                  env->ext_key_usage_string(),
1395
1232
                  GetKeyUsage(env, cert)) ||
1396
2464
      !Set<Value>(context,
1397
                  info,
1398
                  env->serial_number_string(),
1399
2464
                  GetSerialNumber(env, cert)) ||
1400

3696
      !Set<Object>(context,
1401
                   info,
1402
                   env->raw_string(),
1403
                   GetRawDERCertificate(env, cert))) {
1404
    return MaybeLocal<Object>();
1405
  }
1406
1407
1232
  return scope.Escape(info);
1408
}
1409
1410
}  // namespace crypto
1411
}  // namespace node