GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_crypto_common.cc Lines: 372 557 66.8 %
Date: 2020-08-07 22:13:19 Branches: 191 405 47.2 %

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 "node_crypto_common.h"
7
#include "node.h"
8
#include "node_internals.h"
9
#include "node_url.h"
10
#include "string_bytes.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::ArrayBufferView;
29
using v8::Context;
30
using v8::EscapableHandleScope;
31
using v8::Integer;
32
using v8::Local;
33
using v8::MaybeLocal;
34
using v8::NewStringType;
35
using v8::Null;
36
using v8::Object;
37
using v8::String;
38
using v8::Undefined;
39
using v8::Value;
40
41
namespace crypto {
42
43
static constexpr int X509_NAME_FLAGS =
44
    ASN1_STRFLGS_ESC_CTRL |
45
    ASN1_STRFLGS_UTF8_CONVERT |
46
    XN_FLAG_SEP_MULTILINE |
47
    XN_FLAG_FN_SN;
48
49
800
int SSL_CTX_get_issuer(SSL_CTX* ctx, X509* cert, X509** issuer) {
50
800
  X509_STORE* store = SSL_CTX_get_cert_store(ctx);
51
  DeleteFnPtr<X509_STORE_CTX, X509_STORE_CTX_free> store_ctx(
52
1600
      X509_STORE_CTX_new());
53
1600
  return store_ctx.get() != nullptr &&
54

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

104
  return session != nullptr && SSL_set_session(ssl.get(), session.get()) == 1;
124
}
125
126
104
SSLSessionPointer GetTLSSession(Local<Value> val) {
127
104
  if (!val->IsArrayBufferView())
128
    return SSLSessionPointer();
129
104
  ArrayBufferViewContents<unsigned char> sbuf(val.As<ArrayBufferView>());
130
104
  return GetTLSSession(sbuf.data(), sbuf.length());
131
}
132
133
104
SSLSessionPointer GetTLSSession(const unsigned char* buf, size_t length) {
134
104
  return SSLSessionPointer(d2i_SSL_SESSION(nullptr, &buf, length));
135
}
136
137
std::unordered_multimap<std::string, std::string>
138
GetCertificateAltNames(X509* cert) {
139
  std::unordered_multimap<std::string, std::string> map;
140
  BIOPointer bio(BIO_new(BIO_s_mem()));
141
  BUF_MEM* mem;
142
  int idx = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
143
  if (idx < 0)  // There is no subject alt name
144
    return map;
145
146
  X509_EXTENSION* ext = X509_get_ext(cert, idx);
147
  CHECK_NOT_NULL(ext);
148
  const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
149
  CHECK_EQ(method, X509V3_EXT_get_nid(NID_subject_alt_name));
150
151
  GENERAL_NAMES* names = static_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(ext));
152
  if (names == nullptr)  // There are no names
153
    return map;
154
155
  for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) {
156
    USE(BIO_reset(bio.get()));
157
    GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);
158
    if (gen->type == GEN_DNS) {
159
      ASN1_IA5STRING* name = gen->d.dNSName;
160
      BIO_write(bio.get(), name->data, name->length);
161
      BIO_get_mem_ptr(bio.get(), &mem);
162
      map.emplace("dns", std::string(mem->data, mem->length));
163
    } else {
164
      STACK_OF(CONF_VALUE)* nval = i2v_GENERAL_NAME(
165
          const_cast<X509V3_EXT_METHOD*>(method), gen, nullptr);
166
      if (nval == nullptr)
167
        continue;
168
      X509V3_EXT_val_prn(bio.get(), nval, 0, 0);
169
      sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
170
      BIO_get_mem_ptr(bio.get(), &mem);
171
      std::string value(mem->data, mem->length);
172
      if (value.compare(0, 11, "IP Address:") == 0) {
173
        map.emplace("ip", value.substr(11));
174
      } else if (value.compare(0, 4, "URI:") == 0) {
175
        url::URL url(value.substr(4));
176
        if (url.flags() & url::URL_FLAGS_CANNOT_BE_BASE ||
177
            url.flags() & url::URL_FLAGS_FAILED) {
178
          continue;  // Skip this one
179
        }
180
        map.emplace("uri", url.host());
181
      }
182
    }
183
  }
184
  sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
185
  return map;
