All files / lib/internal/crypto util.js

97.08% Statements 432/445
87.5% Branches 77/88
100% Functions 19/19
97.08% Lines 432/445

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 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 12360x 12360x 12360x 12360x 12360x 12360x 105x 105x 105x 2460x 2460x 2460x 105x 105x 105x 105x 4x 4x 4x 105x 103517x 103517x 103517x 105x 105x 105x 105x 2444x 2444x 333x 333x 333x 333x 2111x 2444x 105x 105x 105x 105x 105x 4x 4x 4x 4x 2x 2x 2x 2x 4x 2x 2x 2x 4x 105x 105x 112646x 112646x 112646x 1226x 1226x 1226x 1226x 112446x 159x 159x 159x 159x 159x 159x 159x 159x 159x 159x 159x 159x 109863x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 920x 920x         920x 105x 10985x 10985x 10977x 10977x 10977x 10977x 10956x 10956x 10956x 10934x 10934x 10956x 475x 475x 10956x 4003x 4003x 4003x 4003x 9573x 9573x 9573x 9573x 9573x 9573x 10977x 29x 10985x 105x 1733x 1733x 1733x 2367x 1709x 1733x 105x 87x 87x 87x 87x 87x 87x           87x 87x 105x 158x 158x 8x 8x 8x 8x 158x 105x 105x 1092x 1092x 1092x 1092x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 105x 105x 1060x 1060x 1042x 1060x 105x 1060x 1060x 1060x 1060x 1060x 1060x 105x 105x 105x 105x 105x 105x 105x 105x 38x 38x 38x 38x 112x 112x 112x 112x 112x 38x 38x 38x 105x 6x 6x 6x 6x 14x 14x 14x 6x 6x 6x 105x 1487x 1487x 1487x 1487x 1487x 1487x 105x 169x 169x 169x 190x 190x 190x 169x 169x 105x 52x 52x 52x 52x 52x 52x 52x 52x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 258x 258x 66x 66x 66x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 66x 66x 66x 81x         81x 66x 258x 105x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x  
'use strict';
 
const {
  ArrayPrototypeIncludes,
  ArrayPrototypePush,
  BigInt,
  FunctionPrototypeBind,
  Number,
  ObjectKeys,
  Promise,
  StringPrototypeToLowerCase,
  Symbol,
} = primordials;
 
const {
  getCiphers: _getCiphers,
  getCurves: _getCurves,
  getHashes: _getHashes,
  setEngine: _setEngine,
  secureHeapUsed: _secureHeapUsed,
} = internalBinding('crypto');
 
const { getOptionValue } = require('internal/options');
 
const {
  crypto: {
    ENGINE_METHOD_ALL
  }
} = internalBinding('constants');
 
const normalizeHashName = require('internal/crypto/hashnames');
 
const {
  hideStackFrames,
  codes: {
    ERR_CRYPTO_ENGINE_UNKNOWN,
    ERR_INVALID_ARG_TYPE,
    ERR_INVALID_ARG_VALUE,
    ERR_OUT_OF_RANGE,
  }
} = require('internal/errors');
 
const {
  validateArray,
  validateNumber,
  validateString
} = require('internal/validators');
 
const { Buffer } = require('buffer');
 
const {
  cachedResult,
  filterDuplicateStrings,
} = require('internal/util');
 
const {
  isArrayBufferView,
  isAnyArrayBuffer,
} = require('internal/util/types');
 
const kHandle = Symbol('kHandle');
const kKeyObject = Symbol('kKeyObject');
 
const lazyRequireCache = {};
 
function lazyRequire(name) {
  let ret = lazyRequireCache[name];
  if (ret === undefined)
    ret = lazyRequireCache[name] = require(name);
  return ret;
}
 
let DOMException;
const lazyDOMException = hideStackFrames((message, name) => {
  if (DOMException === undefined)
    DOMException = internalBinding('messaging').DOMException;
  return new DOMException(message, name);
});
 
var defaultEncoding = 'buffer';
 
function setDefaultEncoding(val) {
  defaultEncoding = val;
}
 
function getDefaultEncoding() {
  return defaultEncoding;
}
 
// This is here because many functions accepted binary strings without
// any explicit encoding in older versions of node, and we don't want
// to break them unnecessarily.
function toBuf(val, encoding) {
  if (typeof val === 'string') {
    if (encoding === 'buffer')
      encoding = 'utf8';
    return Buffer.from(val, encoding);
  }
  return val;
}
 
const getCiphers = cachedResult(() => filterDuplicateStrings(_getCiphers()));
const getHashes = cachedResult(() => filterDuplicateStrings(_getHashes()));
const getCurves = cachedResult(() => filterDuplicateStrings(_getCurves()));
 
function setEngine(id, flags) {
  validateString(id, 'id');
  if (flags)
    validateNumber(flags, 'flags');
  flags = flags >>> 0;
 
  // Use provided engine for everything by default
  if (flags === 0)
    flags = ENGINE_METHOD_ALL;
 
  if (!_setEngine(id, flags))
    throw new ERR_CRYPTO_ENGINE_UNKNOWN(id);
}
 
