All files / lib _tls_common.js

94.46% Statements 307/325
93.62% Branches 132/141
100% Functions 5/5
94.46% Lines 307/325

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 3268x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 4529x 4529x 4529x 4529x 4529x 2019x 2x 4529x 8x 8x 2293x 2293x       2293x 2293x 390x 390x 376x 390x 390x 2265x 2265x 2265x 2265x 2265x 2265x 2293x 2293x 8x 2261x 2261x 57x 57x 57x 57x 57x 57x 2261x 8x 8x 8x 8x 8x 2293x 2293x 2293x 2293x 2293x 2293x 2293x 2293x 2293x 2293x 2293x 2293x 531x 86x 115x 115x 115x 531x 445x 445x 445x 2293x 1683x 1683x 2204x 2204x 2293x 840x 32x 51x 51x 51x 840x 808x 808x 808x 840x 2180x 2180x 2180x 2180x 2180x 2180x 2180x 2293x 829x 43x 56x 56x 56x 56x 56x 829x 786x 786x 786x 829x 2147x 2147x 2292x 8x     8x 8x     8x 8x 8x 2147x 2147x 2292x 3x         3x         3x 3x 3x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 3x 2144x 2293x 4x 4x 4x 2140x 2140x 2140x 2140x 2140x 2293x 2293x 2293x 2293x 2293x 2293x 2x 2x 2x 2x 2138x 2138x 2138x 2138x 2293x 2293x 2293x 2133x 2293x 2293x 2293x 2133x 2133x 2139x 12x 12x 2129x 2286x 10x 10x 10x 10x 2127x 2286x 2x       2x 2x 2x 2x 2126x 2245x 749x 749x 2126x 2286x 17x 17x 17x 17x 1x 2x 2x 2x 2x 1x 1x 1x 1x 2x 17x 16x 16x 16x 14x 16x 2x 2x 16x 17x 2120x 2120x 2120x 2120x 2285x 1278x 1278x 1278x 2120x 2286x 1x 1x 1x 1x 2286x 1x 1x 1x 1x 2118x 2118x 8x 8x 8x 8x 8x 8x 1155x 1155x 1145x 1149x 1155x 692x 692x 1149x 1152x 64x 64x 64x 64x 64x 126x 126x 126x 126x 64x 64x 1145x 8x  
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
'use strict';
 
const {
  ArrayIsArray,
  ObjectCreate,
} = primordials;
 
const { parseCertString } = require('internal/tls');
const { isArrayBufferView } = require('internal/util/types');
const tls = require('tls');
const {
  ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED,
  ERR_INVALID_ARG_TYPE,
  ERR_INVALID_OPT_VALUE,
  ERR_TLS_INVALID_PROTOCOL_VERSION,
  ERR_TLS_PROTOCOL_VERSION_CONFLICT,
} = require('internal/errors').codes;
const {
  SSL_OP_CIPHER_SERVER_PREFERENCE,
  TLS1_VERSION,
  TLS1_1_VERSION,
  TLS1_2_VERSION,
  TLS1_3_VERSION,
} = internalBinding('constants').crypto;
 
// Lazily loaded from internal/crypto/util.
let toBuf = null;
 
function toV(which, v, def) {
  if (v == null) v = def;
  if (v === 'TLSv1') return TLS1_VERSION;
  if (v === 'TLSv1.1') return TLS1_1_VERSION;
  if (v === 'TLSv1.2') return TLS1_2_VERSION;
  if (v === 'TLSv1.3') return TLS1_3_VERSION;
  throw new ERR_TLS_INVALID_PROTOCOL_VERSION(v, which);
}
 
const { SecureContext: NativeSecureContext } = internalBinding('crypto');
function SecureContext(secureProtocol, secureOptions, minVersion, maxVersion) {
  if (!(this instanceof SecureContext)) {
    return new SecureContext(secureProtocol, secureOptions, minVersion,
                             maxVersion);
  }
 
  if (secureProtocol) {
    if (minVersion != null)
      throw new ERR_TLS_PROTOCOL_VERSION_CONFLICT(minVersion, secureProtocol);
    if (maxVersion != null)
      throw new ERR_TLS_PROTOCOL_VERSION_CONFLICT(maxVersion, secureProtocol);
  }
 
  this.context = new NativeSecureContext();
  this.context.init(secureProtocol,
                    toV('minimum', minVersion, tls.DEFAULT_MIN_VERSION),
                    toV('maximum', maxVersion, tls.DEFAULT_MAX_VERSION));
 
  if (secureOptions) this.context.setOptions(secureOptions);
}
 