186
}
187
188
std::string GetCertificateCN(X509* cert) {
189
  X509_NAME* subject = X509_get_subject_name(cert);
190
  if (subject != nullptr) {
191
    int nid = OBJ_txt2nid("CN");
192
    int idx = X509_NAME_get_index_by_NID(subject, nid, -1);
193
    if (idx != -1) {
194
      X509_NAME_ENTRY* cn = X509_NAME_get_entry(subject, idx);
195
      if (cn != nullptr) {
196
        ASN1_STRING* cn_str = X509_NAME_ENTRY_get_data(cn);
197
        if (cn_str != nullptr) {
198
          return std::string(reinterpret_cast<const char*>(
199
              ASN1_STRING_get0_data(cn_str)));
200
        }
201
      }
202
    }
203
  }
204
  return std::string();
205
}
206
207
867
long VerifyPeerCertificate(  // NOLINT(runtime/int)
208
    const SSLPointer& ssl,
209
    long def) {  // NOLINT(runtime/int)
210
867
  long err = def;  // NOLINT(runtime/int)
211
867
  if (X509* peer_cert = SSL_get_peer_certificate(ssl.get())) {
212
859
    X509_free(peer_cert);
213
859
    err = SSL_get_verify_result(ssl.get());
214
  } else {
215
8
    const SSL_CIPHER* curr_cipher = SSL_get_current_cipher(ssl.get());
216
8
    const SSL_SESSION* sess = SSL_get_session(ssl.get());
217
    // Allow no-cert for PSK authentication in TLS1.2 and lower.
218
    // In TLS1.3 check that session was reused because TLS1.3 PSK
219
    // looks like session resumption.
220

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

9
  if (err == 1 && chain != nullptr) err = SSL_set1_chain(ssl.get(), chain);
239
9
  return err;
240
}
241
242
const char* GetClientHelloALPN(const SSLPointer& ssl) {
243
  const unsigned char* buf;
244
  size_t len;
245
  size_t rem;
246
247
  if (!SSL_client_hello_get0_ext(
248
          ssl.get(),
249
          TLSEXT_TYPE_application_layer_protocol_negotiation,
250
          &buf,
251
          &rem) ||
252
      rem < 2) {
253
    return nullptr;
254
  }
255
256
  len = (buf[0] << 8) | buf[1];
257
  if (len + 2 != rem) return nullptr;
258
  return reinterpret_cast<const char*>(buf + 3);
259
}
260
261
const char* GetClientHelloServerName(const SSLPointer& ssl) {
262
  const unsigned char* buf;
263
  size_t len;
264
  size_t rem;
265
266
  if (!SSL_client_hello_get0_ext(
267
          ssl.get(),
268
          TLSEXT_TYPE_server_name,
269
          &buf,
270
          &rem) || rem <= 2) {
271
    return nullptr;
272
  }
273
274
  len = (*buf << 8) | *(buf + 1);
275
  if (len + 2 != rem)
276
    return nullptr;
277
  rem = len;
278
279
  if (rem == 0 || *(buf + 2) != TLSEXT_NAMETYPE_host_name) return nullptr;
280
  rem--;
281
  if (rem <= 2)
282
    return nullptr;
283
  len = (*(buf + 3) << 8) | *(buf + 4);
284
  if (len + 2 > rem)
285
    return nullptr;
286
  return reinterpret_cast<const char*>(buf + 5);
287
}
288
289
22
const char* GetServerName(SSL* ssl) {
290
22
  return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
291
}
292
293
bool SetGroups(SecureContext* sc, const char* groups) {
294
  return SSL_CTX_set1_groups_list(**sc, groups) == 1;
295
}
296
297
413
const char* X509ErrorCode(long err) {  // NOLINT(runtime/int)
298
413
  const char* code = "UNSPECIFIED";
299
#define CASE_X509_ERR(CODE) case X509_V_ERR_##CODE: code = #CODE; break;
300







413
  switch (err) {
301
1
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT)
302
1
    CASE_X509_ERR(UNABLE_TO_GET_CRL)
303
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CERT_SIGNATURE)
304
    CASE_X509_ERR(UNABLE_TO_DECRYPT_CRL_SIGNATURE)
305
    CASE_X509_ERR(UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY)
306
    CASE_X509_ERR(CERT_SIGNATURE_FAILURE)
307
    CASE_X509_ERR(CRL_SIGNATURE_FAILURE)
308
    CASE_X509_ERR(CERT_NOT_YET_VALID)
309
    CASE_X509_ERR(CERT_HAS_EXPIRED)
310
    CASE_X509_ERR(CRL_NOT_YET_VALID)
311
    CASE_X509_ERR(CRL_HAS_EXPIRED)
312
    CASE_X509_ERR(ERROR_IN_CERT_NOT_BEFORE_FIELD)
313
    CASE_X509_ERR(ERROR_IN_CERT_NOT_AFTER_FIELD)
314
    CASE_X509_ERR(ERROR_IN_CRL_LAST_UPDATE_FIELD)
315
    CASE_X509_ERR(ERROR_IN_CRL_NEXT_UPDATE_FIELD)
316
    CASE_X509_ERR(OUT_OF_MEM)
317
230
    CASE_X509_ERR(DEPTH_ZERO_SELF_SIGNED_CERT)
318
13
    CASE_X509_ERR(SELF_SIGNED_CERT_IN_CHAIN)
319
3
    CASE_X509_ERR(UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
320
163
    CASE_X509_ERR(UNABLE_TO_VERIFY_LEAF_SIGNATURE)
321
    CASE_X509_ERR(CERT_CHAIN_TOO_LONG)
322
1
    CASE_X509_ERR(CERT_REVOKED)
323
    CASE_X509_ERR(INVALID_CA)
324
    CASE_X509_ERR(PATH_LENGTH_EXCEEDED)
325
1
    CASE_X509_ERR(INVALID_PURPOSE)
326
    CASE_X509_ERR(CERT_UNTRUSTED)
327
    CASE_X509_ERR(CERT_REJECTED)
328
    CASE_X509_ERR(HOSTNAME_MISMATCH)
329
  }
330
#undef CASE_X509_ERR
331
413
  return code;
332
}
333
334
MaybeLocal<Value> GetValidationErrorReason(Environment* env, int err) {
335
  if (err == 0)
336
    return Undefined(env->isolate());
337
  const char* reason = X509_verify_cert_error_string(err);
338
  return OneByteString(env->isolate(), reason);
339
}
340
341
MaybeLocal<Value> GetValidationErrorCode(Environment* env, int err) {
342
  if (err == 0)
343
    return Undefined(env->isolate());
344
  return OneByteString(env->isolate(), X509ErrorCode(err));
345
}
346
347
12
MaybeLocal<Value> GetCert(Environment* env, const SSLPointer& ssl) {
348
12
  ClearErrorOnReturn clear_error_on_return;
349
12
  X509* cert = SSL_get_certificate(ssl.get());
350
12
  if (cert == nullptr)
351
2
    return Undefined(env->isolate());
352
353
11
  MaybeLocal<Object> maybe_cert = X509ToObject(env, cert);
354
11
  return maybe_cert.FromMaybe<Value>(Local<Value>());
355
}
356
357
namespace {
358
template <typename T>
359
20587
bool Set(
360
    Local<Context> context,
361
    Local<Object> target,
362
    Local<Value> name,
363
    MaybeLocal<T> maybe_value) {
364
  Local<Value> value;
365


20587
  if (!maybe_value.ToLocal(&value))
366
    return false;
367
368
  // Undefined is ignored, but still considered successful
369


41174
  if (value->IsUndefined())
370
3331
    return true;
371
372
34512
  return !target->Set(context, name, value).IsNothing();
373
}
374
375
6819
Local<Value> ToV8Value(Environment* env, const BIOPointer& bio) {
376
  BUF_MEM* mem;
377
6819
  BIO_get_mem_ptr(bio.get(), &mem);
378
  MaybeLocal<String> ret =
379
      String::NewFromUtf8(
380
          env->isolate(),
381
6819
          mem->data,
382
          NewStringType::kNormal,
383
13638
          mem->length);
384
6819
  USE(BIO_reset(bio.get()));
385
6819
  return ret.FromMaybe(Local<Value>());
386
}
387
388
147
MaybeLocal<Value> GetCipherValue(Environment* env,
389
    const SSL_CIPHER* cipher,
390
    const char* (*getstr)(const SSL_CIPHER* cipher)) {
391
147
  if (cipher == nullptr)
392
    return Undefined(env->isolate());
393
394
294
  return OneByteString(env->isolate(), getstr(cipher));
395
}
396
397
49
MaybeLocal<Value> GetCipherName(Environment* env, const SSL_CIPHER* cipher) {
398
49
  return GetCipherValue(env, cipher, SSL_CIPHER_get_name);
399
}
400
401
49
MaybeLocal<Value> GetCipherStandardName(
402
    Environment* env,
403
    const SSL_CIPHER* cipher) {
404
49
  return GetCipherValue(env, cipher, SSL_CIPHER_standard_name);
405
}
406
407
49
MaybeLocal<Value> GetCipherVersion(Environment* env, const SSL_CIPHER* cipher) {
408
49
  return GetCipherValue(env, cipher, SSL_CIPHER_get_version);
409
}
410
411
387
StackOfX509 CloneSSLCerts(X509Pointer&& cert,
412
                          const STACK_OF(X509)* const ssl_certs) {
413
774
  StackOfX509 peer_certs(sk_X509_new(nullptr));
414
387
  if (cert)
415
    sk_X509_push(peer_certs.get(), cert.release());
416
1111
  for (int i = 0; i < sk_X509_num(ssl_certs); i++) {
417
1448
    X509Pointer cert(X509_dup(sk_X509_value(ssl_certs, i)));
418

724
    if (!cert || !sk_X509_push(peer_certs.get(), cert.get()))
419
      return StackOfX509();
420
    // `cert` is now managed by the stack.
421
724
    cert.release();
422
  }
423
387
  return peer_certs;
424
}
425
426
387
MaybeLocal<Object> AddIssuerChainToObject(
427
    X509Pointer* cert,
428
    Local<Object> object,
429
    StackOfX509&& peer_certs,
430
    Environment* const env) {
431
387
  Local<Context> context = env->isolate()->GetCurrentContext();
432
387
  cert->reset(sk_X509_delete(peer_certs.get(), 0));
433
  for (;;) {
434
    int i;
435
393
    for (i = 0; i < sk_X509_num(peer_certs.get()); i++) {
436
337
      X509* ca = sk_X509_value(peer_certs.get(), i);
437
337
      if (X509_check_issued(ca, cert->get()) != X509_V_OK)
438
2
        continue;
439
440
      Local<Object> ca_info;
441
335
      MaybeLocal<Object> maybe_ca_info = X509ToObject(env, ca);
442
335
      if (!maybe_ca_info.ToLocal(&ca_info))
443
        return MaybeLocal<Object>();
444
445
670
      if (!Set<Object>(context, object, env->issuercert_string(), ca_info))
446
        return MaybeLocal<Object>();
447
335
      object = ca_info;
448
449
      // NOTE: Intentionally freeing cert that is not used anymore.
450
      // Delete cert and continue aggregating issuers.
451
335
      cert->reset(sk_X509_delete(peer_certs.get(), i));
452
335
      break;
453
    }
454
455
    // Issuer not found, break out of the loop.
456
391
    if (i == sk_X509_num(peer_certs.get()))
457
387
      break;
458
4
  }
459
387
  return MaybeLocal<Object>(object);
460
}
461
462
387
MaybeLocal<Object> GetLastIssuedCert(
463
    X509Pointer* cert,
464
    const SSLPointer& ssl,
465
    Local<Object> issuer_chain,
466
    Environment* const env) {
467
387
  Local<Context> context = env->isolate()->GetCurrentContext();
468
1107
  while (X509_check_issued(cert->get(), cert->get()) != X509_V_OK) {
469
    X509* ca;
470
360
    if (SSL_CTX_get_issuer(SSL_get_SSL_CTX(ssl.get()), cert->get(), &ca) <= 0)
471
      break;
472
473
    Local<Object> ca_info;
474
360
    MaybeLocal<Object> maybe_ca_info = X509ToObject(env, ca);
475
360
    if (!maybe_ca_info.ToLocal(&ca_info))
476
      return MaybeLocal<Object>();
477
478
720
    if (!Set<Object>(context, issuer_chain, env->issuercert_string(), ca_info))
479
      return MaybeLocal<Object>();
480
360
    issuer_chain = ca_info;
481
482
    // Delete previous cert and continue aggregating issuers.
483
360
    cert->reset(ca);
484
  }
485
387
  return MaybeLocal<Object>(issuer_chain);
486
}
487
488
1137
MaybeLocal<Object> GetRawDERCertificate(Environment* env, X509* cert) {
489
1137
  int size = i2d_X509(cert, nullptr);
490
491
2274
  AllocatedBuffer buffer = AllocatedBuffer::AllocateManaged(env, size);
492
  unsigned char* serialized =
493
1137
      reinterpret_cast<unsigned char*>(buffer.data());
494
1137
  i2d_X509(cert, &serialized);
495
2274
  return buffer.ToBuffer();
496
}
497
498
1137
MaybeLocal<Value> GetSerialNumber(Environment* env, X509* cert) {
499
1137
  if (ASN1_INTEGER* serial_number = X509_get_serialNumber(cert)) {
500
1137
    BignumPointer bn(ASN1_INTEGER_to_BN(serial_number, nullptr));
501
1137
    if (bn) {
502
1137
      OpenSSLBuffer buf(BN_bn2hex(bn.get()));
503
1137
      if (buf)
504
2274
        return OneByteString(env->isolate(), buf.get());
505
    }
506
  }
507
508
  return Undefined(env->isolate());
509
}
510
511
1137
MaybeLocal<Value> GetKeyUsage(Environment* env, X509* cert) {
512
  StackOfASN1 eku(static_cast<STACK_OF(ASN1_OBJECT)*>(
513
2274
      X509_get_ext_d2i(cert, NID_ext_key_usage, nullptr, nullptr)));
514
1137
  if (eku) {
515
8
    const int count = sk_ASN1_OBJECT_num(eku.get());
516
16
    MaybeStackBuffer<Local<Value>, 16> ext_key_usage(count);
517
    char buf[256];
518
519
8
    int j = 0;
520
20
    for (int i = 0; i < count; i++) {
521
12
      if (OBJ_obj2txt(buf,
522
                      sizeof(buf),
523
12
                      sk_ASN1_OBJECT_value(eku.get(), i), 1) >= 0) {
524
24
        ext_key_usage[j++] = OneByteString(env->isolate(), buf);
525
      }
526
    }
527
528
16
    return Array::New(env->isolate(), ext_key_usage.out(), count);
529
  }
530
531
2258
  return Undefined(env->isolate());
532
}
533
534
2274
void AddFingerprintDigest(
535
    const unsigned char* md,
536
    unsigned int md_size,
537
    char (*fingerprint)[3 * EVP_MAX_MD_SIZE + 1]) {
538
  unsigned int i;
539
2274
  const char hex[] = "0123456789ABCDEF";
540
541
61398
  for (i = 0; i < md_size; i++) {
542
59124
    (*fingerprint)[3*i] = hex[(md[i] & 0xf0) >> 4];
543
59124
    (*fingerprint)[(3*i)+1] = hex[(md[i] & 0x0f)];
544
59124
    (*fingerprint)[(3*i)+2] = ':';
545
  }
546
547
2274
  if (md_size > 0) {
548
2274
    (*fingerprint)[(3*(md_size-1))+2] = '\0';
549
  } else {
550
    (*fingerprint)[0] = '\0';
551
  }
552
2274
}
553
554
72
bool SafeX509ExtPrint(const BIOPointer& out, X509_EXTENSION* ext) {
555
72
  const X509V3_EXT_METHOD* method = X509V3_EXT_get(ext);
556
557
72
  if (method != X509V3_EXT_get_nid(NID_subject_alt_name))
558
67
    return false;
559
560
5
  GENERAL_NAMES* names = static_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(ext));
561
5
  if (names == nullptr)
562
1
    return false;
563
564
16
  for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) {
565
12
    GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);
