GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_common.cc Lines: 519 677 76.7 %
Date: 2022-08-05 04:16:08 Branches: 280 485 57.7 %

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

1806
      X509_STORE_CTX_init(store_ctx.get(), store, nullptr, nullptr) == 1 &&
62
903
      X509_STORE_CTX_get1_issuer(&issuer, store_ctx.get(), cert) == 1) {
63
432
    result.reset(issuer);
64
  }
65
903
  return result;
66
}
67
68
void LogSecret(
69
    const SSLPointer& ssl,
70
    const char* name,
71
    const unsigned char* secret,
72
    size_t secretlen) {
73
  auto keylog_cb = SSL_CTX_get_keylog_callback(SSL_get_SSL_CTX(ssl.get()));
74
  unsigned char crandom[32];
75
76
  if (keylog_cb == nullptr ||
77
      SSL_get_client_random(ssl.get(), crandom, 32) != 32) {
78
    return;
79
  }
80
81
  std::string line = name;
82
  line += " " + StringBytes::hex_encode(
83
      reinterpret_cast<const char*>(crandom), 32);
84
  line += " " + StringBytes::hex_encode(
85
      reinterpret_cast<const char*>(secret), secretlen);
86
  keylog_cb(ssl.get(), line.c_str());
87
}
88
89
40
bool SetALPN(const SSLPointer& ssl, std::string_view alpn) {
90
40
  return SSL_set_alpn_protos(ssl.get(),
91
40
                             reinterpret_cast<const uint8_t*>(alpn.data()),
92
80
                             alpn.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
108
bool SetTLSSession(
115
    const SSLPointer& ssl,
116
    const SSLSessionPointer& session) {
117

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

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

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







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

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

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

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


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

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

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

26
    if (prefix == nullptr ||
781
12
        (unicode && val_type != V_ASN1_UTF8STRING) ||
782

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

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

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

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


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

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

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

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

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

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

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

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