GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/crypto/crypto_common.cc Lines: 276 549 50.3 %
Date: 2021-02-19 04:08:54 Branches: 124 387 32.0 %

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::ArrayBufferView;
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 X509_NAME_FLAGS =
43
    ASN1_STRFLGS_ESC_CTRL |
44
    ASN1_STRFLGS_UTF8_CONVERT |
45
    XN_FLAG_SEP_MULTILINE |
46
    XN_FLAG_FN_SN;
47
48
2
int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) {
49
2
  X509_STORE* store = SSL_CTX_get_cert_store(ctx);
50
  DeleteFnPtr<X509_STORE_CTX, X509_STORE_CTX_free> store_ctx(
51
4
      X509_STORE_CTX_new());
52
4
  return store_ctx.get() != nullptr &&
53

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

22
  return session != nullptr && SSL_set_session(ssl.get(), session.get()) == 1;
123
}
124
125
22
SSLSessionPointer GetTLSSession(Local<Value> val) {
126
22
  if (!val->IsArrayBufferView())
127
    return SSLSessionPointer();
128
22
  ArrayBufferViewContents<unsigned char> sbuf(val.As<ArrayBufferView>());
129
22
  return GetTLSSession(sbuf.data(), sbuf.length());
130
}
131
132
22
SSLSessionPointer GetTLSSession(const unsigned char* buf, size_t length) {
133
22
  return SSLSessionPointer(d2i_SSL_SESSION(nullptr, &buf, length));
134
}
135
136
std::unordered_multimap<std::string, std::string>
137
GetCertificateAltNames(X509* cert) {
138
  std::unordered_multimap<std::string, std::string> map;
139
  BIOPointer bio(BIO_new(BIO_s_mem()));
140
  BUF_MEM* mem;
141
  int idx = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
142
  if (idx < 0)  // There is no subject alt name
143
    return map;
144
145
  X509_EXTENSION* ext = X509_get_ext(cert, idx);
146
  CHECK_NOT_NULL(ext);
147
  const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
148
  CHECK_EQ(method, X509V3_EXT_get_nid(NID_subject_alt_name));
149
150
  GENERAL_NAMES* names = static_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(ext));
151
  if (names == nullptr)  // There are no names
152
    return map;
153
154
  for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) {
155
    USE(BIO_reset(bio.get()));
156
    GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);
157
    if (gen->type == GEN_DNS) {
158
      ASN1_IA5STRING* name = gen->d.dNSName;
159
      BIO_write(bio.get(), name->data, name->length);
160
      BIO_get_mem_ptr(bio.get(), &mem);
161
      map.emplace("dns", std::string(mem->data, mem->length));
162
    } else {
163
      STACK_OF(CONF_VALUE)* nval = i2v_GENERAL_NAME(
164
          const_cast<X509V3_EXT_METHOD*>(method), gen, nullptr);
165
      if (nval == nullptr)
166
        continue;
167
      X509V3_EXT_val_prn(bio.get(), nval, 0, 0);
168
      sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
169
      BIO_get_mem_ptr(bio.get(), &mem);
170
      std::string value(mem->data, mem->length);
171
      if (value.compare(0, 11, "IP Address:") == 0) {
172
        map.emplace("ip", value.substr(11));
173
      } else if (value.compare(0, 4, "URI:") == 0) {
174
        url::URL url(value.substr(4));
175
        if (url.flags() & url::URL_FLAGS_CANNOT_BE_BASE ||
176
            url.flags() & url::URL_FLAGS_FAILED) {
177
          continue;  // Skip this one
178
        }
179
        map.emplace("uri", url.host());
180
      }
181
    }
182
  }
183
  sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
184
  return map;
