GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_common.cc Lines: 533 703 75.8 %
Date: 2022-01-22 04:14:05 Branches: 282 485 58.1 %

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

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

96
  return session != nullptr && SSL_set_session(ssl.get(), session.get()) == 1;
126
}
127
128
96
SSLSessionPointer GetTLSSession(Local<Value> val) {
129
96
  if (!val->IsArrayBufferView())
130
    return SSLSessionPointer();
131
96
  ArrayBufferViewContents<unsigned char> sbuf(val.As<ArrayBufferView>());
132
96
  return GetTLSSession(sbuf.data(), sbuf.length());
133
}
134
135
96
SSLSessionPointer GetTLSSession(const unsigned char* buf, size_t length) {
136
96
  return SSLSessionPointer(d2i_SSL_SESSION(nullptr, &buf, length));
137
}
138
139
948
long VerifyPeerCertificate(  // NOLINT(runtime/int)
140
    const SSLPointer& ssl,
141
    long def) {  // NOLINT(runtime/int)
142
948
  long err = def;  // NOLINT(runtime/int)
143
948
  if (X509* peer_cert = SSL_get_peer_certificate(ssl.get())) {
144
922
    X509_free(peer_cert);
145
922
    err = SSL_get_verify_result(ssl.get());
146
  } else {
147
26
    const SSL_CIPHER* curr_cipher = SSL_get_current_cipher(ssl.get());
148
26
    const SSL_SESSION* sess = SSL_get_session(ssl.get());
149
    // Allow no-cert for PSK authentication in TLS1.2 and lower.
150
    // In TLS1.3 check that session was reused because TLS1.3 PSK
151
    // looks like session resumption.
152

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

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







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

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

124
        if (static_cast<unsigned char>(c) < ' ' || c == '\x7f') {
646
4
          return false;
647
        }
648
      } else {
649
        // Check if the char is a control character or non-ASCII character. Note
650
        // that char may or may not be a signed type. Regardless, non-ASCII
651
        // values will always be outside of this range.
652

4588
        if (c < ' ' || c > '~') {
653
11
          return false;
654
        }
655
      }
656
    }
657
  }
658
177
  return true;
