GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_common.cc Lines: 520 679 76.6 %
Date: 2022-09-25 04:23:55 Branches: 282 491 57.4 %

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::BackingStore;
30
using v8::Context;
31
using v8::EscapableHandleScope;
32
using v8::Integer;
33
using v8::Local;
34
using v8::MaybeLocal;
35
using v8::NewStringType;
36
using v8::Object;
37
using v8::String;
38
using v8::Undefined;
39
using v8::Value;
40
41
namespace crypto {
42
static constexpr int kX509NameFlagsMultiline =
43
    ASN1_STRFLGS_ESC_2253 |
44
    ASN1_STRFLGS_ESC_CTRL |
45
    ASN1_STRFLGS_UTF8_CONVERT |
46
    XN_FLAG_SEP_MULTILINE |
47
    XN_FLAG_FN_SN;
48
49
static constexpr int kX509NameFlagsRFC2253WithinUtf8JSON =
50
    XN_FLAG_RFC2253 &
51
    ~ASN1_STRFLGS_ESC_MSB &
52
    ~ASN1_STRFLGS_ESC_CTRL;
53
54
904
X509Pointer SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert) {
55
904
  X509_STORE* store = SSL_CTX_get_cert_store(ctx);
56
  DeleteFnPtr<X509_STORE_CTX, X509_STORE_CTX_free> store_ctx(
57
1808
      X509_STORE_CTX_new());
58
904
  X509Pointer result;
59
  X509* issuer;
60
1808
  if (store_ctx.get() != nullptr &&
61

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

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

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

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







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

451
  if (cert && !sk_X509_push(peer_certs.get(), cert.release()))
328
    return StackOfX509();
329
1246
  for (int i = 0; i < sk_X509_num(ssl_certs); i++) {
330
795
    X509Pointer cert(X509_dup(sk_X509_value(ssl_certs, i)));
331

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

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

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


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

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

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

26
    if (prefix == nullptr ||
785
12
        (unicode && val_type != V_ASN1_UTF8STRING) ||
786

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

171
      !Set<Value>(env->context(),
1093
                  info,
1094
                  env->version_string(),
1095
                  GetCurrentCipherValue<GetCipherVersion>(env, ssl))) {
1096
    return MaybeLocal<Object>();
1097
  }
1098
1099
57
  return scope.Escape(info);
1100
}
1101
1102
894
MaybeLocal<Object> GetEphemeralKey(Environment* env, const SSLPointer& ssl) {
1103
894
  CHECK_EQ(SSL_is_server(ssl.get()), 0);
1104
  EVP_PKEY* raw_key;
1105
1106
894
  EscapableHandleScope scope(env->isolate());
1107
894
  Local<Object> info = Object::New(env->isolate());
1108
894
  if (!SSL_get_server_tmp_key(ssl.get(), &raw_key))
1109
27
    return scope.Escape(info);
1110
1111
867
  Local<Context> context = env->context();
1112
1734
  crypto::EVPKeyPointer key(raw_key);
1113
1114
867
  int kid = EVP_PKEY_id(key.get());
1115
867
  int bits = EVP_PKEY_bits(key.get());
1116
867
  switch (kid) {
1117
6
    case EVP_PKEY_DH:
1118
24
      if (!Set<String>(context, info, env->type_string(), env->dh_string()) ||
1119

24
          !Set<Integer>(context,
1120
               info,
1121
               env->size_string(),
1122
               Integer::New(env->isolate(), bits))) {
1123
        return MaybeLocal<Object>();
1124
      }
1125
6
      break;
1126
861
    case EVP_PKEY_EC:
1127
    case EVP_PKEY_X25519:
1128
    case EVP_PKEY_X448:
1129
      {
1130
        const char* curve_name;
1131
861
        if (kid == EVP_PKEY_EC) {
1132
10
          ECKeyPointer ec(EVP_PKEY_get1_EC_KEY(key.get()));
1133
5
          int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec.get()));
1134
5
          curve_name = OBJ_nid2sn(nid);
1135
        } else {
1136
856
          curve_name = OBJ_nid2sn(kid);
1137
        }
1138
2583
        if (!Set<String>(context,
1139
                         info,
1140
                         env->type_string(),
1141
861
                         env->ecdh_string()) ||
1142
2583
            !Set<String>(context,
1143
                info,
1144
                env->name_string(),
1145
1722
                OneByteString(env->isolate(), curve_name)) ||
1146

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


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

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

3714
      !Set<Value>(context,
1283
                  info,
1284
                  env->infoaccess_string(),
1285
                  GetInfoAccessString(env, bio, cert))) {
1286
    return MaybeLocal<Object>();
1287
  }
1288
1289
2476
  EVPKeyPointer pkey(X509_get_pubkey(cert));
1290
1238
  RSAPointer rsa;
1291
1238
  ECPointer ec;
1292
1238
  if (pkey) {
1293
1238
    switch (EVP_PKEY_id(pkey.get())) {
1294
1191
      case EVP_PKEY_RSA:
1295
1191
        rsa.reset(EVP_PKEY_get1_RSA(pkey.get()));
1296
1191
        break;
1297
47
      case EVP_PKEY_EC:
1298
47
        ec.reset(EVP_PKEY_get1_EC_KEY(pkey.get()));
1299
47
        break;
1300
    }
1301
  }
1302
1303
1238
  if (rsa) {
1304
    const BIGNUM* n;
1305
    const BIGNUM* e;
1306
1191
    RSA_get0_key(rsa.get(), &n, &e, nullptr);
1307
2382
    if (!Set<Value>(context,
1308
                    info,
1309
                    env->modulus_string(),
1310
1191
                    GetModulusString(env, bio, n)) ||
1311
3573
        !Set<Value>(context, info, env->bits_string(), GetBits(env, n)) ||
1312
2382
        !Set<Value>(context,
1313
                    info,
1314
                    env->exponent_string(),
1315
2382
                    GetExponentString(env, bio, e)) ||
1316

3573
        !Set<Object>(context,
1317
                     info,
1318
                     env->pubkey_string(),
1319
                     GetPubKey(env, rsa))) {
1320
      return MaybeLocal<Object>();
1321
    }
1322
47
  } else if (ec) {
1323
47
    const EC_GROUP* group = EC_KEY_get0_group(ec.get());
1324
1325
94
    if (!Set<Value>(context,
1326
                    info,
1327
                    env->bits_string(),
1328
94
                    GetECGroup(env, group, ec)) ||
1329

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

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

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

3714
      !Set<Object>(context,
1396
                   info,
1397
                   env->raw_string(),
1398
                   GetRawDERCertificate(env, cert))) {
1399
    return MaybeLocal<Object>();
1400
  }
1401
1402
1238
  return scope.Escape(info);
1403
}
1404
1405
}  // namespace crypto
1406
}  // namespace node