All files / lib/internal/tls secure-context.js

95.61% Statements 305/319
94.3% Branches 116/123
100% Functions 8/8
95.61% Lines 305/319

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 3208x 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 2424x 2424x 2424x 2424x 2424x 2424x 8x 896x 896x 896x 896x 896x 896x 8x 602x 602x 631x 631x 602x 602x 8x 939x 939x 958x 958x 939x 939x 8x 2542x 2542x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 2542x 8x 941x 941x 941x 941x 916x 941x 8x 2362x 2362x 2362x 2362x 2362x 2362x 2362x 2362x 45397x 45397x 2362x 2362x 2362x 2362x 2362x 2362x 2362x 45397x 45397x 2362x 2362x 2362x 2362x 2362x 2362x 2360x 2360x 2362x 8x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 2436x 602x 2436x 1834x 1834x 2426x 2436x 939x 939x 2402x 2402x 2402x 2402x 2402x 2436x 928x 43x 56x 56x 56x 56x 56x 56x 56x 928x 885x 885x 928x 2369x 2436x 8x 8x 8x 8x 8x 8x 8x 2369x 2436x 3x         3x         3x 3x 3x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 3x 2366x 2436x 2436x 2362x 2362x 2362x 2362x 2362x 2362x 2362x 2362x 2362x 2362x 2362x 2362x 2362x 2432x 2436x 2436x 146x 146x 2355x 2429x 2436x 2436x 11x 11x 2355x 2355x 2355x 2355x 2436x 10x 10x 10x 10x 10x 2349x 2436x 2x         2x 2x 2x 2x 2x 2348x 2436x 846x 846x 846x 2348x 2436x 17x 1x 2x 2x 2x 1x 1x 1x 1x 1x 17x 14x 16x 2x 2x 17x 2342x 2429x 1x 1x     2429x 1x 1x 1x 1x 2340x 2436x 8x 1x 1x 1x 1x 1x 7x 1x 1x 1x 1x 1x 6x 6x 2338x 2436x 2x 2x 2x 2436x 8x 8x 8x 8x  
'use strict';
 
const {
  ArrayIsArray,
  ArrayPrototypeFilter,
  ArrayPrototypeForEach,
  ArrayPrototypeJoin,
  StringPrototypeSplit,
  StringPrototypeStartsWith,
} = primordials;
 
const {
  codes: {
    ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED,
    ERR_INVALID_ARG_TYPE,
    ERR_INVALID_ARG_VALUE,
  },
} = require('internal/errors');
 
const {
  isArrayBufferView,
} = require('internal/util/types');
 
const {
  validateInt32,
  validateObject,
  validateString,
} = require('internal/validators');
 
const {
  toBuf,
} = require('internal/crypto/util');
 
const {
  crypto: {
    TLS1_2_VERSION,
    TLS1_3_VERSION,
  },
} = internalBinding('constants');
 
function getDefaultEcdhCurve() {
  // We do it this way because DEFAULT_ECDH_CURVE can be
  // changed by users, so we need to grab the current
  // value, but we want the evaluation to be lazy.
  return require('tls').DEFAULT_ECDH_CURVE || 'auto';
}
 
function getDefaultCiphers() {
  // We do it this way because DEFAULT_CIPHERS can be
  // changed by users, so we need to grab the current
  // value, but we want the evaluation to be lazy.
  return require('tls').DEFAULT_CIPHERS;
}
 
function addCACerts(context, certs, name) {
  ArrayPrototypeForEach(certs, (cert) => {
    validateKeyOrCertOption(name, cert);
    context.addCACert(cert);
  });
}
 
function setCerts(context, certs, name) {
  ArrayPrototypeForEach(certs, (cert) => {
    validateKeyOrCertOption(name, cert);
    context.setCert(cert);
  });
}
 
function validateKeyOrCertOption(name, value) {
  if (typeof value !== 'string' && !isArrayBufferView(value)) {
    throw new ERR_INVALID_ARG_TYPE(
      name,
      [
        'string',
        'Buffer',
        'TypedArray',
        'DataView',
      ],
      value
    );
  }
}
 