const getArrayBufferOrView = hideStackFrames((buffer, name, encoding) => {
  if (isAnyArrayBuffer(buffer))
    return buffer;
  if (typeof buffer === 'string') {
    if (encoding === 'buffer')
      encoding = 'utf8';
    return Buffer.from(buffer, encoding);
  }
  if (!isArrayBufferView(buffer)) {
    throw new ERR_INVALID_ARG_TYPE(
      name,
      [
        'string',
        'ArrayBuffer',
        'Buffer',
        'TypedArray',
        'DataView',
      ],
      buffer
    );
  }
  return buffer;
});
 
// The maximum buffer size that we'll support in the WebCrypto impl
const kMaxBufferLength = (2 ** 31) - 1;
 
// The EC named curves that we currently support via the Web Crypto API.
const kNamedCurveAliases = {
  'P-256': 'prime256v1',
  'P-384': 'secp384r1',
  'P-521': 'secp521r1',
  'NODE-ED25519': 'ed25519',
  'NODE-ED448': 'ed448',
  'NODE-X25519': 'x25519',
  'NODE-X448': 'x448',
};
 
const kAesKeyLengths = [128, 192, 256];
 
// These are the only algorithms we currently support
// via the Web Crypto API
const kAlgorithms = {
  'rsassa-pkcs1-v1_5': 'RSASSA-PKCS1-v1_5',
  'rsa-pss': 'RSA-PSS',
  'rsa-oaep': 'RSA-OAEP',
  'ecdsa': 'ECDSA',
  'ecdh': 'ECDH',
  'aes-ctr': 'AES-CTR',
  'aes-cbc': 'AES-CBC',
  'aes-gcm': 'AES-GCM',
  'aes-kw': 'AES-KW',
  'hmac': 'HMAC',
  'sha-1': 'SHA-1',
  'sha-256': 'SHA-256',
  'sha-384': 'SHA-384',
  'sha-512': 'SHA-512',
  'hkdf': 'HKDF',
  'pbkdf2': 'PBKDF2',
  // Following here are Node.js specific extensions. All
  // should be prefixed with 'node-'
  'node-dsa': 'NODE-DSA',
  'node-dh': 'NODE-DH',
  'node-scrypt': 'NODE-SCRYPT',
  'node-ed25519': 'NODE-ED25519',
  'node-ed448': 'NODE-ED448',
};
const kAlgorithmsKeys = ObjectKeys(kAlgorithms);
 
// These are the only export and import formats we currently
// support via the Web Crypto API
const kExportFormats = [
  'raw',
  'pkcs8',
  'spki',
  'jwk',
  'node.keyObject'];
 
// These are the only hash algorithms we currently support via
// the Web Crypto API.
const kHashTypes = [
  'SHA-1',
  'SHA-256',
  'SHA-384',
  'SHA-512',
];
 
function validateMaxBufferLength(data, name) {
  if (data.byteLength > kMaxBufferLength) {
    throw lazyDOMException(
      `${name} must be less than ${kMaxBufferLength + 1} bits`,
      'OperationError');
  }
}
 
function normalizeAlgorithm(algorithm, label = 'algorithm') {
  if (algorithm != null) {
    if (typeof algorithm === 'string')
      algorithm = { name: algorithm };
 
    if (typeof algorithm === 'object') {
      const { name } = algorithm;
      let hash;
      if (typeof name !== 'string' ||
          !ArrayPrototypeIncludes(
            kAlgorithmsKeys,
            StringPrototypeToLowerCase(name))) {
        throw lazyDOMException('Unrecognized name.', 'NotSupportedError');
      }
      if (algorithm.hash !== undefined) {
        hash = normalizeAlgorithm(algorithm.hash, 'algorithm.hash');
        if (!ArrayPrototypeIncludes(kHashTypes, hash.name))
          throw lazyDOMException('Unrecognized name.', 'NotSupportedError');
      }
      return {
        ...algorithm,
        name: kAlgorithms[StringPrototypeToLowerCase(name)],
        hash,
      };
    }
  }
  throw lazyDOMException('Unrecognized name.', 'NotSupportedError');
}
 
function hasAnyNotIn(set, checks) {
  for (const s of set)
    if (!ArrayPrototypeIncludes(checks, s))
      return true;
  return false;
}
 
function validateBitLength(length, name, required = false) {
  if (length !== undefined || required) {
    validateNumber(length, name);
    if (length < 0)
      throw new ERR_OUT_OF_RANGE(name, '> 0');
    if (length % 8) {
      throw new ERR_INVALID_ARG_VALUE(
        name,
        length,
        'must be a multiple of 8');
    }
  }
}
 
function validateByteLength(buf, name, target) {
  if (buf.byteLength !== target) {
    throw lazyDOMException(
      `${name} must contain exactly ${target} bytes`,
      'OperationError');
  }
}
 
