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: 371 558 66.5 %
Date: 2020-06-24 22:13:30 Branches: 192 407 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
130
bool SetTLSSession(
121
    const SSLPointer& ssl,
122
    const SSLSessionPointer& session) {
123

130
  return session != nullptr && SSL_set_session(ssl.get(), session.get()) == 1;
124
}
125
126
130
SSLSessionPointer GetTLSSession(Local<Value> val) {
127
130
  if (!val->IsArrayBufferView())
128
    return SSLSessionPointer();
129
130
  ArrayBufferViewContents<unsigned char> sbuf(val.As<ArrayBufferView>());
130
130
  return GetTLSSession(sbuf.data(), sbuf.length());
131
}
132
133
130
SSLSessionPointer GetTLSSession(const unsigned char* buf, size_t length) {
134
130
  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
880
long VerifyPeerCertificate(  // NOLINT(runtime/int)
208
    const SSLPointer& ssl,
209
    long def) {  // NOLINT(runtime/int)
210
880
  long err = def;  // NOLINT(runtime/int)
211
880
  if (X509* peer_cert = SSL_get_peer_certificate(ssl.get())) {
212
872
    X509_free(peer_cert);
213
872
    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
873
  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
  Local<Value> ret;
354
11
  MaybeLocal<Object> maybe_cert = X509ToObject(env, cert);
355
22
  return maybe_cert.ToLocal(&ret) ? ret : MaybeLocal<Value>();
356
}
357
358
namespace {
359
template <typename T>
360
20587
bool Set(
361
    Local<Context> context,
362
    Local<Object> target,
363
    Local<Value> name,
364
    MaybeLocal<T> maybe_value) {
365
  Local<Value> value;
366


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


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

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

2274
  if (index < 0)
714
4404
    return Undefined(env->isolate());
715
716
72
  X509_EXTENSION* ext = X509_get_ext(cert, index);
717

72
  CHECK_NOT_NULL(ext);
718
719



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

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

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

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


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

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

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

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

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

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

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

2274
                  GetSerialNumber(env, cert)) ||
1106
3411
      !Set<Object>(context,
1107
                   info,
1108
                   env->raw_string(),
1109
                   GetRawDERCertificate(env, cert))) {
1110
    return MaybeLocal<Object>();
1111
  }
1112
1113
1137
  return scope.Escape(info);
1114
}
1115
1116
}  // namespace crypto
1117
}  // namespace node