566
567
12
    if (i != 0)
568
8
      BIO_write(out.get(), ", ", 2);
569
570
12
    if (gen->type == GEN_DNS) {
571
9
      ASN1_IA5STRING* name = gen->d.dNSName;
572
573
9
      BIO_write(out.get(), "DNS:", 4);
574
9
      BIO_write(out.get(), name->data, name->length);
575
    } else {
576
      STACK_OF(CONF_VALUE)* nval = i2v_GENERAL_NAME(
577
3
          const_cast<X509V3_EXT_METHOD*>(method), gen, nullptr);
578
3
      if (nval == nullptr)
579
        return false;
580
3
      X509V3_EXT_val_prn(out.get(), nval, 0, 0);
581
3
      sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
582
    }
583
  }
584
4
  sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
585
586
4
  return true;
587
}
588
589
2274
MaybeLocal<Value> GetFingerprintDigest(
590
    Environment* env,
591
    const EVP_MD* method,
592
    X509* cert) {
593
  unsigned char md[EVP_MAX_MD_SIZE];
594
  unsigned int md_size;
595
  char fingerprint[EVP_MAX_MD_SIZE * 3 + 1];
596
597
2274
  if (X509_digest(cert, method, md, &md_size)) {
598
2274
    AddFingerprintDigest(md, md_size, &fingerprint);
599
4548
    return OneByteString(env->isolate(), fingerprint);
600
  }
601
  return Undefined(env->isolate());
602
}
603
604
1137
MaybeLocal<Value> GetValidTo(
605
    Environment* env,
606
    X509* cert,
607
    const BIOPointer& bio) {
608
1137
  ASN1_TIME_print(bio.get(), X509_get0_notAfter(cert));
609
2274
  return ToV8Value(env, bio);
610
}
611
612
1137
MaybeLocal<Value> GetValidFrom(
613
    Environment* env,
614
    X509* cert,
615
    const BIOPointer& bio) {
616
1137
  ASN1_TIME_print(bio.get(), X509_get0_notBefore(cert));
617
2274
  return ToV8Value(env, bio);
618
}
619
620
37
MaybeLocal<Value> GetCurveASN1Name(Environment* env, const int nid) {
621
37
  const char* nist = OBJ_nid2sn(nid);
622
  return nist != nullptr ?
623
      MaybeLocal<Value>(OneByteString(env->isolate(), nist)) :
624
74
      MaybeLocal<Value>(Undefined(env->isolate()));
625
}
626
627
37
MaybeLocal<Value> GetCurveNistName(Environment* env, const int nid) {
628
37
  const char* nist = EC_curve_nid2nist(nid);
629
  return nist != nullptr ?
630
      MaybeLocal<Value>(OneByteString(env->isolate(), nist)) :
631
74
      MaybeLocal<Value>(Undefined(env->isolate()));
632
}
633
634
37
MaybeLocal<Value> GetECPubKey(
635
    Environment* env,
636
    const EC_GROUP* group,
637
    const ECPointer& ec) {
638
37
  const EC_POINT* pubkey = EC_KEY_get0_public_key(ec.get());
639
37
  if (pubkey == nullptr)
640
    return Undefined(env->isolate());
641
642
74
  return ECPointToBuffer(
643
      env,
644
      group,
645
      pubkey,
646
37
      EC_KEY_get_conv_form(ec.get()),
647
111
      nullptr).FromMaybe(Local<Object>());
648
}
649
650
37
MaybeLocal<Value> GetECGroup(
651
    Environment* env,
652
    const EC_GROUP* group,
653
    const ECPointer& ec) {
654
37
  if (group == nullptr)
655
    return Undefined(env->isolate());
656
657
37
  int bits = EC_GROUP_order_bits(group);
658
37
  if (bits <= 0)
659
    return Undefined(env->isolate());
660
661
74
  return Integer::New(env->isolate(), bits);
662
}
663
664
1100
MaybeLocal<Object> GetPubKey(Environment* env, const RSAPointer& rsa) {
665
1100
  int size = i2d_RSA_PUBKEY(rsa.get(), nullptr);
666
1100
  CHECK_GE(size, 0);
667
668
2200
  AllocatedBuffer buffer = AllocatedBuffer::AllocateManaged(env, size);
669
  unsigned char* serialized =
670
1100
      reinterpret_cast<unsigned char*>(buffer.data());
671
1100
  i2d_RSA_PUBKEY(rsa.get(), &serialized);
672
2200
  return buffer.ToBuffer();
673
}
674
675
1100
MaybeLocal<Value> GetExponentString(
676
    Environment* env,
677
    const BIOPointer& bio,
678
    const BIGNUM* e) {
679
1100
  uint64_t exponent_word = static_cast<uint64_t>(BN_get_word(e));
680
1100
  uint32_t lo = static_cast<uint32_t>(exponent_word);
681
1100
  uint32_t hi = static_cast<uint32_t>(exponent_word >> 32);
682
1100
  if (hi == 0)
683
1100
    BIO_printf(bio.get(), "0x%x", lo);
684
  else
685
    BIO_printf(bio.get(), "0x%x%08x", hi, lo);
686
687
2200
  return ToV8Value(env, bio);
688
}
689
690
1100
Local<Value> GetBits(Environment* env, const BIGNUM* n) {
691
2200
  return Integer::New(env->isolate(), BN_num_bits(n));
692
}
693
694
1100
MaybeLocal<Value> GetModulusString(
695
    Environment* env,
696
    const BIOPointer& bio,
697
    const BIGNUM* n) {
698
1100
  BN_print(bio.get(), n);
699
2200
  return ToV8Value(env, bio);
700
}
701
702
template <int nid>
703
2274
MaybeLocal<Value> GetInfoString(
704
    Environment* env,
705
    const BIOPointer& bio,
706
    X509* cert) {
707
2274
  int index = X509_get_ext_by_NID(cert, nid, -1);
708

2274
  if (index < 0)
709
4404
    return Undefined(env->isolate());
710
711
72
  X509_EXTENSION* ext = X509_get_ext(cert, index);
712

72
  CHECK_NOT_NULL(ext);
713
714



140
  if (!SafeX509ExtPrint(bio, ext) &&
715
68
      X509V3_EXT_print(bio.get(), ext, 0, 0) != 1) {
716
1
    USE(BIO_reset(bio.get()));
717
2
    return Null(env->isolate());
718
  }
719
720
142
  return ToV8Value(env, bio);
721
}
722
723
1137
MaybeLocal<Value> GetIssuerString(
724
    Environment* env,
725
    const BIOPointer& bio,
726
    X509* cert) {
727
1137
  X509_NAME* issuer_name = X509_get_issuer_name(cert);
728
1137
  if (X509_NAME_print_ex(bio.get(), issuer_name, 0, X509_NAME_FLAGS) <= 0) {
729
    USE(BIO_reset(bio.get()));
730
    return Undefined(env->isolate());
731
  }
732
733
2274
  return ToV8Value(env, bio);
734
}
735
736
1137
MaybeLocal<Value> GetSubject(
737
    Environment* env,
738
    const BIOPointer& bio,
739
    X509* cert) {
740
1137
  if (X509_NAME_print_ex(
741
          bio.get(),
742
1137
          X509_get_subject_name(cert),
743
          0,
744
          X509_NAME_FLAGS) <= 0) {
745
    USE(BIO_reset(bio.get()));
746
    return Undefined(env->isolate());
747
  }
748
749
2274
  return ToV8Value(env, bio);
750
}
751
}  // namespace
752
753
49
MaybeLocal<Value> GetCipherName(Environment* env, const SSLPointer& ssl) {
754
49
  return GetCipherName(env, SSL_get_current_cipher(ssl.get()));
755
}
756
757
49
MaybeLocal<Value> GetCipherStandardName(
758
    Environment* env,
759
    const SSLPointer& ssl) {
760
49
  return GetCipherStandardName(env, SSL_get_current_cipher(ssl.get()));
761
}
762
763
49
MaybeLocal<Value> GetCipherVersion(Environment* env, const SSLPointer& ssl) {
764
49
  return GetCipherVersion(env, SSL_get_current_cipher(ssl.get()));
765
}
766
767
MaybeLocal<Array> GetClientHelloCiphers(
768
    Environment* env,
769
    const SSLPointer& ssl) {
770
  EscapableHandleScope scope(env->isolate());
771
  const unsigned char* buf;
772
  size_t len = SSL_client_hello_get0_ciphers(ssl.get(), &buf);
773
  size_t count = len / 2;
774
  MaybeStackBuffer<Local<Value>, 16> ciphers(count);
775
  int j = 0;
776
  for (size_t n = 0; n < len; n += 2) {
777
    const SSL_CIPHER* cipher = SSL_CIPHER_find(ssl.get(), buf);
778
    buf += 2;
779
    Local<Object> obj = Object::New(env->isolate());
780
    if (!Set(env->context(),
781
             obj,
782
             env->name_string(),
783
             GetCipherName(env, cipher)) ||
784
        !Set(env->context(),
785
             obj,
786
             env->standard_name_string(),
787
             GetCipherStandardName(env, cipher)) ||
788
        !Set(env->context(),
789
             obj,
790
             env->version_string(),
791
             GetCipherVersion(env, cipher))) {
792
      return MaybeLocal<Array>();
793
    }
794
    ciphers[j++] = obj;
795
  }
796
  Local<Array> ret = Array::New(env->isolate(), ciphers.out(), count);
797
  return scope.Escape(ret);
798
}
799
800
801
49
MaybeLocal<Object> GetCipherInfo(Environment* env, const SSLPointer& ssl) {
802
49
  EscapableHandleScope scope(env->isolate());
803
49
  Local<Object> info = Object::New(env->isolate());
804
805
196
  if (!Set<Value>(env->context(),
806
                  info,
807
                  env->name_string(),
808
49
                  GetCipherName(env, ssl)) ||
809
147
      !Set<Value>(env->context(),
810
                  info,
811
                  env->standard_name_string(),
812

98
                  GetCipherStandardName(env, ssl)) ||
813
147
      !Set<Value>(env->context(),
814
                  info,
815
                  env->version_string(),
816
                  GetCipherVersion(env, ssl))) {
817
    return MaybeLocal<Object>();
818
  }
819
820
49
  return scope.Escape(info);
821
}
822
823
797
MaybeLocal<Object> GetEphemeralKey(Environment* env, const SSLPointer& ssl) {
824
797
  CHECK_EQ(SSL_is_server(ssl.get()), 0);
825
  EVP_PKEY* raw_key;
826
827
797
  EscapableHandleScope scope(env->isolate());
828
797
  Local<Object> info = Object::New(env->isolate());
829
797
  if (!SSL_get_server_tmp_key(ssl.get(), &raw_key))
830
27
    return scope.Escape(info);
831
832
770
  Local<Context> context = env->context();
833
1540
  crypto::EVPKeyPointer key(raw_key);
834
835
770
  int kid = EVP_PKEY_id(key.get());
836
770
  int bits = EVP_PKEY_bits(key.get());
837
770
  switch (kid) {
838
    case EVP_PKEY_DH:
839

35
      if (!Set<String>(context, info, env->type_string(), env->dh_string()) ||
840
28
          !Set<Integer>(context,
841
               info,
842
               env->size_string(),
843
               Integer::New(env->isolate(), bits))) {
844
        return MaybeLocal<Object>();
845
      }
846
7
      break;
847
    case EVP_PKEY_EC:
848
    case EVP_PKEY_X25519:
849
    case EVP_PKEY_X448:
850
      {
851
        const char* curve_name;
852
763
        if (kid == EVP_PKEY_EC) {
853
10
          ECKeyPointer ec(EVP_PKEY_get1_EC_KEY(key.get()));
854
5
          int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec.get()));
855
5
          curve_name = OBJ_nid2sn(nid);
856
        } else {
857
758
          curve_name = OBJ_nid2sn(kid);
858
        }
859
3815
        if (!Set<String>(context,
860
                         info,
861
                         env->type_string(),
862
763
                         env->ecdh_string()) ||
863
3052
            !Set<String>(context,
864
                info,
865
                env->name_string(),
866

1526
                OneByteString(env->isolate(), curve_name)) ||
867
3052
            !Set<Integer>(context,
868
                 info,
869
                 env->size_string(),
870
                 Integer::New(env->isolate(), bits))) {
871
          return MaybeLocal<Object>();
872
        }
873
      }
