GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_common.cc Lines: 532 697 76.3 %
Date: 2022-03-01 04:14:51 Branches: 285 495 57.6 %

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 kX509NameFlagsMultiline =
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
static constexpr int kX509NameFlagsRFC2253WithinUtf8JSON =
52
    XN_FLAG_RFC2253 &
53
    ~ASN1_STRFLGS_ESC_MSB &
54
    ~ASN1_STRFLGS_ESC_CTRL;
55
56
896
bool SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) {
57
896
  X509_STORE* store = SSL_CTX_get_cert_store(ctx);
58
  DeleteFnPtr<X509_STORE_CTX, X509_STORE_CTX_free> store_ctx(
59
896
      X509_STORE_CTX_new());
60
1792
  return store_ctx.get() != nullptr &&
61

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

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

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

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







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

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

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

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


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

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

22
    switch (nid) {
784
      case NID_id_on_SmtpUTF8Mailbox:
785
        prefix = " SmtpUTF8Mailbox:";
786
        break;
787
10
      case NID_XmppAddr:
788
10
        prefix = " XmppAddr:";
789
10
        break;
790
8
      case NID_SRVName:
791
8
        prefix = " SRVName:";
792
8
        unicode = false;
793
8
        break;
794
      case NID_ms_upn:
795
        prefix = " UPN:";
796
        break;
797
      case NID_NAIRealm:
798
        prefix = " NAIRealm:";
799
        break;
800
    }
801
#endif  // OPENSSL_VERSION_MAJOR >= 3
802
22
    int val_type = gen->d.otherName->value->type;
803

22
    if (prefix == nullptr ||
804
10
        (unicode && val_type != V_ASN1_UTF8STRING) ||
805

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

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

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

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


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

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

3
        !Set<Value>(context,
1307
                    info,
1308
                    env->issuer_string(),
1309
                    GetIssuerString(env, bio, cert))) {
1310
      return MaybeLocal<Object>();
1311
    }
1312
  } else {
1313
2428
    if (!Set<Value>(context,
1314
                    info,
1315
                    env->subject_string(),
1316
2428
                    GetX509NameObject<X509_get_subject_name>(env, cert)) ||
1317

3642
        !Set<Value>(context,
1318
                    info,
1319
                    env->issuer_string(),
1320
                    GetX509NameObject<X509_get_issuer_name>(env, cert))) {
1321
      return MaybeLocal<Object>();
1322
    }
1323
  }
1324
1325
2430
  if (!Set<Value>(context,
1326
                  info,
1327
                  env->subjectaltname_string(),
1328
2430
                  GetSubjectAltNameString(env, bio, cert)) ||
1329

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

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

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

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

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

3645
      !Set<Object>(context,
1443
                   info,
1444
                   env->raw_string(),
1445
                   GetRawDERCertificate(env, cert))) {
1446
    return MaybeLocal<Object>();
1447
  }
1448
1449
1215
  return scope.Escape(info);
1450
}
1451
1452
}  // namespace crypto
1453
}  // namespace node