185
}
186
187
std::string GetCertificateCN(X509* cert) {
188
  X509_NAME* subject = X509_get_subject_name(cert);
189
  if (subject != nullptr) {
190
    int nid = OBJ_txt2nid("CN");
191
    int idx = X509_NAME_get_index_by_NID(subject, nid, -1);
192
    if (idx != -1) {
193
      X509_NAME_ENTRY* cn = X509_NAME_get_entry(subject, idx);
194
      if (cn != nullptr) {
195
        ASN1_STRING* cn_str = X509_NAME_ENTRY_get_data(cn);
196
        if (cn_str != nullptr) {
197
          return std::string(reinterpret_cast<const char*>(
198
              ASN1_STRING_get0_data(cn_str)));
199
        }
200
      }
201
    }
202
  }
203
  return std::string();
204
}
205
206
13
long VerifyPeerCertificate(  // NOLINT(runtime/int)
207
    const SSLPointer& ssl,
208
    long def) {  // NOLINT(runtime/int)
209
13
  long err = def;  // NOLINT(runtime/int)
210
13
  if (X509* peer_cert = SSL_get_peer_certificate(ssl.get())) {
211
13
    X509_free(peer_cert);
212
13
    err = SSL_get_verify_result(ssl.get());
213
  } else {
214
    const SSL_CIPHER* curr_cipher = SSL_get_current_cipher(ssl.get());
215
    const SSL_SESSION* sess = SSL_get_session(ssl.get());
216
    // Allow no-cert for PSK authentication in TLS1.2 and lower.
217
    // In TLS1.3 check that session was reused because TLS1.3 PSK
218
    // looks like session resumption.
219
    if (SSL_CIPHER_get_auth_nid(curr_cipher) == NID_auth_psk ||
220
        (SSL_SESSION_get_protocol_version(sess) == TLS1_3_VERSION &&
221
         SSL_session_reused(ssl.get()))) {
222
      return X509_V_OK;
223
    }
224
  }
225
13
  return err;
226
}
227
228
int UseSNIContext(const SSLPointer& ssl, BaseObjectPtr<SecureContext> context) {
229
  SSL_CTX* ctx = context->ctx_.get();
230
  X509* x509 = SSL_CTX_get0_certificate(ctx);
231
  EVP_PKEY* pkey = SSL_CTX_get0_privatekey(ctx);
232
  STACK_OF(X509)* chain;
233
234
  int err = SSL_CTX_get0_chain_certs(ctx, &chain);
235
  if (err == 1) err = SSL_use_certificate(ssl.get(), x509);
236
  if (err == 1) err = SSL_use_PrivateKey(ssl.get(), pkey);
237
  if (err == 1 && chain != nullptr) err = SSL_set1_chain(ssl.get(), chain);
238
  return err;
239
}
240
241
const char* GetClientHelloALPN(const SSLPointer& ssl) {
242
  const unsigned char* buf;
243
  size_t len;
244
  size_t rem;
245
246
  if (!SSL_client_hello_get0_ext(
247
          ssl.get(),
248
          TLSEXT_TYPE_application_layer_protocol_negotiation,
249
          &buf,
250
          &rem) ||
251
      rem < 2) {
252
    return nullptr;
253
  }
254
255
  len = (buf[0] << 8) | buf[1];
256
  if (len + 2 != rem) return nullptr;
257
  return reinterpret_cast<const char*>(buf + 3);
258
}
259
260
const char* GetClientHelloServerName(const SSLPointer& ssl) {
261
  const unsigned char* buf;
262
  size_t len;
263
  size_t rem;
264
265
  if (!SSL_client_hello_get0_ext(
266
          ssl.get(),
267
          TLSEXT_TYPE_server_name,
268
          &buf,
269
          &rem) || rem <= 2) {
270
    return nullptr;
271
  }
272
273
  len = (*buf << 8) | *(buf + 1);
274
  if (len + 2 != rem)
275
    return nullptr;
276
  rem = len;
277
278
  if (rem == 0 || *(buf + 2) != TLSEXT_NAMETYPE_host_name) return nullptr;
279
  rem--;
280
  if (rem <= 2)
281
    return nullptr;
282
  len = (*(buf + 3) << 8) | *(buf + 4);
283
  if (len + 2 > rem)
284
    return nullptr;
285
  return reinterpret_cast<const char*>(buf + 5);
286
}
287
288
const char* GetServerName(SSL* ssl) {
289
  return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
290
}
291
292
bool SetGroups(SecureContext* sc, const char* groups) {
293
  return SSL_CTX_set1_groups_list(**sc, groups) == 1;
294
}
295
296
const char* X509ErrorCode(long err) {  // NOLINT(runtime/int)
297
  const char* code = "UNSPECIFIED";
298
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
299
  switch (err) {
300
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
301
    CASE_X509_ERR(UNABLE_TO_GET_CRL)
302
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
303
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
304
    CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
305
    CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
306
    CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
307
    CASE_X509_ERR(CERT_NOT_YET_VALID)
308
    CASE_X509_ERR(CERT_HAS_EXPIRED)
309
    CASE_X509_ERR(CRL_NOT_YET_VALID)
310
    CASE_X509_ERR(CRL_HAS_EXPIRED)
311
    CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
312
    CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
313
    CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
314
    CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
315
    CASE_X509_ERR(OUT_OF_MEM)
316
    CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
317
    CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
318
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
319
    CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
320
    CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
321
    CASE_X509_ERR(CERT_REVOKED)
322
    CASE_X509_ERR(INVALID_CA)
323
    CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
324
    CASE_X509_ERR(INVALID_PURPOSE)
325
    CASE_X509_ERR(CERT_UNTRUSTED)
326
    CASE_X509_ERR(CERT_REJECTED)
327
    CASE_X509_ERR(HOSTNAME_MISMATCH)
328
  }
329
#undef CASE_X509_ERR
330
  return code;
331
}
332
333
MaybeLocal<Value> GetValidationErrorReason(Environment* env, int err) {
334
  if (err == 0)
335
    return Undefined(env->isolate());
336
  const char* reason = X509_verify_cert_error_string(err);
337
  return OneByteString(env->isolate(), reason);
338
}
339
340
MaybeLocal<Value> GetValidationErrorCode(Environment* env, int err) {
341
  if (err == 0)
342
    return Undefined(env->isolate());
343
  return OneByteString(env->isolate(), X509ErrorCode(err));
344
}
345
346
MaybeLocal<Value> GetCert(Environment* env, const SSLPointer& ssl) {
347
  ClearErrorOnReturn clear_error_on_return;
348
  X509* cert = SSL_get_certificate(ssl.get());
349
  if (cert == nullptr)
350
    return Undefined(env->isolate());
351
352
  MaybeLocal<Object> maybe_cert = X509ToObject(env, cert);
353
  return maybe_cert.FromMaybe<Value>(Local<Value>());
354
}
355
356
44
Local<Value> ToV8Value(Environment* env, const BIOPointer& bio) {
357
  BUF_MEM* mem;
358
44
  BIO_get_mem_ptr(bio.get(), &mem);
359
  MaybeLocal<String> ret =
360
      String::NewFromUtf8(
361
          env->isolate(),
362
44
          mem->data,
363
          NewStringType::kNormal,
364
88
          mem->length);
365
44
  USE(BIO_reset(bio.get()));
366
44
  return ret.FromMaybe(Local<Value>());
367
}
368
369
namespace {
370
template <typename T>
371
134
bool Set(
372
    Local<Context> context,
373
    Local<Object> target,
374
    Local<Value> name,
375
    MaybeLocal<T> maybe_value) {
376
  Local<Value> value;
377


134
  if (!maybe_value.ToLocal(&value))
378
    return false;
379
380
  // Undefined is ignored, but still considered successful
381


268
  if (value->IsUndefined())
382
12
    return true;
383
384
244
  return !target->Set(context, name, value).IsNothing();
385
}
386
387
MaybeLocal<Value> GetCipherValue(Environment* env,
388
    const SSL_CIPHER* cipher,
389
    const char* (*getstr)(const SSL_CIPHER* cipher)) {
390
  if (cipher == nullptr)
391
    return Undefined(env->isolate());
392
393
  return OneByteString(env->isolate(), getstr(cipher));
394
}
395
396
MaybeLocal<Value> GetCipherName(Environment* env, const SSL_CIPHER* cipher) {
397
  return GetCipherValue(env, cipher, SSL_CIPHER_get_name);
398
}
399
400
MaybeLocal<Value> GetCipherStandardName(
401
    Environment* env,
402
    const SSL_CIPHER* cipher) {
403
  return GetCipherValue(env, cipher, SSL_CIPHER_standard_name);
404
}
405
406
MaybeLocal<Value> GetCipherVersion(Environment* env, const SSL_CIPHER* cipher) {
407
  return GetCipherValue(env, cipher, SSL_CIPHER_get_version);
408
}
409
410
2
StackOfX509 CloneSSLCerts(X509Pointer&& cert,
411
                          const STACK_OF(X509)* const ssl_certs) {
412
4
  StackOfX509 peer_certs(sk_X509_new(nullptr));
413
2
  if (cert)
414
    sk_X509_push(peer_certs.get(), cert.release());
415
8
  for (int i = 0; i < sk_X509_num(ssl_certs); i++) {
416
12
    X509Pointer cert(X509_dup(sk_X509_value(ssl_certs, i)));
417

6
    if (!cert || !sk_X509_push(peer_certs.get(), cert.get()))
418
      return StackOfX509();
419
    // `cert` is now managed by the stack.
420
6
    cert.release();
421
  }
422
2
  return peer_certs;
423
}
424
425
2
MaybeLocal<Object> AddIssuerChainToObject(
426
    X509Pointer* cert,
427
    Local<Object> object,
428
    StackOfX509&& peer_certs,
429
    Environment* const env) {
430
2
  Local<Context> context = env->isolate()->GetCurrentContext();
431
2
  cert->reset(sk_X509_delete(peer_certs.get(), 0));
432
  for (;;) {
433
    int i;
434
4
    for (i = 0; i < sk_X509_num(peer_certs.get()); i++) {
435
4
      X509* ca = sk_X509_value(peer_certs.get(), i);
436
4
      if (X509_check_issued(ca, cert->get()) != X509_V_OK)
437
        continue;
438
439
      Local<Object> ca_info;
440
4
      MaybeLocal<Object> maybe_ca_info = X509ToObject(env, ca);
441
4
      if (!maybe_ca_info.ToLocal(&ca_info))
442
        return MaybeLocal<Object>();
443
444
8
      if (!Set<Object>(context, object, env->issuercert_string(), ca_info))
445
        return MaybeLocal<Object>();
446
4
      object = ca_info;
447
448
      // NOTE: Intentionally freeing cert that is not used anymore.
449
      // Delete cert and continue aggregating issuers.
450
4
      cert->reset(sk_X509_delete(peer_certs.get(), i));
451
4
      break;
452
    }
453
454
    // Issuer not found, break out of the loop.
455
4
    if (i == sk_X509_num(peer_certs.get()))
456
2
      break;
457
2
  }
458
2
  return MaybeLocal<Object>(object);
459
}
460
461
2
MaybeLocal<Object> GetLastIssuedCert(
462
    X509Pointer* cert,
463
    const SSLPointer& ssl,
464
    Local<Object> issuer_chain,
465
    Environment* const env) {
466
2
  Local<Context> context = env->isolate()->GetCurrentContext();
467
6
  while (X509_check_issued(cert->get(), cert->get()) != X509_V_OK) {
468
    X509* ca;
469
2
    if (SSL_CTX_get_issuer(SSL_get_SSL_CTX(ssl.get()), cert->get(), &ca) <= 0)
470
      break;
471
472
    Local<Object> ca_info;
473
2
    MaybeLocal<Object> maybe_ca_info = X509ToObject(env, ca);
474
2
    if (!maybe_ca_info.ToLocal(&ca_info))
475
      return MaybeLocal<Object>();
476
477
4
    if (!Set<Object>(context, issuer_chain, env->issuercert_string(), ca_info))
478
      return MaybeLocal<Object>();
479
2
    issuer_chain = ca_info;
480
481
    // Delete previous cert and continue aggregating issuers.
482
2
    cert->reset(ca);
483
  }
484
2
  return MaybeLocal<Object>(issuer_chain);
485
}
486
487
16
void AddFingerprintDigest(
488
    const unsigned char* md,
489
    unsigned int md_size,
490
    char (*fingerprint)[3 * EVP_MAX_MD_SIZE + 1]) {
491
  unsigned int i;
492
16
  const char hex[] = "0123456789ABCDEF";
493
494
432
  for (i = 0; i < md_size; i++) {
495
416
    (*fingerprint)[3*i] = hex[(md[i] & 0xf0) >> 4];
496
416
    (*fingerprint)[(3*i)+1] = hex[(md[i] & 0x0f)];
497
416
    (*fingerprint)[(3*i)+2] = ':';
498
  }
499
500
16
  if (md_size > 0) {
501
16
    (*fingerprint)[(3*(md_size-1))+2] = '\0';
502
  } else {
503
    (*fingerprint)[0] = '\0';
504
  }
505
16
}
506
507
6
MaybeLocal<Value> GetCurveASN1Name(Environment* env, const int nid) {
508
6
  const char* nist = OBJ_nid2sn(nid);
509
  return nist != nullptr ?
510
      MaybeLocal<Value>(OneByteString(env->isolate(), nist)) :
511
12
      MaybeLocal<Value>(Undefined(env->isolate()));
512
}
513
514
6
MaybeLocal<Value> GetCurveNistName(Environment* env, const int nid) {
515
6
  const char* nist = EC_curve_nid2nist(nid);
516
  return nist != nullptr ?
517
      MaybeLocal<Value>(OneByteString(env->isolate(), nist)) :
518
12
      MaybeLocal<Value>(Undefined(env->isolate()));
519
}
520
521
6
MaybeLocal<Value> GetECPubKey(
522
    Environment* env,
523
    const EC_GROUP* group,
524
    const ECPointer& ec) {
525
6
  const EC_POINT* pubkey = EC_KEY_get0_public_key(ec.get());
526
6
  if (pubkey == nullptr)
527
    return Undefined(env->isolate());
528
529
12
  return ECPointToBuffer(
530
      env,
531
      group,
532
      pubkey,
533
6
      EC_KEY_get_conv_form(ec.get()),
534
18
      nullptr).FromMaybe(Local<Object>());
535
}
536
537
6
MaybeLocal<Value> GetECGroup(
538
    Environment* env,
539
    const EC_GROUP* group,
540
    const ECPointer& ec) {
541
6
  if (group == nullptr)
542
    return Undefined(env->isolate());
543
544
6
  int bits = EC_GROUP_order_bits(group);
545
6
  if (bits <= 0)
546
    return Undefined(env->isolate());
547
548
12
  return Integer::New(env->isolate(), bits);
549
}
550
551
2
MaybeLocal<Object> GetPubKey(Environment* env, const RSAPointer& rsa) {
552
2
  int size = i2d_RSA_PUBKEY(rsa.get(), nullptr);
553
2
  CHECK_GE(size, 0);
554
555
4
  AllocatedBuffer buffer = AllocatedBuffer::AllocateManaged(env, size);
556
  unsigned char* serialized =
557
2
      reinterpret_cast<unsigned char*>(buffer.data());
558
2
  i2d_RSA_PUBKEY(rsa.get(), &serialized);
559
4
  return buffer.ToBuffer();
560
}
561
562
2
MaybeLocal<Value> GetExponentString(
563
    Environment* env,
564
    const BIOPointer& bio,
565
    const BIGNUM* e) {
566
2
  uint64_t exponent_word = static_cast<uint64_t>(BN_get_word(e));
567
2
  uint32_t lo = static_cast<uint32_t>(exponent_word);
568
2
  uint32_t hi = static_cast<uint32_t>(exponent_word >> 32);
569
2
  if (hi == 0)
570
2
    BIO_printf(bio.get(), "0x%x", lo);
571
  else
572
    BIO_printf(bio.get(), "0x%x%08x", hi, lo);
573
574
4
  return ToV8Value(env, bio);
575
}
576
577
2
Local<Value> GetBits(Environment* env, const BIGNUM* n) {
578
4
  return Integer::New(env->isolate(), BN_num_bits(n));
579
}
580
581
2
MaybeLocal<Value> GetModulusString(
582
    Environment* env,
583
    const BIOPointer& bio,
584
    const BIGNUM* n) {
585
2
  BN_print(bio.get(), n);
586
4
  return ToV8Value(env, bio);
587
}
588
}  // namespace
589
590
8
MaybeLocal<Object> GetRawDERCertificate(Environment* env, X509* cert) {
591
8
  int size = i2d_X509(cert, nullptr);
592
593
16
  AllocatedBuffer buffer = AllocatedBuffer::AllocateManaged(env, size);
594
  unsigned char* serialized =
595
8
      reinterpret_cast<unsigned char*>(buffer.data());
596
8
  i2d_X509(cert, &serialized);
597
16
  return buffer.ToBuffer();
598
}
599
600
8
MaybeLocal<Value> GetSerialNumber(Environment* env, X509* cert) {
601
8
  if (ASN1_INTEGER* serial_number = X509_get_serialNumber(cert)) {
602
8
    BignumPointer bn(ASN1_INTEGER_to_BN(serial_number, nullptr));
603
8
    if (bn) {
604
8
      char* data = BN_bn2hex(bn.get());
605
8
      ByteSource buf = ByteSource::Allocated(data, strlen(data));
606
8
      if (buf)
607
16
        return OneByteString(env->isolate(), buf.get());
608
    }
609
  }
610
611
  return Undefined(env->isolate());
612
}
613
614
8
MaybeLocal<Value> GetKeyUsage(Environment* env, X509* cert) {
615
  StackOfASN1 eku(static_cast<STACK_OF(ASN1_OBJECT)*>(
616
16
      X509_get_ext_d2i(cert, NID_ext_key_usage, nullptr, nullptr)));
617
8
  if (eku) {
618
4
    const int count = sk_ASN1_OBJECT_num(eku.get());
619
8
    MaybeStackBuffer<Local<Value>, 16> ext_key_usage(count);
620
    char buf[256];
621
622
4
    int j = 0;
623
12
    for (int i = 0; i < count; i++) {
624
8
      if (OBJ_obj2txt(buf,
625
                      sizeof(buf),
626
8
                      sk_ASN1_OBJECT_value(eku.get(), i), 1) >= 0) {
627
16
        ext_key_usage[j++] = OneByteString(env->isolate(), buf);
628
      }
629
    }
630
631
8
    return Array::New(env->isolate(), ext_key_usage.out(), count);
632
  }
633
634
8
  return Undefined(env->isolate());
635
}
636
637
16
MaybeLocal<Value> GetFingerprintDigest(
638
    Environment* env,
639
    const EVP_MD* method,
640
    X509* cert) {
641
  unsigned char md[EVP_MAX_MD_SIZE];
642
  unsigned int md_size;
643
  char fingerprint[EVP_MAX_MD_SIZE * 3 + 1];
644
645
16
  if (X509_digest(cert, method, md, &md_size)) {
646
16
    AddFingerprintDigest(md, md_size, &fingerprint);
647
32
    return OneByteString(env->isolate(), fingerprint);
648
  }
649
  return Undefined(env->isolate());
650
}
651
652
8
MaybeLocal<Value> GetValidTo(
653
    Environment* env,
654
    X509* cert,
655
    const BIOPointer& bio) {
656
8
  ASN1_TIME_print(bio.get(), X509_get0_notAfter(cert));
657
16
  return ToV8Value(env, bio);
658
}
659
660
8
MaybeLocal<Value> GetValidFrom(
661
    Environment* env,
662
    X509* cert,
663
    const BIOPointer& bio) {
664
8
  ASN1_TIME_print(bio.get(), X509_get0_notBefore(cert));
665
16
  return ToV8Value(env, bio);
666
}
667
668
8
bool SafeX509ExtPrint(const BIOPointer& out, X509_EXTENSION* ext) {
669
8
  const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
670
671
8
  if (method != X509V3_EXT_get_nid(NID_subject_alt_name))
672
6
    return false;
673
674
2
  GENERAL_NAMES* names = static_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(ext));