function setKey(context, key, passphrase, name) {
  validateKeyOrCertOption(`${name}.key`, key);
  if (passphrase !== undefined && passphrase !== null)
    validateString(passphrase, `${name}.passphrase`);
  context.setKey(key, passphrase);
}
 
function processCiphers(ciphers, name) {
  ciphers = StringPrototypeSplit(ciphers || getDefaultCiphers(), ':');
 
  const cipherList =
    ArrayPrototypeJoin(
      ArrayPrototypeFilter(
        ciphers,
        (cipher) => {
          return cipher.length > 0 &&
            !StringPrototypeStartsWith(cipher, 'TLS_');
        }), ':');
 
  const cipherSuites =
    ArrayPrototypeJoin(
      ArrayPrototypeFilter(
        ciphers,
        (cipher) => {
          return cipher.length > 0 &&
            StringPrototypeStartsWith(cipher, 'TLS_');
        }), ':');
 
  // Specifying empty cipher suites for both TLS1.2 and TLS1.3 is invalid, its
  // not possible to handshake with no suites.
  if (cipherSuites === '' && cipherList === '')
    throw new ERR_INVALID_ARG_VALUE(name, ciphers);
 
  return { cipherList, cipherSuites };
}
 
function configSecureContext(context, options = {}, name = 'options') {
  validateObject(options, name);
 
  const {
    ca,
    cert,
    ciphers = getDefaultCiphers(),
    clientCertEngine,
    crl,
    dhparam,
    ecdhCurve = getDefaultEcdhCurve(),
    key,
    passphrase,
    pfx,
    privateKeyIdentifier,
    privateKeyEngine,
    sessionIdContext,
    sessionTimeout,
    sigalgs,
    ticketKeys,
  } = options;
 
  // Add CA before the cert to be able to load cert's issuer in C++ code.
  // NOTE(@jasnell): ca, cert, and key are permitted to be falsy, so do not
  // change the checks to !== undefined checks.
  if (ca) {
    addCACerts(context, ArrayIsArray(ca) ? ca : [ca], `${name}.ca`);
  } else {
    context.addRootCerts();
  }
 
  if (cert) {
    setCerts(context, ArrayIsArray(cert) ? cert : [cert], `${name}.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.
  if (key) {
    if (ArrayIsArray(key)) {
      for (let i = 0; i < key.length; ++i) {
        const val = key[i];
        const pem = (
          val?.pem !== undefined ? val.pem : val);
        const pass = (
          val?.passphrase !== undefined ? val.passphrase : passphrase);
        setKey(context, pem, pass, name);
      }
    } else {
      setKey(context, key, passphrase, name);
    }
  }
 
  if (sigalgs !== undefined && sigalgs !== null) {
    validateString(sigalgs, `${name}.sigalgs`);
 
    if (sigalgs === '')
      throw new ERR_INVALID_ARG_VALUE(`${name}.sigalgs`, sigalgs);
 
    context.setSigalgs(sigalgs);
  }
 
  if (privateKeyIdentifier !== undefined && privateKeyIdentifier !== null) {
    if (privateKeyEngine === undefined || privateKeyEngine === null) {
      // Engine is required when privateKeyIdentifier is present
      throw new ERR_INVALID_ARG_VALUE(`${name}.privateKeyEngine`,
                                      privateKeyEngine);
    }
    if (key) {
      // Both data key and engine key can't be set at the same time
      throw new ERR_INVALID_ARG_VALUE(`${name}.privateKeyIdentifier`,
                                      privateKeyIdentifier);
    }
 
    if (typeof privateKeyIdentifier === 'string' &&
        typeof privateKeyEngine === 'string') {
      if (context.setEngineKey)
        context.setEngineKey(privateKeyIdentifier, privateKeyEngine);
      else
        throw new ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED();
    } else if (typeof privateKeyIdentifier !== 'string') {
      throw new ERR_INVALID_ARG_TYPE(`${name}.privateKeyIdentifier`,
                                     ['string', 'null', 'undefined'],
                                     privateKeyIdentifier);
    } else {
      throw new ERR_INVALID_ARG_TYPE(`${name}.privateKeyEngine`,
                                     ['string', 'null', 'undefined'],
                                     privateKeyEngine);
    }
  }
 
  if (ciphers !== undefined && ciphers !== null)
    validateString(ciphers, `${name}.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 {
    cipherList,
    cipherSuites,
  } = processCiphers(ciphers, `${name}.ciphers`);
 
  context.setCipherSuites(cipherSuites);
  context.setCiphers(cipherList);
 
  if (cipherSuites === '' &&
      context.getMaxProto() > TLS1_2_VERSION &&
      context.getMinProto() < TLS1_3_VERSION) {
    context.setMaxProto(TLS1_2_VERSION);
  }
 
  if (cipherList === '' &&
      context.getMinProto() < TLS1_3_VERSION &&
      context.getMaxProto() > TLS1_2_VERSION) {
    context.setMinProto(TLS1_3_VERSION);
  }
 
  validateString(ecdhCurve, `${name}.ecdhCurve`);
  context.setECDHCurve(ecdhCurve);
 
  if (dhparam !== undefined && dhparam !== null) {
    validateKeyOrCertOption(`${name}.dhparam`, dhparam);
    const warning = context.setDHParam(dhparam);
    if (warning)
      process.emitWarning(warning, 'SecurityWarning');
  }
 
  if (crl !== undefined && crl !== null) {
    if (ArrayIsArray(crl)) {
      for (const val of crl) {
        validateKeyOrCertOption(`${name}.crl`, val);
        context.addCRL(val);
      }
    } else {
      validateKeyOrCertOption(`${name}.crl`, crl);
      context.addCRL(crl);
    }
  }
 
  if (sessionIdContext !== undefined && sessionIdContext !== null) {
    validateString(sessionIdContext, `${name}.sessionIdContext`);
    context.setSessionIdContext(sessionIdContext);
  }
 
  if (pfx !== undefined && pfx !== null) {
    if (ArrayIsArray(pfx)) {
      ArrayPrototypeForEach(pfx, (val) => {
        const raw = val.buf ? val.buf : val;
        const pass = val.passphrase || passphrase;
        if (pass !== undefined && pass !== null) {
          context.loadPKCS12(toBuf(raw), toBuf(pass));
        } else {
          context.loadPKCS12(toBuf(raw));
        }
      });
    } else if (passphrase) {
      context.loadPKCS12(toBuf(pfx), toBuf(passphrase));
    } else {
      context.loadPKCS12(toBuf(pfx));
    }
  }
 
  if (typeof clientCertEngine === 'string') {
    if (typeof context.setClientCertEngine !== 'function')
      throw new ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED();
    else
      context.setClientCertEngine(clientCertEngine);
  } else if (clientCertEngine !== undefined && clientCertEngine !== null) {
    throw new ERR_INVALID_ARG_TYPE(`${name}.clientCertEngine`,
                                   ['string', 'null', 'undefined'],
                                   clientCertEngine);
  }
 
  if (ticketKeys !== undefined && ticketKeys !== null) {
    if (!isArrayBufferView(ticketKeys)) {
      throw new ERR_INVALID_ARG_TYPE(
        `${name}.ticketKeys`,
        ['Buffer', 'TypedArray', 'DataView'],
        ticketKeys);
    }
    if (ticketKeys.byteLength !== 48) {
      throw new ERR_INVALID_ARG_VALUE(
        `${name}.ticketKeys`,
        ticketKeys.byteLength,
        'must be exactly 48 bytes');
    }
    context.setTicketKeys(ticketKeys);
  }
 
  if (sessionTimeout !== undefined && sessionTimeout !== null) {
    validateInt32(sessionTimeout, `${name}.sessionTimeout`);
    context.setSessionTimeout(sessionTimeout);
  }
}
 
module.exports = {
  configSecureContext,
};