GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_common.cc Lines: 519 678 76.5 %
Date: 2022-08-30 04:20:47 Branches: 280 485 57.7 %

Line Branch Exec Source
1
#include "base_object-inl.h"
2
#include "env-inl.h"
3
#include "node_buffer.h"
4
#include "node_crypto.h"
5
#include "crypto/crypto_common.h"
6
#include "node.h"
7
#include "node_internals.h"
8
#include "node_url.h"
9
#include "string_bytes.h"
10
#include "memory_tracker-inl.h"
11
#include "v8.h"
12
13
#include <openssl/ec.h>
14
#include <openssl/ecdh.h>
15
#include <openssl/evp.h>
16
#include <openssl/pem.h>
17
#include <openssl/x509v3.h>
18
#include <openssl/hmac.h>
19
#include <openssl/rand.h>
20
#include <openssl/pkcs12.h>
21
22
#include <string>
23
#include <unordered_map>
24
25
namespace node {
26
27
using v8::Array;
28
using v8::ArrayBuffer;
29
using v8::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 (cert)
327
    sk_X509_push(peer_certs.get(), cert.release());
328
1246
  for (int i = 0; i < sk_X509_num(ssl_certs); i++) {
329
795
    X509Pointer cert(X509_dup(sk_X509_value(ssl_certs, i)));
330

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

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

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


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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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