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: 363 549 66.1 %
Date: 2021-04-22 04:13:51 Branches: 178 387 46.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
831
int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) {
49
831
  X509_STORE* store = SSL_CTX_get_cert_store(ctx);
50
  DeleteFnPtr<X509_STORE_CTX, X509_STORE_CTX_free> store_ctx(
51
1662
      X509_STORE_CTX_new());
52
1662
  return store_ctx.get() != nullptr &&
53

1662
         X509_STORE_CTX_init(store_ctx.get(), store, nullptr, nullptr) == 1 &&
54
2493
         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
38
bool SetALPN(const SSLPointer& ssl, Local<Value> alpn) {
86
38
  if (!alpn->IsArrayBufferView())
87
    return false;
88
38
  ArrayBufferViewContents<unsigned char> protos(alpn.As<ArrayBufferView>());
89
38
  return SSL_set_alpn_protos(ssl.get(), protos.data(), protos.length()) == 0;
90
}
91
92
4
MaybeLocal<Value> GetSSLOCSPResponse(
93
    Environment* env,
94
    SSL* ssl,
95
    Local<Value> default_value) {
96
  const unsigned char* resp;
97
4
  int len = SSL_get_tlsext_status_ocsp_resp(ssl, &resp);
98
4
  if (resp == nullptr)
99
2
    return default_value;
100
101
  Local<Value> ret;
102
  MaybeLocal<Object> maybe_buffer =
103
2
      Buffer::Copy(env, reinterpret_cast<const char*>(resp), len);
104
105
2
  if (!maybe_buffer.ToLocal(&ret))
106
    return MaybeLocal<Value>();
107
108
2
  return ret;
109
}
110
111
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
124
bool SetTLSSession(
120
    const SSLPointer& ssl,
121
    const SSLSessionPointer& session) {
122

124
  return session != nullptr && SSL_set_session(ssl.get(), session.get()) == 1;
123
}
124
125
124
SSLSessionPointer GetTLSSession(Local<Value> val) {
126
124
  if (!val->IsArrayBufferView())
127
    return SSLSessionPointer();
128
124
  ArrayBufferViewContents<unsigned char> sbuf(val.As<ArrayBufferView>());
129
124
  return GetTLSSession(sbuf.data(), sbuf.length());
130
}
131
132
124
SSLSessionPointer GetTLSSession(const unsigned char* buf, size_t length) {
133
124
  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
901
long VerifyPeerCertificate(  // NOLINT(runtime/int)
207
    const SSLPointer& ssl,
208
    long def) {  // NOLINT(runtime/int)
209
901
  long err = def;  // NOLINT(runtime/int)
210
901
  if (X509* peer_cert = SSL_get_peer_certificate(ssl.get())) {
211
893
    X509_free(peer_cert);
212
893
    err = SSL_get_verify_result(ssl.get());
213
  } else {
214
8
    const SSL_CIPHER* curr_cipher = SSL_get_current_cipher(ssl.get());
215
8
    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

21
    if (SSL_CIPHER_get_auth_nid(curr_cipher) == NID_auth_psk ||
220
12
        (SSL_SESSION_get_protocol_version(sess) == TLS1_3_VERSION &&
221
6
         SSL_session_reused(ssl.get()))) {
222
7
      return X509_V_OK;
223
    }
224
  }
225
894
  return err;
226
}
227
228
12
int UseSNIContext(const SSLPointer& ssl, BaseObjectPtr<SecureContext> context) {
229
12
  SSL_CTX* ctx = context->ctx_.get();
230
12
  X509* x509 = SSL_CTX_get0_certificate(ctx);
231
12
  EVP_PKEY* pkey = SSL_CTX_get0_privatekey(ctx);
232
  STACK_OF(X509)* chain;
233
234
12
  int err = SSL_CTX_get0_chain_certs(ctx, &chain);
235
12
  if (err == 1) err = SSL_use_certificate(ssl.get(), x509);
236
12
  if (err == 1) err = SSL_use_PrivateKey(ssl.get(), pkey);
237

12
  if (err == 1 && chain != nullptr) err = SSL_set1_chain(ssl.get(), chain);
238
12
  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
25
const char* GetServerName(SSL* ssl) {
289
25
  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
427
const char* X509ErrorCode(long err) {  // NOLINT(runtime/int)
297
427
  const char* code = "UNSPECIFIED";
298
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
299







427
  switch (err) {
300
    // if you modify anything in here, *please* update the respective section in
301
    // doc/api/tls.md as well
302
1
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
303
1
    CASE_X509_ERR(UNABLE_TO_GET_CRL)
304
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
305
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
306
    CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
307
    CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
308
    CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
309
    CASE_X509_ERR(CERT_NOT_YET_VALID)
310
    CASE_X509_ERR(CERT_HAS_EXPIRED)
311
    CASE_X509_ERR(CRL_NOT_YET_VALID)
312
    CASE_X509_ERR(CRL_HAS_EXPIRED)
313
    CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
314
    CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
315
    CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
316
    CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
317
    CASE_X509_ERR(OUT_OF_MEM)
318
238
    CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
319
14
    CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
320
4
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
321
167
    CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
322
    CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
323
1
    CASE_X509_ERR(CERT_REVOKED)
324
    CASE_X509_ERR(INVALID_CA)
325
    CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
326
1
    CASE_X509_ERR(INVALID_PURPOSE)
327
    CASE_X509_ERR(CERT_UNTRUSTED)
328
    CASE_X509_ERR(CERT_REJECTED)
329
    CASE_X509_ERR(HOSTNAME_MISMATCH)
330
  }
331
#undef CASE_X509_ERR
332
427
  return code;
333
}
334
335
MaybeLocal<Value> GetValidationErrorReason(Environment* env, int err) {
336
  if (err == 0)
337
    return Undefined(env->isolate());
338
  const char* reason = X509_verify_cert_error_string(err);
339
  return OneByteString(env->isolate(), reason);
340
}
341
342
MaybeLocal<Value> GetValidationErrorCode(Environment* env, int err) {
343
  if (err == 0)
344
    return Undefined(env->isolate());
345
  return OneByteString(env->isolate(), X509ErrorCode(err));
346
}
347
348
12
MaybeLocal<Value> GetCert(Environment* env, const SSLPointer& ssl) {
349
12
  ClearErrorOnReturn clear_error_on_return;
350
12
  X509* cert = SSL_get_certificate(ssl.get());
351
12
  if (cert == nullptr)
352
2
    return Undefined(env->isolate());
353
354
11
  MaybeLocal<Object> maybe_cert = X509ToObject(env, cert);
355
11
  return maybe_cert.FromMaybe<Value>(Local<Value>());
356
}
357
358
6945
Local<Value> ToV8Value(Environment* env, const BIOPointer& bio) {
359
  BUF_MEM* mem;
360
6945
  BIO_get_mem_ptr(bio.get(), &mem);
361
  MaybeLocal<String> ret =
362
      String::NewFromUtf8(
363
          env->isolate(),
364
6945
          mem->data,
365
          NewStringType::kNormal,
366
13890
          mem->length);
367
6945
  USE(BIO_reset(bio.get()));
368
6945
  return ret.FromMaybe(Local<Value>());
369
}
370
371
namespace {
372
template <typename T>
373
20944
bool Set(
374
    Local<Context> context,
375
    Local<Object> target,
376
    Local<Value> name,
377
    MaybeLocal<T> maybe_value) {
378
  Local<Value> value;
379


20944
  if (!maybe_value.ToLocal(&value))
380
    return false;
381
382
  // Undefined is ignored, but still considered successful
383


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

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

106
                  GetCipherStandardName(env, ssl)) ||
796
159
      !Set<Value>(env->context(),
797
                  info,
798
                  env->version_string(),
799
                  GetCipherVersion(env, ssl))) {
800
    return MaybeLocal<Object>();
801
  }
802
803
53
  return scope.Escape(info);
804
}
805
806
828
MaybeLocal<Object> GetEphemeralKey(Environment* env, const SSLPointer& ssl) {
807
828
  CHECK_EQ(SSL_is_server(ssl.get()), 0);
808
  EVP_PKEY* raw_key;
809
810
828
  EscapableHandleScope scope(env->isolate());
811
828
  Local<Object> info = Object::New(env->isolate());
812
828
  if (!SSL_get_server_tmp_key(ssl.get(), &raw_key))
813
44
    return scope.Escape(info);
814
815
784
  Local<Context> context = env->context();
816
1568
  crypto::EVPKeyPointer key(raw_key);
817
818
784
  int kid = EVP_PKEY_id(key.get());
819
784
  int bits = EVP_PKEY_bits(key.get());
820
784
  switch (kid) {
821
    case EVP_PKEY_DH:
822

35
      if (!Set<String>(context, info, env->type_string(), env->dh_string()) ||
823
28
          !Set<Integer>(context,
824
               info,
825
               env->size_string(),
826
               Integer::New(env->isolate(), bits))) {
827
        return MaybeLocal<Object>();
828
      }
829
7
      break;
830
    case EVP_PKEY_EC:
831
    case EVP_PKEY_X25519:
832
    case EVP_PKEY_X448:
833
      {
834
        const char* curve_name;
835
777
        if (kid == EVP_PKEY_EC) {
836
10
          ECKeyPointer ec(EVP_PKEY_get1_EC_KEY(key.get()));
837
5
          int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec.get()));
838
5
          curve_name = OBJ_nid2sn(nid);
839
        } else {
840
772
          curve_name = OBJ_nid2sn(kid);
841
        }
842
3885
        if (!Set<String>(context,
843
                         info,
844
                         env->type_string(),
845
777
                         env->ecdh_string()) ||
846
3108
            !Set<String>(context,
847
                info,
848
                env->name_string(),
849

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


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

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

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

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

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

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

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

2312
                  GetSerialNumber(env, cert)) ||
1084
3468
      !Set<Object>(context,
1085
                   info,
1086
                   env->raw_string(),
1087
                   GetRawDERCertificate(env, cert))) {
1088
    return MaybeLocal<Object>();
1089
  }
1090
1091
1156
  return scope.Escape(info);
1092
}
1093
1094
}  // namespace crypto
1095

14310
}  // namespace node