function validateKeyOrCertOption(name, value) {
  if (typeof value !== 'string' && !isArrayBufferView(value)) {
    throw new ERR_INVALID_ARG_TYPE(
      `options.${name}`,
      ['string', 'Buffer', 'TypedArray', 'DataView'],
      value
    );
  }
}
 
exports.SecureContext = SecureContext;
 
 
exports.createSecureContext = function createSecureContext(options) {
  if (!options) options = {};
 
  let secureOptions = options.secureOptions;
  if (options.honorCipherOrder)
    secureOptions |= SSL_OP_CIPHER_SERVER_PREFERENCE;
 
  const c = new SecureContext(options.secureProtocol, secureOptions,
                              options.minVersion, options.maxVersion);
 
  // Add CA before the cert to be able to load cert's issuer in C++ code.
  const { ca } = options;
  if (ca) {
    if (ArrayIsArray(ca)) {
      for (const val of ca) {
        validateKeyOrCertOption('ca', val);
        c.context.addCACert(val);
      }
    } else {
      validateKeyOrCertOption('ca', ca);
      c.context.addCACert(ca);
    }
  } else {
    c.context.addRootCerts();
  }
 
  const { cert } = options;
  if (cert) {
    if (ArrayIsArray(cert)) {
      for (const val of cert) {
        validateKeyOrCertOption('cert', val);
        c.context.setCert(val);
      }
    } else {
      validateKeyOrCertOption('cert', cert);
      c.context.setCert(cert);
    }
  }
 
  // Set the key after the cert.
  // `ssl_set_pkey` returns `0` when the key does not match the cert, but
  // `ssl_set_cert` returns `1` and nullifies the key in the SSL structure
  // which leads to the crash later on.
  const key = options.key;
  const passphrase = options.passphrase;
  if (key) {
    if (ArrayIsArray(key)) {
      for (const val of key) {
        // eslint-disable-next-line eqeqeq
        const pem = (val != undefined && val.pem !== undefined ? val.pem : val);
        validateKeyOrCertOption('key', pem);
        c.context.setKey(pem, val.passphrase || passphrase);
      }
    } else {
      validateKeyOrCertOption('key', key);
      c.context.setKey(key, passphrase);
    }
  }
 
  const sigalgs = options.sigalgs;
  if (sigalgs !== undefined) {
    if (typeof sigalgs !== 'string') {
      throw new ERR_INVALID_ARG_TYPE('options.sigalgs', 'string', sigalgs);
    }
 
    if (sigalgs === '') {
      throw new ERR_INVALID_OPT_VALUE('sigalgs', sigalgs);
    }
 
    c.context.setSigalgs(sigalgs);
  }
 
  const { privateKeyIdentifier, privateKeyEngine } = options;
  if (privateKeyIdentifier !== undefined) {
    if (privateKeyEngine === undefined) {
      // Engine is required when privateKeyIdentifier is present
      throw new ERR_INVALID_OPT_VALUE('privateKeyEngine',
                                      privateKeyEngine);
    }
    if (key) {
      // Both data key and engine key can't be set at the same time
      throw new ERR_INVALID_OPT_VALUE('privateKeyIdentifier',
                                      privateKeyIdentifier);
    }
 
    if (typeof privateKeyIdentifier === 'string' &&
        typeof privateKeyEngine === 'string') {
      if (c.context.setEngineKey)
        c.context.setEngineKey(privateKeyIdentifier, privateKeyEngine);
      else
        throw new ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED();
    } else if (typeof privateKeyIdentifier !== 'string') {
      throw new ERR_INVALID_ARG_TYPE('options.privateKeyIdentifier',
                                     ['string', 'undefined'],
                                     privateKeyIdentifier);
    } else {
      throw new ERR_INVALID_ARG_TYPE('options.privateKeyEngine',
                                     ['string', 'undefined'],
                                     privateKeyEngine);
    }
  }
 
  if (options.ciphers && typeof options.ciphers !== 'string') {
    throw new ERR_INVALID_ARG_TYPE(
      'options.ciphers', 'string', options.ciphers);
  }
 
  // Work around an OpenSSL API quirk. cipherList is for TLSv1.2 and below,
  // cipherSuites is for TLSv1.3 (and presumably any later versions). TLSv1.3
  // cipher suites all have a standard name format beginning with TLS_, so split
  // the ciphers and pass them to the appropriate API.
  const ciphers = (options.ciphers || tls.DEFAULT_CIPHERS).split(':');
  const cipherList = ciphers.filter((_) => !_.match(/^TLS_/) &&
                                    _.length > 0).join(':');
  const cipherSuites = ciphers.filter((_) => _.match(/^TLS_/)).join(':');
 
  if (cipherSuites === '' && cipherList === '') {
    // Specifying empty cipher suites for both TLS1.2 and TLS1.3 is invalid, its
    // not possible to handshake with no suites.
    throw new ERR_INVALID_OPT_VALUE('ciphers', ciphers);
  }
 
  c.context.setCipherSuites(cipherSuites);
  c.context.setCiphers(cipherList);
 
  if (cipherSuites === '' && c.context.getMaxProto() > TLS1_2_VERSION &&
      c.context.getMinProto() < TLS1_3_VERSION)
    c.context.setMaxProto(TLS1_2_VERSION);
 
  if (cipherList === '' && c.context.getMinProto() < TLS1_3_VERSION &&
      c.context.getMaxProto() > TLS1_2_VERSION)
    c.context.setMinProto(TLS1_3_VERSION);
 
  if (options.ecdhCurve === undefined)
    c.context.setECDHCurve(tls.DEFAULT_ECDH_CURVE);
  else if (options.ecdhCurve)
    c.context.setECDHCurve(options.ecdhCurve);
 
  if (options.dhparam) {
    const warning = c.context.setDHParam(options.dhparam);
    if (warning)
      process.emitWarning(warning, 'SecurityWarning');
  }
 
  if (options.crl) {
    if (ArrayIsArray(options.crl)) {
      for (const crl of options.crl) {
        c.context.addCRL(crl);
      }
    } else {
      c.context.addCRL(options.crl);
    }
  }
 
  if (options.sessionIdContext) {
    c.context.setSessionIdContext(options.sessionIdContext);
  }
 
  if (options.pfx) {
    if (!toBuf)
      toBuf = require('internal/crypto/util').toBuf;
 
    if (ArrayIsArray(options.pfx)) {
      for (const pfx of options.pfx) {
        const raw = pfx.buf ? pfx.buf : pfx;
        const buf = toBuf(raw);
        const passphrase = pfx.passphrase || options.passphrase;
        if (passphrase) {
          c.context.loadPKCS12(buf, toBuf(passphrase));
        } else {
          c.context.loadPKCS12(buf);
        }
      }
    } else {
      const buf = toBuf(options.pfx);
      const passphrase = options.passphrase;
      if (passphrase) {
        c.context.loadPKCS12(buf, toBuf(passphrase));
      } else {
        c.context.loadPKCS12(buf);
      }
    }
  }
 
  // Do not keep read/write buffers in free list for OpenSSL < 1.1.0. (For
  // OpenSSL 1.1.0, buffers are malloced and freed without the use of a
  // freelist.)
  if (options.singleUse) {
    c.singleUse = true;
    c.context.setFreeListLength(0);
  }
 
  if (typeof options.clientCertEngine === 'string') {
    if (c.context.setClientCertEngine)
      c.context.setClientCertEngine(options.clientCertEngine);
    else
      throw new ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED();
  } else if (options.clientCertEngine != null) {
    throw new ERR_INVALID_ARG_TYPE('options.clientCertEngine',
                                   ['string', 'null', 'undefined'],
                                   options.clientCertEngine);
  }
 
  return c;
};
 
// Translate some fields from the handle's C-friendly format into more idiomatic
// javascript object representations before passing them back to the user.  Can
// be used on any cert object, but changing the name would be semver-major.
exports.translatePeerCertificate = function translatePeerCertificate(c) {
  if (!c)
    return null;
 
  if (c.issuer != null) c.issuer = parseCertString(c.issuer);
  if (c.issuerCertificate != null && c.issuerCertificate !== c) {
    c.issuerCertificate = translatePeerCertificate(c.issuerCertificate);
  }
  if (c.subject != null) c.subject = parseCertString(c.subject);
  if (c.infoAccess != null) {
    const info = c.infoAccess;
    c.infoAccess = ObjectCreate(null);
 
    // XXX: More key validation?
    info.replace(/([^\n:]*):([^\n]*)(?:\n|$)/g, (all, key, val) => {
      if (key in c.infoAccess)
        c.infoAccess[key].push(val);
      else
        c.infoAccess[key] = [val];
    });
  }
  return c;
};