GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_common.cc Lines: 529 691 76.6 %
Date: 2022-05-15 04:15:05 Branches: 279 485 57.5 %

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
898
bool SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) {
56
898
  X509_STORE* store = SSL_CTX_get_cert_store(ctx);
57
  DeleteFnPtr<X509_STORE_CTX, X509_STORE_CTX_free> store_ctx(
58
898
      X509_STORE_CTX_new());
59
1796
  return store_ctx.get() != nullptr &&
60

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

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

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

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







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

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

319
        if (static_cast<unsigned char>(c) < ' ' || c == '\x7f') {
621
7
          return false;
622
        }
623
      } else {
624
        // Check if the char is a control character or non-ASCII character. Note
625
        // that char may or may not be a signed type. Regardless, non-ASCII
626
        // values will always be outside of this range.
627

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


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

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

26
    switch (nid) {
779
      case NID_id_on_SmtpUTF8Mailbox:
780
        prefix = "SmtpUTF8Mailbox";
781
        break;
782
12
      case NID_XmppAddr:
783
12
        prefix = "XmppAddr";
784
12
        break;
785
9
      case NID_SRVName:
786
9
        prefix = "SRVName";
787
9
        unicode = false;
788
9
        break;
789
      case NID_ms_upn:
790
        prefix = "UPN";
791
        break;
792
      case NID_NAIRealm:
793
        prefix = "NAIRealm";
794
        break;
795
    }
796
#endif  // OPENSSL_VERSION_MAJOR >= 3
797
26
    int val_type = gen->d.otherName->value->type;
798

26
    if (prefix == nullptr ||
799
12
        (unicode && val_type != V_ASN1_UTF8STRING) ||
800

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

159
      !Set<Value>(env->context(),
1115
                  info,
1116
                  env->version_string(),
1117
                  GetCipherVersion(env, ssl))) {
1118
    return MaybeLocal<Object>();
1119
  }
1120
1121
53
  return scope.Escape(info);
1122
}
1123
1124
890
MaybeLocal<Object> GetEphemeralKey(Environment* env, const SSLPointer& ssl) {
1125
890
  CHECK_EQ(SSL_is_server(ssl.get()), 0);
1126
  EVP_PKEY* raw_key;
1127
1128
890
  EscapableHandleScope scope(env->isolate());
1129
890
  Local<Object> info = Object::New(env->isolate());
1130
890
  if (!SSL_get_server_tmp_key(ssl.get(), &raw_key))
1131
30
    return scope.Escape(info);
1132
1133
860
  Local<Context> context = env->context();
1134
1720
  crypto::EVPKeyPointer key(raw_key);
1135
1136
860
  int kid = EVP_PKEY_id(key.get());
1137
860
  int bits = EVP_PKEY_bits(key.get());
1138
860
  switch (kid) {
1139
7
    case EVP_PKEY_DH:
1140
28
      if (!Set<String>(context, info, env->type_string(), env->dh_string()) ||
1141

28
          !Set<Integer>(context,
1142
               info,
1143
               env->size_string(),
1144
               Integer::New(env->isolate(), bits))) {
1145
        return MaybeLocal<Object>();
1146
      }
1147
7
      break;
1148
853
    case EVP_PKEY_EC:
1149
    case EVP_PKEY_X25519:
1150
    case EVP_PKEY_X448:
1151
      {
1152
        const char* curve_name;
1153
853
        if (kid == EVP_PKEY_EC) {
1154
10
          ECKeyPointer ec(EVP_PKEY_get1_EC_KEY(key.get()));
1155
5
          int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec.get()));
1156
5
          curve_name = OBJ_nid2sn(nid);
1157
        } else {
1158
848
          curve_name = OBJ_nid2sn(kid);
1159
        }
1160
2559
        if (!Set<String>(context,
1161
                         info,
1162
                         env->type_string(),
1163
853
                         env->ecdh_string()) ||
1164
2559
            !Set<String>(context,
1165
                info,
1166
                env->name_string(),
1167
1706
                OneByteString(env->isolate(), curve_name)) ||
1168

3412
            !Set<Integer>(context,
1169
                 info,
1170
                 env->size_string(),
1171
                 Integer::New(env->isolate(), bits))) {
1172
          return MaybeLocal<Object>();
1173
853
        }
1174
      }
1175
853
      break;
1176
  }
1177
1178
860
  return scope.Escape(info);