675
2
  if (names == nullptr)
676
    return false;
677
678
8
  for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) {
679
6
    GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);
680
681
6
    if (i != 0)
682
4
      BIO_write(out.get(), ", ", 2);
683
684
6
    if (gen->type == GEN_DNS) {
685
6
      ASN1_IA5STRING* name = gen->d.dNSName;
686
687
6
      BIO_write(out.get(), "DNS:", 4);
688
6
      BIO_write(out.get(), name->data, name->length);
689
    } else {
690
      STACK_OF(CONF_VALUE)* nval = i2v_GENERAL_NAME(
691
          const_cast<X509V3_EXT_METHOD*>(method), gen, nullptr);
692
      if (nval == nullptr)
693
        return false;
694
      X509V3_EXT_val_prn(out.get(), nval, 0, 0);
695
      sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
696
    }
697
  }
698
2
  sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
699
700
2
  return true;
701
}
702
703
8
MaybeLocal<Value> GetIssuerString(
704
    Environment* env,
705
    const BIOPointer& bio,
706
    X509* cert) {
707
8
  X509_NAME* issuer_name = X509_get_issuer_name(cert);
708
8
  if (X509_NAME_print_ex(bio.get(), issuer_name, 0, X509_NAME_FLAGS) <= 0) {
709
    USE(BIO_reset(bio.get()));
710
    return Undefined(env->isolate());
711
  }
712
713
16
  return ToV8Value(env, bio);
714
}
715
716
8
MaybeLocal<Value> GetSubject(
717
    Environment* env,
718
    const BIOPointer& bio,
719
    X509* cert) {
720
8
  if (X509_NAME_print_ex(
721
          bio.get(),
722
8
          X509_get_subject_name(cert),
723
          0,
724
          X509_NAME_FLAGS) <= 0) {
725
    USE(BIO_reset(bio.get()));
726
    return Undefined(env->isolate());
727
  }
728
729
16
  return ToV8Value(env, bio);
730
}
731
732
MaybeLocal<Value> GetCipherName(Environment* env, const SSLPointer& ssl) {
733
  return GetCipherName(env, SSL_get_current_cipher(ssl.get()));
734
}
735
736
MaybeLocal<Value> GetCipherStandardName(
737
    Environment* env,
738
    const SSLPointer& ssl) {
739
  return GetCipherStandardName(env, SSL_get_current_cipher(ssl.get()));
740
}
741
742
MaybeLocal<Value> GetCipherVersion(Environment* env, const SSLPointer& ssl) {
743
  return GetCipherVersion(env, SSL_get_current_cipher(ssl.get()));
744
}
745
746
MaybeLocal<Array> GetClientHelloCiphers(
747
    Environment* env,
748
    const SSLPointer& ssl) {
749
  EscapableHandleScope scope(env->isolate());
750
  const unsigned char* buf;
751
  size_t len = SSL_client_hello_get0_ciphers(ssl.get(), &buf);
752
  size_t count = len / 2;
753
  MaybeStackBuffer<Local<Value>, 16> ciphers(count);
754
  int j = 0;
755
  for (size_t n = 0; n < len; n += 2) {
756
    const SSL_CIPHER* cipher = SSL_CIPHER_find(ssl.get(), buf);
757
    buf += 2;
758
    Local<Object> obj = Object::New(env->isolate());
759
    if (!Set(env->context(),
760
             obj,
761
             env->name_string(),
762
             GetCipherName(env, cipher)) ||
763
        !Set(env->context(),
764
             obj,
765
             env->standard_name_string(),
766
             GetCipherStandardName(env, cipher)) ||
767
        !Set(env->context(),
768
             obj,
769
             env->version_string(),
770
             GetCipherVersion(env, cipher))) {
771
      return MaybeLocal<Array>();
772
    }
773
    ciphers[j++] = obj;
774
  }
775
  Local<Array> ret = Array::New(env->isolate(), ciphers.out(), count);
776
  return scope.Escape(ret);
777
}
778
779
780
MaybeLocal<Object> GetCipherInfo(Environment* env, const SSLPointer& ssl) {
781
  if (SSL_get_current_cipher(ssl.get()) == nullptr)
782
    return MaybeLocal<Object>();
783
  EscapableHandleScope scope(env->isolate());
784
  Local<Object> info = Object::New(env->isolate());
785
786
  if (!Set<Value>(env->context(),
787
                  info,
788
                  env->name_string(),
789
                  GetCipherName(env, ssl)) ||
790
      !Set<Value>(env->context(),
791
                  info,
792
                  env->standard_name_string(),
793
                  GetCipherStandardName(env, ssl)) ||
794
      !Set<Value>(env->context(),
795
                  info,
796
                  env->version_string(),
797
                  GetCipherVersion(env, ssl))) {
798
    return MaybeLocal<Object>();
799
  }
800
801
  return scope.Escape(info);
802
}
803
804
13
MaybeLocal<Object> GetEphemeralKey(Environment* env, const SSLPointer& ssl) {
805
13
  CHECK_EQ(SSL_is_server(ssl.get()), 0);
806
  EVP_PKEY* raw_key;
807
808
13
  EscapableHandleScope scope(env->isolate());
809
13
  Local<Object> info = Object::New(env->isolate());
810
13
  if (!SSL_get_server_tmp_key(ssl.get(), &raw_key))
811
11
    return scope.Escape(info);
812
813
2
  Local<Context> context = env->context();
814
4
  crypto::EVPKeyPointer key(raw_key);
815
816
2
  int kid = EVP_PKEY_id(key.get());
817
2
  int bits = EVP_PKEY_bits(key.get());
818
2
  switch (kid) {
819
    case EVP_PKEY_DH:
820
      if (!Set<String>(context, info, env->type_string(), env->dh_string()) ||
821
          !Set<Integer>(context,
822
               info,
823
               env->size_string(),
824
               Integer::New(env->isolate(), bits))) {
825
        return MaybeLocal<Object>();
826
      }
827
      break;
828
    case EVP_PKEY_EC:
829
    case EVP_PKEY_X25519:
830
    case EVP_PKEY_X448:
831
      {
832
        const char* curve_name;
833
2
        if (kid == EVP_PKEY_EC) {
834
          ECKeyPointer ec(EVP_PKEY_get1_EC_KEY(key.get()));
835
          int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec.get()));
836
          curve_name = OBJ_nid2sn(nid);
837
        } else {
838
2
          curve_name = OBJ_nid2sn(kid);
839
        }
840
10
        if (!Set<String>(context,
841
                         info,
842
                         env->type_string(),
843
2
                         env->ecdh_string()) ||
844
8
            !Set<String>(context,
845
                info,
846
                env->name_string(),
847

4
                OneByteString(env->isolate(), curve_name)) ||
848
8
            !Set<Integer>(context,
849
                 info,
850
                 env->size_string(),
851
                 Integer::New(env->isolate(), bits))) {
852
          return MaybeLocal<Object>();
853
        }
854
      }