const validateByteSource = hideStackFrames((val, name) => {
  val = toBuf(val);
 
  if (isAnyArrayBuffer(val) || isArrayBufferView(val))
    return;
 
  throw new ERR_INVALID_ARG_TYPE(
    name,
    [
      'string',
      'ArrayBuffer',
      'TypedArray',
      'DataView',
      'Buffer',
    ],
    val);
});
 
function onDone(resolve, reject, err, result) {
  if (err) return reject(err);
  resolve(result);
}
 
function jobPromise(job) {
  return new Promise((resolve, reject) => {
    job.ondone = FunctionPrototypeBind(onDone, job, resolve, reject);
    job.run();
  });
}
 
// In WebCrypto, the publicExponent option in RSA is represented as a
// WebIDL "BigInteger"... that is, a Uint8Array that allows an arbitrary
// number of leading zero bits. Our conventional APIs for reading
// an unsigned int from a Buffer are not adequate. The implementation
// here is adapted from the chromium implementation here:
// https://github.com/chromium/chromium/blob/HEAD/third_party/blink/public/platform/web_crypto_algorithm_params.h, but ported to JavaScript
// Returns undefined if the conversion was unsuccessful.
function bigIntArrayToUnsignedInt(input) {
  let result = 0;
 
  for (let n = 0; n < input.length; ++n) {
    const n_reversed = input.length - n - 1;
    if (n_reversed >= 4 && input[n])
      return;  // Too large
    result |= input[n] << 8 * n_reversed;
  }
 
  return result;
}
 
function bigIntArrayToUnsignedBigInt(input) {
  let result = 0n;
 
  for (let n = 0; n < input.length; ++n) {
    const n_reversed = input.length - n - 1;
    result |= BigInt(input[n]) << 8n * BigInt(n_reversed);
  }
 
  return result;
}
 
function getStringOption(options, key) {
  let value;
  if (options && (value = options[key]) != null)
    validateString(value, `options.${key}`);
  return value;
}
 
function getUsagesUnion(usageSet, ...usages) {
  const newset = [];
  for (let n = 0; n < usages.length; n++) {
    if (usageSet.has(usages[n]))
      ArrayPrototypePush(newset, usages[n]);
  }
  return newset;
}
 
function getHashLength(name) {
  switch (name) {
    case 'SHA-1': return 160;
    case 'SHA-256': return 256;
    case 'SHA-384': return 384;
    case 'SHA-512': return 512;
  }
}
 
const kKeyOps = {
  sign: 1,
  verify: 2,
  encrypt: 3,
  decrypt: 4,
  wrapKey: 5,
  unwrapKey: 6,
  deriveKey: 7,
  deriveBits: 8,
};
 
function validateKeyOps(keyOps, usagesSet) {
  if (keyOps === undefined) return;
  validateArray(keyOps, 'keyData.key_ops');
  let flags = 0;
  for (let n = 0; n < keyOps.length; n++) {
    const op = keyOps[n];
    const op_flag = kKeyOps[op];
    // Skipping unknown key ops
    if (op_flag === undefined)
      continue;
    // Have we seen it already? if so, error
    if (flags & (1 << op_flag))
      throw lazyDOMException('Duplicate key operation', 'DataError');
    flags |= (1 << op_flag);
 
    // TODO(@jasnell): RFC7517 section 4.3 strong recommends validating
    // key usage combinations. Specifically, it says that unrelated key
    // ops SHOULD NOT be used together. We're not yet validating that here.
  }
 
  if (usagesSet !== undefined) {
    for (const use of usagesSet) {
      if (!ArrayPrototypeIncludes(keyOps, use)) {
        throw lazyDOMException(
          'Key operations and usage mismatch',
          'DataError');
      }
    }
  }
}
 
function secureHeapUsed() {
  const val = _secureHeapUsed();
  if (val === undefined)
    return { total: 0, used: 0, utilization: 0, min: 0 };
  const used = Number(_secureHeapUsed());
  const total = Number(getOptionValue('--secure-heap'));
  const min = Number(getOptionValue('--secure-heap-min'));
  const utilization = used / total;
  return { total, used, utilization, min };
}
 
module.exports = {
  getArrayBufferOrView,
  getCiphers,
  getCurves,
  getDefaultEncoding,
  getHashes,
  kHandle,
  kKeyObject,
  setDefaultEncoding,
  setEngine,
  toBuf,
 
  kHashTypes,
  kNamedCurveAliases,
  kAesKeyLengths,
  kExportFormats,
  normalizeAlgorithm,
  normalizeHashName,
  hasAnyNotIn,
  lazyDOMException,
  validateBitLength,
  validateByteLength,
  validateByteSource,
  validateKeyOps,
  jobPromise,
  lazyRequire,
  validateMaxBufferLength,
  bigIntArrayToUnsignedBigInt,
  bigIntArrayToUnsignedInt,
  getStringOption,
  getUsagesUnion,
  getHashLength,
  secureHeapUsed,
};