1179
}
1180
1181
73
MaybeLocal<Object> ECPointToBuffer(Environment* env,
1182
                                   const EC_GROUP* group,
1183
                                   const EC_POINT* point,
1184
                                   point_conversion_form_t form,
1185
                                   const char** error) {
1186
73
  size_t len = EC_POINT_point2oct(group, point, form, nullptr, 0, nullptr);
1187
73
  if (len == 0) {
1188
    if (error != nullptr) *error = "Failed to get public key length";
1189
    return MaybeLocal<Object>();
1190
  }
1191
1192
73
  std::unique_ptr<BackingStore> bs;
1193
  {
1194
73
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
1195
73
    bs = ArrayBuffer::NewBackingStore(env->isolate(), len);
1196
  }
1197
1198
146
  len = EC_POINT_point2oct(group,
1199
                           point,
1200
                           form,
1201
73
                           reinterpret_cast<unsigned char*>(bs->Data()),
1202
                           bs->ByteLength(),
1203
                           nullptr);
1204
73
  if (len == 0) {
1205
    if (error != nullptr) *error = "Failed to get public key";
1206
    return MaybeLocal<Object>();
1207
  }
1208
1209
73
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
1210
146
  return Buffer::New(env, ab, 0, ab->ByteLength()).FromMaybe(Local<Object>());
1211
}
1212
1213
496
MaybeLocal<Value> GetPeerCert(
1214
    Environment* env,
1215
    const SSLPointer& ssl,
1216
    bool abbreviated,
1217
    bool is_server) {
1218
496
  ClearErrorOnReturn clear_error_on_return;
1219
  Local<Object> result;
1220
  MaybeLocal<Object> maybe_cert;
1221
1222
  // NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain`
1223
  // contains the `peer_certificate`, but on server it doesn't.
1224
992
  X509Pointer cert(is_server ? SSL_get_peer_certificate(ssl.get()) : nullptr);
1225
496
  STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(ssl.get());
1226


496
  if (!cert && (ssl_certs == nullptr || sk_X509_num(ssl_certs) == 0))
1227
10
    return Undefined(env->isolate());
1228
1229
  // Short result requested.
1230
491
  if (abbreviated) {
1231
    maybe_cert =
1232
43
        X509ToObject(env, cert ? cert.get() : sk_X509_value(ssl_certs, 0));
1233
86
    return maybe_cert.ToLocal(&result) ? result : MaybeLocal<Value>();
1234
  }
1235
1236
896
  StackOfX509 peer_certs = CloneSSLCerts(std::move(cert), ssl_certs);
1237
448
  if (peer_certs == nullptr)
1238
    return Undefined(env->isolate());
1239
1240
  // First and main certificate.
1241
896
  X509Pointer first_cert(sk_X509_value(peer_certs.get(), 0));
1242
448
  CHECK(first_cert);
1243
448
  maybe_cert = X509ToObject(env, first_cert.release());
1244
448
  if (!maybe_cert.ToLocal(&result))
1245
    return MaybeLocal<Value>();
1246
1247
  Local<Object> issuer_chain;
1248
  MaybeLocal<Object> maybe_issuer_chain;
1249
1250
  maybe_issuer_chain =
1251
      AddIssuerChainToObject(
1252
          &cert,
1253
          result,
1254
448
          std::move(peer_certs),
1255
448
          env);
1256
448
  if (!maybe_issuer_chain.ToLocal(&issuer_chain))
1257
    return MaybeLocal<Value>();
1258
1259
  maybe_issuer_chain =
1260
      GetLastIssuedCert(
1261
          &cert,
1262
          ssl,
1263
          issuer_chain,
1264
448
          env);
1265
1266
  issuer_chain.Clear();
1267
448
  if (!maybe_issuer_chain.ToLocal(&issuer_chain))
1268
    return MaybeLocal<Value>();
1269
1270
  // Last certificate should be self-signed.
1271
895
  if (X509_check_issued(cert.get(), cert.get()) == X509_V_OK &&
1272

1342
      !Set<Object>(env->context(),
1273
           issuer_chain,
1274
           env->issuercert_string(),
1275
           issuer_chain)) {
1276
    return MaybeLocal<Value>();
1277
  }
1278
1279
448
  return result;
1280
}
1281
1282
1230
MaybeLocal<Object> X509ToObject(
1283
    Environment* env,
1284
    X509* cert) {
1285
1230
  EscapableHandleScope scope(env->isolate());
1286
1230
  Local<Context> context = env->context();
1287
1230
  Local<Object> info = Object::New(env->isolate());
1288
1289
2460
  BIOPointer bio(BIO_new(BIO_s_mem()));
1290
1230
  CHECK(bio);
1291
1292
2460
  if (!Set<Value>(context,
1293
                  info,
1294
                  env->subject_string(),
1295
1230
                  GetX509NameObject<X509_get_subject_name>(env, cert)) ||
1296
2460
      !Set<Value>(context,
1297
                  info,
1298
                  env->issuer_string(),
1299
1230
                  GetX509NameObject<X509_get_issuer_name>(env, cert)) ||
1300
2460
      !Set<Value>(context,
1301
                  info,
1302
                  env->subjectaltname_string(),
1303
2460
                  GetSubjectAltNameString(env, bio, cert)) ||
1304

3690
      !Set<Value>(context,
1305
                  info,
1306
                  env->infoaccess_string(),
1307
                  GetInfoAccessString(env, bio, cert))) {
1308
    return MaybeLocal<Object>();
1309
  }
1310
1311
2460
  EVPKeyPointer pkey(X509_get_pubkey(cert));
1312
1230
  RSAPointer rsa;
1313
1230
  ECPointer ec;
1314
1230
  if (pkey) {
1315
1230
    switch (EVP_PKEY_id(pkey.get())) {
1316
1183
      case EVP_PKEY_RSA:
1317
1183
        rsa.reset(EVP_PKEY_get1_RSA(pkey.get()));
1318
1183
        break;
1319
47
      case EVP_PKEY_EC:
1320
47
        ec.reset(EVP_PKEY_get1_EC_KEY(pkey.get()));
1321
47
        break;
1322
    }
1323
  }
1324
1325
1230
  if (rsa) {
1326
    const BIGNUM* n;
1327
    const BIGNUM* e;
1328
1183
    RSA_get0_key(rsa.get(), &n, &e, nullptr);
1329
2366
    if (!Set<Value>(context,
1330
                    info,
1331
                    env->modulus_string(),
1332
1183
                    GetModulusString(env, bio, n)) ||
1333
3549
        !Set<Value>(context, info, env->bits_string(), GetBits(env, n)) ||
1334
2366
        !Set<Value>(context,
1335
                    info,
1336
                    env->exponent_string(),
1337
2366
                    GetExponentString(env, bio, e)) ||
1338

3549
        !Set<Object>(context,
1339
                     info,
1340
                     env->pubkey_string(),
1341
                     GetPubKey(env, rsa))) {
1342
      return MaybeLocal<Object>();
1343
    }
1344
47
  } else if (ec) {
1345
47
    const EC_GROUP* group = EC_KEY_get0_group(ec.get());
1346
1347
94
    if (!Set<Value>(context,
1348
                    info,
1349
                    env->bits_string(),
1350
94
                    GetECGroup(env, group, ec)) ||
1351

141
        !Set<Value>(context,
1352
                    info,
1353
                    env->pubkey_string(),
1354
                    GetECPubKey(env, group, ec))) {
1355
      return MaybeLocal<Object>();
1356
    }
1357
1358
47
    const int nid = EC_GROUP_get_curve_name(group);
1359
47
    if (nid != 0) {
1360
      // Curve is well-known, get its OID and NIST nick-name (if it has one).
1361
1362
94
      if (!Set<Value>(context,
1363
                      info,
1364
                      env->asn1curve_string(),
1365
94
                      GetCurveName<OBJ_nid2sn>(env, nid)) ||
1366

141
          !Set<Value>(context,
1367
                      info,
1368
                      env->nistcurve_string(),
1369
                      GetCurveName<EC_curve_nid2nist>(env, nid))) {
1370
        return MaybeLocal<Object>();
1371
      }
1372
    } else {
1373
      // Unnamed curves can be described by their mathematical properties,
1374
      // but aren't used much (at all?) with X.509/TLS. Support later if needed.
1375
    }
1376
  }
1377
1378
  // pkey, rsa, and ec pointers are no longer needed.
1379
1230
  pkey.reset();
1380
1230
  rsa.reset();
1381
1230
  ec.reset();
1382
1383
2460
  if (!Set<Value>(context,
1384
                  info,
1385
                  env->valid_from_string(),
1386
2460
                  GetValidFrom(env, cert, bio)) ||
1387

3690
      !Set<Value>(context,
1388
                  info,
1389
                  env->valid_to_string(),
1390
                  GetValidTo(env, cert, bio))) {
1391
    return MaybeLocal<Object>();
1392
  }
1393
1394
  // bio is no longer needed
1395
1230
  bio.reset();
1396
1397
2460
  if (!Set<Value>(context,
1398
                  info,
1399
                  env->fingerprint_string(),
1400
1230
                  GetFingerprintDigest(env, EVP_sha1(), cert)) ||
1401
2460
      !Set<Value>(context,
1402
                  info,
1403
                  env->fingerprint256_string(),
1404
1230
                  GetFingerprintDigest(env, EVP_sha256(), cert)) ||
1405
2460
      !Set<Value>(context,
1406
                  info,
1407
                  env->fingerprint512_string(),
1408
1230
                  GetFingerprintDigest(env, EVP_sha512(), cert)) ||
1409
2460
      !Set<Value>(context,
1410
                  info,
1411
                  env->ext_key_usage_string(),
1412
1230
                  GetKeyUsage(env, cert)) ||
1413
2460
      !Set<Value>(context,
1414
                  info,
1415
                  env->serial_number_string(),
1416
2460
                  GetSerialNumber(env, cert)) ||
1417

3690
      !Set<Object>(context,
1418
                   info,
1419
                   env->raw_string(),
1420
                   GetRawDERCertificate(env, cert))) {
1421
    return MaybeLocal<Object>();
1422
  }
1423
1424
1230
  return scope.Escape(info);
1425
}
1426
1427
}  // namespace crypto
1428
}  // namespace node