659
}
660
661
217
static inline void PrintAltName(const BIOPointer& out, const char* name,
662
                                size_t length, bool utf8,
663
                                const char* safe_prefix) {
664
217
  if (IsSafeAltName(name, length, utf8)) {
665
    // For backward-compatibility, append "safe" names without any
666
    // modifications.
667
177
    if (safe_prefix != nullptr) {
668
8
      BIO_printf(out.get(), "%s:", safe_prefix);
669
    }
670
177
    BIO_write(out.get(), name, length);
671
  } else {
672
    // If a name is not "safe", we cannot embed it without special
673
    // encoding. This does not usually happen, but we don't want to hide
674
    // it from the user either. We use JSON compatible escaping here.
675
40
    BIO_write(out.get(), "\"", 1);
676
40
    if (safe_prefix != nullptr) {
677
8
      BIO_printf(out.get(), "%s:", safe_prefix);
678
    }
679
1411
    for (size_t j = 0; j < length; j++) {
680
1371
      char c = static_cast<char>(name[j]);
681
1371
      if (c == '\\') {
682
16
        BIO_write(out.get(), "\\\\", 2);
683
1355
      } else if (c == '"') {
684
4
        BIO_write(out.get(), "\\\"", 2);
685


1351
      } else if ((c >= ' ' && c != ',' && c <= '~') || (utf8 && (c & 0x80))) {
686
        // Note that the above condition explicitly excludes commas, which means
687
        // that those are encoded as Unicode escape sequences in the "else"
688
        // block. That is not strictly necessary, and Node.js itself would parse
689
        // it correctly either way. We only do this to account for third-party
690
        // code that might be splitting the string at commas (as Node.js itself
691
        // used to do).
692
1319
        BIO_write(out.get(), &c, 1);
693
      } else {
694
        // Control character or non-ASCII character. We treat everything as
695
        // Latin-1, which corresponds to the first 255 Unicode code points.
696
32
        const char hex[] = "0123456789abcdef";
697
32
        char u[] = { '\\', 'u', '0', '0', hex[(c & 0xf0) >> 4], hex[c & 0x0f] };
698
32
        BIO_write(out.get(), u, sizeof(u));
699
      }
700
    }
701
40
    BIO_write(out.get(), "\"", 1);
702
  }
703
217
}
704
705
193
static inline void PrintLatin1AltName(const BIOPointer& out,
706
                                      const ASN1_IA5STRING* name,
707
                                      const char* safe_prefix = nullptr) {
708
193
  PrintAltName(out, reinterpret_cast<const char*>(name->data), name->length,
709
               false, safe_prefix);
710
193
}
711
712
10
static inline void PrintUtf8AltName(const BIOPointer& out,
713
                                    const ASN1_UTF8STRING* name,
714
                                    const char* safe_prefix = nullptr) {
715
10
  PrintAltName(out, reinterpret_cast<const char*>(name->data), name->length,
716
               true, safe_prefix);
717
10
}
718
719
// This function currently emulates the behavior of i2v_GENERAL_NAME in a safer
720
// and less ambiguous way.
721
// TODO(tniessen): gradually improve the format in the next major version(s)
722
244
static bool PrintGeneralName(const BIOPointer& out, const GENERAL_NAME* gen) {
723
244
  if (gen->type == GEN_DNS) {
724
24
    ASN1_IA5STRING* name = gen->d.dNSName;
725
24
    BIO_write(out.get(), "DNS:", 4);
726
    // Note that the preferred name syntax (see RFCs 5280 and 1034) with
727
    // wildcards is a subset of what we consider "safe", so spec-compliant DNS
728
    // names will never need to be escaped.
729
24
    PrintLatin1AltName(out, name);
730
220
  } else if (gen->type == GEN_EMAIL) {
731
4
    ASN1_IA5STRING* name = gen->d.rfc822Name;
732
4
    BIO_write(out.get(), "email:", 6);
733
4
    PrintLatin1AltName(out, name);
734
216
  } else if (gen->type == GEN_URI) {
735
159
    ASN1_IA5STRING* name = gen->d.uniformResourceIdentifier;
736
159
    BIO_write(out.get(), "URI:", 4);
737
    // The set of "safe" names was designed to include just about any URI,
738
    // with a few exceptions, most notably URIs that contains commas (see
739
    // RFC 2396). In other words, most legitimate URIs will not require
740
    // escaping.
741
159
    PrintLatin1AltName(out, name);
742
57
  } else if (gen->type == GEN_DIRNAME) {
743
    // For backward compatibility, use X509_NAME_oneline to print the
744
    // X509_NAME object. The format is non standard and should be avoided
745
    // elsewhere, but conveniently, the function produces ASCII and the output
746
    // is unlikely to contains commas or other characters that would require
747
    // escaping. With that in mind, note that it SHOULD NOT produce ASCII
748
    // output since an RFC5280 AttributeValue may be a UTF8String.
749
    // TODO(tniessen): switch to RFC2253 rules in a major release
750
14
    BIO_printf(out.get(), "DirName:");
751
    char oline[256];
752
14
    if (X509_NAME_oneline(gen->d.dirn, oline, sizeof(oline)) != nullptr) {
753
14
      PrintAltName(out, oline, strlen(oline), false, nullptr);
754
    } else {
755
      return false;
756
    }
757
43
  } else if (gen->type == GEN_IPADD) {
758
17
    BIO_printf(out.get(), "IP Address:");
759
17
    const ASN1_OCTET_STRING* ip = gen->d.ip;
760
17
    const unsigned char* b = ip->data;
761
17
    if (ip->length == 4) {
762
11
      BIO_printf(out.get(), "%d.%d.%d.%d", b[0], b[1], b[2], b[3]);
763
6
    } else if (ip->length == 16) {
764
18
      for (unsigned int j = 0; j < 8; j++) {
765
16
        uint16_t pair = (b[2 * j] << 8) | b[2 * j + 1];
766
16
        BIO_printf(out.get(), (j == 0) ? "%X" : ":%X", pair);
767
      }
768
    } else {
769
#if OPENSSL_VERSION_MAJOR >= 3
770
4
      BIO_printf(out.get(), "<invalid length=%d>", ip->length);
771
#else
772
      BIO_printf(out.get(), "<invalid>");
773
#endif
774
    }
775
26
  } else if (gen->type == GEN_RID) {
776
    // Unlike OpenSSL's default implementation, never print the OID as text and
777
    // instead always print its numeric representation.
778
    char oline[256];
779
4
    OBJ_obj2txt(oline, sizeof(oline), gen->d.rid, true);
780
4
    BIO_printf(out.get(), "Registered ID:%s", oline);
781
22
  } else if (gen->type == GEN_OTHERNAME) {
782
    // TODO(tniessen): the format that is used here is based on OpenSSL's
783
    // implementation of i2v_GENERAL_NAME (as of OpenSSL 3.0.1), mostly for
784
    // backward compatibility. It is somewhat awkward, especially when passed to
785
    // translatePeerCertificate, and should be changed in the future, probably
786
    // to the format used by GENERAL_NAME_print (in a major release).
787
22
    bool unicode = true;
788
22
    const char* prefix = nullptr;
789
    // OpenSSL 1.1.1 does not support othername in i2v_GENERAL_NAME and may not
790
    // define these NIDs.
791
#if OPENSSL_VERSION_MAJOR >= 3
792
22
    int nid = OBJ_obj2nid(gen->d.otherName->type_id);
793

22
    switch (nid) {
794
      case NID_id_on_SmtpUTF8Mailbox:
795
        prefix = " SmtpUTF8Mailbox:";
796
        break;
797
10
      case NID_XmppAddr:
798
10
        prefix = " XmppAddr:";
799
10
        break;
800
8
      case NID_SRVName:
801
8
        prefix = " SRVName:";
802
8
        unicode = false;
803
8
        break;
804
      case NID_ms_upn:
805
        prefix = " UPN:";
806
        break;
807
      case NID_NAIRealm:
808
        prefix = " NAIRealm:";
809
        break;
810
    }
811
#endif  // OPENSSL_VERSION_MAJOR >= 3
812
22
    int val_type = gen->d.otherName->value->type;
813

22
    if (prefix == nullptr ||
814
10
        (unicode && val_type != V_ASN1_UTF8STRING) ||
815

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

159
      !Set<Value>(env->context(),
1126
                  info,
1127
                  env->version_string(),
1128
                  GetCipherVersion(env, ssl))) {
1129
    return MaybeLocal<Object>();
1130
  }
1131
1132
53
  return scope.Escape(info);
1133
}
1134
1135
875
MaybeLocal<Object> GetEphemeralKey(Environment* env, const SSLPointer& ssl) {
1136
875
  CHECK_EQ(SSL_is_server(ssl.get()), 0);
1137
  EVP_PKEY* raw_key;
1138
1139
875
  EscapableHandleScope scope(env->isolate());
1140
875
  Local<Object> info = Object::New(env->isolate());
1141
875
  if (!SSL_get_server_tmp_key(ssl.get(), &raw_key))
1142
30
    return scope.Escape(info);
1143
1144
845
  Local<Context> context = env->context();
1145
1690
  crypto::EVPKeyPointer key(raw_key);
1146
1147
845
  int kid = EVP_PKEY_id(key.get());
1148
845
  int bits = EVP_PKEY_bits(key.get());
1149
845
  switch (kid) {
1150
7
    case EVP_PKEY_DH:
1151
28
      if (!Set<String>(context, info, env->type_string(), env->dh_string()) ||
1152

28
          !Set<Integer>(context,
1153
               info,
1154
               env->size_string(),
1155
               Integer::New(env->isolate(), bits))) {
1156
        return MaybeLocal<Object>();
1157
      }
1158
7
      break;
1159
838
    case EVP_PKEY_EC:
1160
    case EVP_PKEY_X25519:
1161
    case EVP_PKEY_X448:
1162
      {
1163
        const char* curve_name;
1164
838
        if (kid == EVP_PKEY_EC) {
1165
10
          ECKeyPointer ec(EVP_PKEY_get1_EC_KEY(key.get()));
1166
5
          int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec.get()));
1167
5
          curve_name = OBJ_nid2sn(nid);
1168
        } else {
1169
833
          curve_name = OBJ_nid2sn(kid);
1170
        }
1171
2514
        if (!Set<String>(context,
1172
                         info,
1173
                         env->type_string(),
1174
838
                         env->ecdh_string()) ||
1175
2514
            !Set<String>(context,
1176
                info,
1177
                env->name_string(),
1178
1676
                OneByteString(env->isolate(), curve_name)) ||
1179

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


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

1342
      !Set<Object>(env->context(),
1284
           issuer_chain,
1285
           env->issuercert_string(),
1286
           issuer_chain)) {
1287
    return MaybeLocal<Value>();
1288
  }
1289
1290
448
  return result;
1291
}
1292
1293
1215
MaybeLocal<Object> X509ToObject(
1294
    Environment* env,
1295
    X509* cert,
1296
    bool names_as_string) {
1297
1215
  EscapableHandleScope scope(env->isolate());
1298
1215
  Local<Context> context = env->context();
1299
1215
  Local<Object> info = Object::New(env->isolate());
1300
1301
2430
  BIOPointer bio(BIO_new(BIO_s_mem()));
1302
1303
1215
  if (names_as_string) {
1304
    // TODO(tniessen): this branch should not have to exist. It is only here
1305
    // because toLegacyObject() does not actually return a legacy object, and
1306
    // instead represents subject and issuer as strings.
1307
2
    if (!Set<Value>(context,
1308
                    info,
1309
                    env->subject_string(),
1310
2
                    GetSubject(env, bio, cert)) ||
1311

3
        !Set<Value>(context,
1312
                    info,
1313
                    env->issuer_string(),
1314
                    GetIssuerString(env, bio, cert))) {
1315
      return MaybeLocal<Object>();
1316
    }
1317
  } else {
1318
2428
    if (!Set<Value>(context,
1319
                    info,
1320
                    env->subject_string(),
1321
2428
                    GetX509NameObject<X509_get_subject_name>(env, cert)) ||
1322

3642
        !Set<Value>(context,
1323
                    info,
1324
                    env->issuer_string(),
1325
                    GetX509NameObject<X509_get_issuer_name>(env, cert))) {
1326
      return MaybeLocal<Object>();
1327
    }
1328
  }
1329
1330
2430
  if (!Set<Value>(context,
1331
                  info,
1332
                  env->subjectaltname_string(),
1333
2430
                  GetSubjectAltNameString(env, bio, cert)) ||
1334

3645
      !Set<Value>(context,
1335
                  info,
1336
                  env->infoaccess_string(),
1337
                  GetInfoAccessString(env, bio, cert))) {
1338
    return MaybeLocal<Object>();
1339
  }
1340
1341
2430
  EVPKeyPointer pkey(X509_get_pubkey(cert));
1342
1215
  RSAPointer rsa;
1343
1215
  ECPointer ec;
1344
1215
  if (pkey) {
1345
1215
    switch (EVP_PKEY_id(pkey.get())) {
1346
1168
      case EVP_PKEY_RSA:
1347
1168
        rsa.reset(EVP_PKEY_get1_RSA(pkey.get()));
1348
1168
        break;
1349
47
      case EVP_PKEY_EC:
1350
47
        ec.reset(EVP_PKEY_get1_EC_KEY(pkey.get()));
1351
47
        break;
1352
    }
1353
  }
1354
1355
1215
  if (rsa) {
1356
    const BIGNUM* n;
1357
    const BIGNUM* e;
1358
1168
    RSA_get0_key(rsa.get(), &n, &e, nullptr);
1359
2336
    if (!Set<Value>(context,
1360
                    info,
1361
                    env->modulus_string(),
1362
1168
                    GetModulusString(env, bio, n)) ||
1363
3504
        !Set<Value>(context, info, env->bits_string(), GetBits(env, n)) ||
1364
2336
        !Set<Value>(context,
1365
                    info,
1366
                    env->exponent_string(),
1367
2336
                    GetExponentString(env, bio, e)) ||
1368

3504
        !Set<Object>(context,
1369
                     info,
1370
                     env->pubkey_string(),
1371
                     GetPubKey(env, rsa))) {
1372
      return MaybeLocal<Object>();
1373
    }
1374
47
  } else if (ec) {
1375
47
    const EC_GROUP* group = EC_KEY_get0_group(ec.get());
1376
1377
94
    if (!Set<Value>(context,
1378
                    info,
1379
                    env->bits_string(),
1380
94
                    GetECGroup(env, group, ec)) ||
1381

141
        !Set<Value>(context,
1382
                    info,
1383
                    env->pubkey_string(),
1384
                    GetECPubKey(env, group, ec))) {
1385
      return MaybeLocal<Object>();
1386
    }
1387
1388
47
    const int nid = EC_GROUP_get_curve_name(group);
1389
47
    if (nid != 0) {
1390
      // Curve is well-known, get its OID and NIST nick-name (if it has one).
1391
1392
94
      if (!Set<Value>(context,
1393
                      info,
1394
                      env->asn1curve_string(),
1395
94
                      GetCurveASN1Name(env, nid)) ||
1396

141
          !Set<Value>(context,
1397
                      info,
1398
                      env->nistcurve_string(),
1399
                      GetCurveNistName(env, nid))) {
1400
        return MaybeLocal<Object>();
1401
      }
1402
    } else {
1403
      // Unnamed curves can be described by their mathematical properties,
1404
      // but aren't used much (at all?) with X.509/TLS. Support later if needed.
1405
    }
1406
  }
1407
1408
  // pkey, rsa, and ec pointers are no longer needed.
1409
1215
  pkey.reset();
1410
1215
  rsa.reset();
1411
1215
  ec.reset();
1412
1413
2430
  if (!Set<Value>(context,
1414
                  info,
1415
                  env->valid_from_string(),
1416
2430
                  GetValidFrom(env, cert, bio)) ||
1417

3645
      !Set<Value>(context,
1418
                  info,
1419
                  env->valid_to_string(),
1420
                  GetValidTo(env, cert, bio))) {
1421
    return MaybeLocal<Object>();
1422
  }
1423
1424
  // bio is no longer needed
1425
1215
  bio.reset();
1426
1427
2430
  if (!Set<Value>(context,
1428
                  info,
1429
                  env->fingerprint_string(),
1430
1215
                  GetFingerprintDigest(env, EVP_sha1(), cert)) ||
1431
2430
      !Set<Value>(context,
1432
                  info,
1433
                  env->fingerprint256_string(),
1434
1215
                  GetFingerprintDigest(env, EVP_sha256(), cert)) ||
1435
2430
      !Set<Value>(context,
1436
                  info,
1437
                  env->fingerprint512_string(),
1438
1215
                  GetFingerprintDigest(env, EVP_sha512(), cert)) ||
1439
2430
      !Set<Value>(context,
1440
                  info,
1441
                  env->ext_key_usage_string(),
1442
1215
                  GetKeyUsage(env, cert)) ||
1443
2430
      !Set<Value>(context,
1444
                  info,
1445
                  env->serial_number_string(),
1446
2430
                  GetSerialNumber(env, cert)) ||
1447

3645
      !Set<Object>(context,
1448
                   info,
1449
                   env->raw_string(),
1450
                   GetRawDERCertificate(env, cert))) {
1451
    return MaybeLocal<Object>();
1452
  }
1453
1454
1215
  return scope.Escape(info);
1455
}
1456
1457
}  // namespace crypto
1458
}  // namespace node