GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_common.cc Lines: 516 674 76.6 %
Date: 2022-11-08 04:21:23 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
4
MaybeLocal<Value> GetSSLOCSPResponse(
93
    Environment* env,
94
    SSL* ssl,
95
    Local<Value> default_value) {
96
  const unsigned char* resp;
97
4
  int len = SSL_get_tlsext_status_ocsp_resp(ssl, &resp);
98
4
  if (resp == nullptr)
99
2
    return default_value;
100
101
  Local<Value> ret;
102
  MaybeLocal<Object> maybe_buffer =
103
2
      Buffer::Copy(env, reinterpret_cast<const char*>(resp), len);
104
105
2
  if (!maybe_buffer.ToLocal(&ret))
106
    return MaybeLocal<Value>();
107
108
2
  return ret;
109
}
110
111
108
bool SetTLSSession(
112
    const SSLPointer& ssl,
113
    const SSLSessionPointer& session) {
114

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

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

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







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

451
  if (cert && !sk_X509_push(peer_certs.get(), cert.release()))
322
    return StackOfX509();
323
1246
  for (int i = 0; i < sk_X509_num(ssl_certs); i++) {
324
795
    X509Pointer cert(X509_dup(sk_X509_value(ssl_certs, i)));
325

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

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

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


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

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

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

26
    if (prefix == nullptr ||
779
12
        (unicode && val_type != V_ASN1_UTF8STRING) ||
780

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

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

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

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


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

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

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

3573
        !Set<Object>(context,
1310
                     info,
1311
                     env->pubkey_string(),
1312
                     GetPubKey(env, rsa))) {
1313
      return MaybeLocal<Object>();
1314
    }
1315
47
  } else if (ec) {
1316
47
    const EC_GROUP* group = EC_KEY_get0_group(ec.get());
1317
1318
94
    if (!Set<Value>(context,
1319
                    info,
1320
                    env->bits_string(),
1321
94
                    GetECGroup(env, group, ec)) ||
1322

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

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

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

3714
      !Set<Object>(context,
1389
                   info,
1390
                   env->raw_string(),
1391
                   GetRawDERCertificate(env, cert))) {
1392
    return MaybeLocal<Object>();
1393
  }
1394
1395
1238
  return scope.Escape(info);
1396
}
1397
1398
}  // namespace crypto
1399
}  // namespace node