855
2
      break;
856
  }
857
858
2
  return scope.Escape(info);
859
}
860
861
6
MaybeLocal<Object> ECPointToBuffer(Environment* env,
862
                                   const EC_GROUP* group,
863
                                   const EC_POINT* point,
864
                                   point_conversion_form_t form,
865
                                   const char** error) {
866
6
  size_t len = EC_POINT_point2oct(group, point, form, nullptr, 0, nullptr);
867
6
  if (len == 0) {
868
    if (error != nullptr) *error = "Failed to get public key length";
869
    return MaybeLocal<Object>();
870
  }
871
12
  AllocatedBuffer buf = AllocatedBuffer::AllocateManaged(env, len);
872
6
  len = EC_POINT_point2oct(group,
873
                           point,
874
                           form,
875
6
                           reinterpret_cast<unsigned char*>(buf.data()),
876
                           buf.size(),
877
6
                           nullptr);
878
6
  if (len == 0) {
879
    if (error != nullptr) *error = "Failed to get public key";
880
    return MaybeLocal<Object>();
881
  }
882
6
  return buf.ToBuffer();
883
}
884
885
2
MaybeLocal<Value> GetPeerCert(
886
    Environment* env,
887
    const SSLPointer& ssl,
888
    bool abbreviated,
889
    bool is_server) {
890
2
  ClearErrorOnReturn clear_error_on_return;
891
  Local<Object> result;
892
  MaybeLocal<Object> maybe_cert;
893
894
  // NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain`
895
  // contains the `peer_certificate`, but on server it doesn't.
896
4
  X509Pointer cert(is_server ? SSL_get_peer_certificate(ssl.get()) : nullptr);
897
2
  STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(ssl.get());
898


2
  if (!cert && (ssl_certs == nullptr || sk_X509_num(ssl_certs) == 0))
899
    return Undefined(env->isolate());
900
901
  // Short result requested.
902
2
  if (abbreviated) {
903
    maybe_cert =
904
        X509ToObject(env, cert ? cert.get() : sk_X509_value(ssl_certs, 0));
905
    return maybe_cert.ToLocal(&result) ? result : MaybeLocal<Value>();
906
  }
907
908
4
  StackOfX509 peer_certs = CloneSSLCerts(std::move(cert), ssl_certs);
909
2
  if (peer_certs == nullptr)
910
    return Undefined(env->isolate());
911
912
  // First and main certificate.
913
4
  X509Pointer first_cert(sk_X509_value(peer_certs.get(), 0));
914
2
  CHECK(first_cert);
915
2
  maybe_cert = X509ToObject(env, first_cert.release());
916
2
  if (!maybe_cert.ToLocal(&result))
917
    return MaybeLocal<Value>();
918
919
  Local<Object> issuer_chain;
920
  MaybeLocal<Object> maybe_issuer_chain;
921
922
  maybe_issuer_chain =
923
      AddIssuerChainToObject(
924
          &cert,
925
          result,
926
2
          std::move(peer_certs),
927
2
          env);
928
2
  if (!maybe_issuer_chain.ToLocal(&issuer_chain))
929
    return MaybeLocal<Value>();
930
931
  maybe_issuer_chain =
932
      GetLastIssuedCert(
933
          &cert,
934
          ssl,
935
          issuer_chain,
936
2
          env);
937
938
  issuer_chain.Clear();
939
2
  if (!maybe_issuer_chain.ToLocal(&issuer_chain))
940
    return MaybeLocal<Value>();
941
942
  // Last certificate should be self-signed.
943

6
  if (X509_check_issued(cert.get(), cert.get()) == X509_V_OK &&
944
6
      !Set<Object>(env->context(),
945
           issuer_chain,
946
           env->issuercert_string(),
947
           issuer_chain)) {
948
    return MaybeLocal<Value>();
949
  }
950
951
2
  return result;
952
}
953
954
8
MaybeLocal<Object> X509ToObject(Environment* env, X509* cert) {
955
8
  EscapableHandleScope scope(env->isolate());
956
8
  Local<Context> context = env->context();
957
8
  Local<Object> info = Object::New(env->isolate());
958
959
16
  BIOPointer bio(BIO_new(BIO_s_mem()));
960
961
32
  if (!Set<Value>(context,
962
                  info,
963
                  env->subject_string(),
964
8
                  GetSubject(env, bio, cert)) ||
965
24
      !Set<Value>(context,
966
                  info,
967
                  env->issuer_string(),
968
8
                  GetIssuerString(env, bio, cert)) ||
969
24
      !Set<Value>(context,
970
                  info,
971
                  env->subjectaltname_string(),
972

16
                  GetInfoString<NID_subject_alt_name>(env, bio, cert)) ||
973
24
      !Set<Value>(context,
974
                  info,
975
                  env->infoaccess_string(),
976
                  GetInfoString<NID_info_access>(env, bio, cert))) {
977
    return MaybeLocal<Object>();
978
  }
979
980
16
  EVPKeyPointer pkey(X509_get_pubkey(cert));
981
16
  RSAPointer rsa;
982
16
  ECPointer ec;
983
8
  if (pkey) {
984
8
    switch (EVP_PKEY_id(pkey.get())) {
985
      case EVP_PKEY_RSA:
986
2
        rsa.reset(EVP_PKEY_get1_RSA(pkey.get()));
987
2
        break;
988
      case EVP_PKEY_EC:
989
6
        ec.reset(EVP_PKEY_get1_EC_KEY(pkey.get()));
990
6
        break;
991
    }
992
  }
993
994
8
  if (rsa) {
995
    const BIGNUM* n;
996
    const BIGNUM* e;
997
2
    RSA_get0_key(rsa.get(), &n, &e, nullptr);
998
8
    if (!Set<Value>(context,
999
                    info,
1000
                    env->modulus_string(),
1001
2
                    GetModulusString(env, bio, n)) ||
1002
10
        !Set<Value>(context, info, env->bits_string(), GetBits(env, n)) ||
1003
6
        !Set<Value>(context,
1004
                    info,
1005
                    env->exponent_string(),
1006

4
                    GetExponentString(env, bio, e)) ||
1007
6
        !Set<Object>(context,
1008
                     info,
1009
                     env->pubkey_string(),
1010
                     GetPubKey(env, rsa))) {
1011
      return MaybeLocal<Object>();
1012
    }
1013
6
  } else if (ec) {
1014
6
    const EC_GROUP* group = EC_KEY_get0_group(ec.get());
1015
1016
24
    if (!Set<Value>(context,
1017
                    info,
1018
                    env->bits_string(),
1019

12
                    GetECGroup(env, group, ec)) ||
1020
18
        !Set<Value>(context,
1021
                    info,
1022
                    env->pubkey_string(),
1023
                    GetECPubKey(env, group, ec))) {
1024
      return MaybeLocal<Object>();
1025
    }
1026
1027
6
    const int nid = EC_GROUP_get_curve_name(group);
1028
6
    if (nid != 0) {
1029
      // Curve is well-known, get its OID and NIST nick-name (if it has one).
1030
1031
24
      if (!Set<Value>(context,
1032
                      info,
1033
                      env->asn1curve_string(),
1034

12
                      GetCurveASN1Name(env, nid)) ||
1035
18
          !Set<Value>(context,
1036
                      info,
1037
                      env->nistcurve_string(),
1038
                      GetCurveNistName(env, nid))) {
1039
        return MaybeLocal<Object>();
1040
      }
1041
    } else {
1042
      // Unnamed curves can be described by their mathematical properties,
1043
      // but aren't used much (at all?) with X.509/TLS. Support later if needed.
1044
    }
1045
  }
1046
1047
  // pkey, rsa, and ec pointers are no longer needed.
1048
8
  pkey.reset();
1049
8
  rsa.reset();
1050
8
  ec.reset();
1051
1052
32
  if (!Set<Value>(context,
1053
                  info,
1054
                  env->valid_from_string(),
1055

16
                  GetValidFrom(env, cert, bio)) ||
1056
24
      !Set<Value>(context,
1057
                  info,
1058
                  env->valid_to_string(),
1059
                  GetValidTo(env, cert, bio))) {
1060
    return MaybeLocal<Object>();
1061
  }
1062
1063
  // bio is no longer needed
1064
8
  bio.reset();
1065
1066
32
  if (!Set<Value>(context,
1067
                  info,
1068
                  env->fingerprint_string(),
1069
8
                  GetFingerprintDigest(env, EVP_sha1(), cert)) ||
1070
24
      !Set<Value>(context,
1071
                  info,
1072
                  env->fingerprint256_string(),
1073
8
                  GetFingerprintDigest(env, EVP_sha256(), cert)) ||
1074
24
      !Set<Value>(context,
1075
                  info,
1076
                  env->ext_key_usage_string(),
1077
8
                  GetKeyUsage(env, cert)) ||
1078
24
      !Set<Value>(context,
1079
                  info,
1080
                  env->serial_number_string(),
1081

16
                  GetSerialNumber(env, cert)) ||
1082
24
      !Set<Object>(context,
1083
                   info,
1084
                   env->raw_string(),
1085
                   GetRawDERCertificate(env, cert))) {
1086
    return MaybeLocal<Object>();
1087
  }
1088
1089
8
  return scope.Escape(info);
1090
}
1091
1092
}  // namespace crypto
1093

366
}  // namespace node