874
763
      break;
875
  }
876
877
770
  return scope.Escape(info);
878
}
879
880
63
MaybeLocal<Object> ECPointToBuffer(Environment* env,
881
                                   const EC_GROUP* group,
882
                                   const EC_POINT* point,
883
                                   point_conversion_form_t form,
884
                                   const char** error) {
885
63
  size_t len = EC_POINT_point2oct(group, point, form, nullptr, 0, nullptr);
886
63
  if (len == 0) {
887
    if (error != nullptr) *error = "Failed to get public key length";
888
    return MaybeLocal<Object>();
889
  }
890
126
  AllocatedBuffer buf = AllocatedBuffer::AllocateManaged(env, len);
891
63
  len = EC_POINT_point2oct(group,
892
                           point,
893
                           form,
894
63
                           reinterpret_cast<unsigned char*>(buf.data()),
895
                           buf.size(),
896
63
                           nullptr);
897
63
  if (len == 0) {
898
    if (error != nullptr) *error = "Failed to get public key";
899
    return MaybeLocal<Object>();
900
  }
901
63
  return buf.ToBuffer();
902
}
903
904
436
MaybeLocal<Value> GetPeerCert(
905
    Environment* env,
906
    const SSLPointer& ssl,
907
    bool abbreviated,
908
    bool is_server) {
909
436
  ClearErrorOnReturn clear_error_on_return;
910
  Local<Object> result;
911
  MaybeLocal<Object> maybe_cert;
912
913
  // NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain`
914
  // contains the `peer_certificate`, but on server it doesn't.
915
872
  X509Pointer cert(is_server ? SSL_get_peer_certificate(ssl.get()) : nullptr);
916
436
  STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(ssl.get());
917


436
  if (!cert && (ssl_certs == nullptr || sk_X509_num(ssl_certs) == 0))
918
10
    return Undefined(env->isolate());
919
920
  // Short result requested.
921
431
  if (abbreviated) {
922
    maybe_cert =
923
44
        X509ToObject(env, cert ? cert.get() : sk_X509_value(ssl_certs, 0));
924
88
    return maybe_cert.ToLocal(&result) ? result : MaybeLocal<Value>();
925
  }
926
927
774
  StackOfX509 peer_certs = CloneSSLCerts(std::move(cert), ssl_certs);
928
387
  if (peer_certs == nullptr)
929
    return Undefined(env->isolate());
930
931
  // First and main certificate.
932
774
  X509Pointer first_cert(sk_X509_value(peer_certs.get(), 0));
933
387
  CHECK(first_cert);
934
774
  maybe_cert = X509ToObject(env, first_cert.release()).ToLocalChecked();
935
387
  if (!maybe_cert.ToLocal(&result))
936
    return MaybeLocal<Value>();
937
938
  Local<Object> issuer_chain;
939
  MaybeLocal<Object> maybe_issuer_chain;
940
941
  maybe_issuer_chain =
942
      AddIssuerChainToObject(
943
          &cert,
944
          result,
945
387
          std::move(peer_certs),
946
387
          env);
947
387
  if (!maybe_issuer_chain.ToLocal(&issuer_chain))
948
    return MaybeLocal<Value>();
949
950
  maybe_issuer_chain =
951
      GetLastIssuedCert(
952
          &cert,
953
          ssl,
954
          issuer_chain,
955
387
          env);
956
957
  issuer_chain.Clear();
958
387
  if (!maybe_issuer_chain.ToLocal(&issuer_chain))
959
    return MaybeLocal<Value>();
960
961
  // Last certificate should be self-signed.
962

1161
  if (X509_check_issued(cert.get(), cert.get()) == X509_V_OK &&
963
1161
      !Set<Object>(env->context(),
964
           issuer_chain,
965
           env->issuercert_string(),
966
           issuer_chain)) {
967
    return MaybeLocal<Value>();
968
  }
969
970
387
  return result;
971
}
972
973
1137
MaybeLocal<Object> X509ToObject(Environment* env, X509* cert) {
974
1137
  EscapableHandleScope scope(env->isolate());
975
1137
  Local<Context> context = env->context();
976
1137
  Local<Object> info = Object::New(env->isolate());
977
978
2274
  BIOPointer bio(BIO_new(BIO_s_mem()));
979
980
4548
  if (!Set<Value>(context,
981
                  info,
982
                  env->subject_string(),
983
1137
                  GetSubject(env, bio, cert)) ||
984
3411
      !Set<Value>(context,
985
                  info,
986
                  env->issuer_string(),
987
1137
                  GetIssuerString(env, bio, cert)) ||
988
3411
      !Set<Value>(context,
989
                  info,
990
                  env->subjectaltname_string(),
991

2274
                  GetInfoString<NID_subject_alt_name>(env, bio, cert)) ||
992
3411
      !Set<Value>(context,
993
                  info,
994
                  env->infoaccess_string(),
995
                  GetInfoString<NID_info_access>(env, bio, cert))) {
996
    return MaybeLocal<Object>();
997
  }
998
999
2274
  EVPKeyPointer pkey(X509_get_pubkey(cert));
1000
2274
  RSAPointer rsa;
1001
2274
  ECPointer ec;
1002
1137
  if (pkey) {
1003
1137
    switch (EVP_PKEY_id(pkey.get())) {
1004
      case EVP_PKEY_RSA:
1005
1100
        rsa.reset(EVP_PKEY_get1_RSA(pkey.get()));
1006
1100
        break;
1007
      case EVP_PKEY_EC:
1008
37
        ec.reset(EVP_PKEY_get1_EC_KEY(pkey.get()));
1009
37
        break;
1010
    }
1011
  }
1012
1013
1137
  if (rsa) {
1014
    const BIGNUM* n;
1015
    const BIGNUM* e;
1016
1100
    RSA_get0_key(rsa.get(), &n, &e, nullptr);
1017
4400
    if (!Set<Value>(context,
1018
                    info,
1019
                    env->modulus_string(),
1020
1100
                    GetModulusString(env, bio, n)) ||
1021
5500
        !Set<Value>(context, info, env->bits_string(), GetBits(env, n)) ||
1022
3300
        !Set<Value>(context,
1023
                    info,
1024
                    env->exponent_string(),
1025

2200
                    GetExponentString(env, bio, e)) ||
1026
3300
        !Set<Object>(context,
1027
                     info,
1028
                     env->pubkey_string(),
1029
                     GetPubKey(env, rsa))) {
1030
      return MaybeLocal<Object>();
1031
    }
1032
37
  } else if (ec) {
1033
37
    const EC_GROUP* group = EC_KEY_get0_group(ec.get());
1034
1035
148
    if (!Set<Value>(context,
1036
                    info,
1037
                    env->bits_string(),
1038

74
                    GetECGroup(env, group, ec)) ||
1039
111
        !Set<Value>(context,
1040
                    info,
1041
                    env->pubkey_string(),
1042
                    GetECPubKey(env, group, ec))) {
1043
      return MaybeLocal<Object>();
1044
    }
1045
1046
37
    const int nid = EC_GROUP_get_curve_name(group);
1047
37
    if (nid != 0) {
1048
      // Curve is well-known, get its OID and NIST nick-name (if it has one).
1049
1050
148
      if (!Set<Value>(context,
1051
                      info,
1052
                      env->asn1curve_string(),
1053

74
                      GetCurveASN1Name(env, nid)) ||
1054
111
          !Set<Value>(context,
1055
                      info,
1056
                      env->nistcurve_string(),
1057
                      GetCurveNistName(env, nid))) {
1058
        return MaybeLocal<Object>();
1059
      }
1060
    } else {
1061
      // Unnamed curves can be described by their mathematical properties,
1062
      // but aren't used much (at all?) with X.509/TLS. Support later if needed.
1063
    }
1064
  }
1065
1066
  // pkey, rsa, and ec pointers are no longer needed.
1067
1137
  pkey.reset();
1068
1137
  rsa.reset();
1069
1137
  ec.reset();
1070
1071
4548
  if (!Set<Value>(context,
1072
                  info,
1073
                  env->valid_from_string(),
1074

2274
                  GetValidFrom(env, cert, bio)) ||
1075
3411
      !Set<Value>(context,
1076
                  info,
1077
                  env->valid_to_string(),
1078
                  GetValidTo(env, cert, bio))) {
1079
    return MaybeLocal<Object>();
1080
  }
1081
1082
  // bio is no longer needed
1083
1137
  bio.reset();
1084
1085
4548
  if (!Set<Value>(context,
1086
                  info,
1087
                  env->fingerprint_string(),
1088
1137
                  GetFingerprintDigest(env, EVP_sha1(), cert)) ||
1089
3411
      !Set<Value>(context,
1090
                  info,
1091
                  env->fingerprint256_string(),
1092
1137
                  GetFingerprintDigest(env, EVP_sha256(), cert)) ||
1093
3411
      !Set<Value>(context,
1094
                  info,
1095
                  env->ext_key_usage_string(),
1096
1137
                  GetKeyUsage(env, cert)) ||
1097
3411
      !Set<Value>(context,
1098
                  info,
1099
                  env->serial_number_string(),
1100

2274
                  GetSerialNumber(env, cert)) ||
1101
3411
      !Set<Object>(context,
1102
                   info,
1103
                   env->raw_string(),
1104
                   GetRawDERCertificate(env, cert))) {
1105
    return MaybeLocal<Object>();
1106
  }
1107
1108
1137
  return scope.Escape(info);
1109
}
1110
1111
}  // namespace crypto
1112

13323
}  // namespace node