All files / lib/internal/crypto aes.js

92.58% Statements 337/364
80.28% Branches 57/71
100% Functions 10/10
92.58% Lines 337/364

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 36522x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 447x 447x 447x 447x 447x 447x 447x 447x 22x 2189x 2189x 2189x 2189x 22x 1037x 1037x 1037x 251x 251x 251x 251x 251x 251x 1037x 236x 236x 236x 236x 236x 236x 1037x 474x 474x 474x 474x 474x   1037x 76x 76x 76x 76x 76x 76x 1037x 1037x 22x 256x 256x 256x 256x 256x 256x 256x 256x 20x 20x 20x 20x 236x 236x 236x 236x 236x 236x 236x 236x 236x 256x 22x 271x 271x 271x 271x 271x 271x 271x 271x 271x 271x 271x 22x 76x 76x 76x 76x 76x 76x 76x 76x 22x 535x 535x 535x 535x 535x 535x 60x 60x 60x 60x 535x 535x 535x 535x 535x 318x 318x 318x 318x 535x 535x 535x 535x 535x 229x 229x 229x 229x 229x 229x 229x 229x 229x 1x 1x 1x 1x 229x 229x 229x 229x 535x 246x 246x 535x 474x 474x 474x 474x 474x 474x 474x 474x 474x 474x 535x 22x 1138x 1138x 1138x 1138x 1138x 1138x 1138x 1138x 22x 1505x 1505x 1505x 1505x 1505x 1505x 1505x 1505x 676x 676x 676x 676x 1505x 85x 85x           85x 85x 85x 85x 85x 85x 85x 1505x 1505x 22x 1213x 1213x 1213x 1213x 1213x 1213x 1213x 1213x 1213x 1213x 1213x 1213x 1213x         1213x 1213x 1213x 1213x 1213x                         1213x 992x 992x 992x 992x 1213x 221x 221x 221x 221x 221x 221x 221x 221x 221x     221x 221x 221x 221x 221x 221x 16x 16x 221x 221x 221x 221x 221x 221x 221x 221x 221x 221x 221x 221x 221x 221x 221x 221x 221x 1213x       1213x 1197x 1213x 992x 992x 992x 1213x 1213x 1213x 1213x 1213x 1213x 1213x 22x 22x 22x 22x 22x 22x 22x  
'use strict';
 
const {
  ArrayBufferIsView,
  ArrayBufferPrototypeSlice,
  ArrayFrom,
  ArrayPrototypeIncludes,
  ArrayPrototypePush,
  MathFloor,
  Promise,
  SafeSet,
  TypedArrayPrototypeSlice,
} = primordials;
 
const {
  AESCipherJob,
  KeyObjectHandle,
  kCryptoJobAsync,
  kKeyVariantAES_CTR_128,
  kKeyVariantAES_CBC_128,
  kKeyVariantAES_GCM_128,
  kKeyVariantAES_KW_128,
  kKeyVariantAES_CTR_192,
  kKeyVariantAES_CBC_192,
  kKeyVariantAES_GCM_192,
  kKeyVariantAES_KW_192,
  kKeyVariantAES_CTR_256,
  kKeyVariantAES_CBC_256,
  kKeyVariantAES_GCM_256,
  kKeyVariantAES_KW_256,
  kWebCryptoCipherDecrypt,
  kWebCryptoCipherEncrypt,
} = internalBinding('crypto');
 
const {
  getArrayBufferOrView,
  hasAnyNotIn,
  jobPromise,
  validateByteLength,
  validateKeyOps,
  validateMaxBufferLength,
  kAesKeyLengths,
  kHandle,
  kKeyObject,
} = require('internal/crypto/util');
 
const {
  lazyDOMException,
} = require('internal/util');
 
const { PromiseReject } = primordials;
 
const {
  codes: {
    ERR_INVALID_ARG_TYPE,
  }
} = require('internal/errors');
 
const {
  InternalCryptoKey,
  SecretKeyObject,
  createSecretKey,
  isKeyObject,
} = require('internal/crypto/keys');
 
const {
  generateKey,
} = require('internal/crypto/keygen');
 
const {
  validateInteger,
  validateOneOf,
} = require('internal/validators');
 
const kMaxCounterLength = 128;
const kTagLengths = [32, 64, 96, 104, 112, 120, 128];
 
function getAlgorithmName(name, length) {
  switch (name) {
    case 'AES-CBC': return `A${length}CBC`;
    case 'AES-CTR': return `A${length}CTR`;
    case 'AES-GCM': return `A${length}GCM`;
    case 'AES-KW': return `A${length}KW`;
  }
}
 
function validateKeyLength(length) {
  if (length !== 128 && length !== 192 && length !== 256)
    throw lazyDOMException('Invalid key length', 'DataError');
}
 
function getVariant(name, length) {
  switch (name) {
    case 'AES-CBC':
      switch (length) {
        case 128: return kKeyVariantAES_CBC_128;
        case 192: return kKeyVariantAES_CBC_192;
        case 256: return kKeyVariantAES_CBC_256;
      }
      break;
    case 'AES-CTR':
      switch (length) {
        case 128: return kKeyVariantAES_CTR_128;
        case 192: return kKeyVariantAES_CTR_192;
        case 256: return kKeyVariantAES_CTR_256;
      }
      break;
    case 'AES-GCM':
      switch (length) {
        case 128: return kKeyVariantAES_GCM_128;
        case 192: return kKeyVariantAES_GCM_192;
        case 256: return kKeyVariantAES_GCM_256;
      }
      break;
    case 'AES-KW':
      switch (length) {
        case 128: return kKeyVariantAES_KW_128;
        case 192: return kKeyVariantAES_KW_192;
        case 256: return kKeyVariantAES_KW_256;
      }
      break;
  }
}
 
function asyncAesCtrCipher(mode, key, data, { counter, length }) {
  counter = getArrayBufferOrView(counter, 'algorithm.counter');
  validateByteLength(counter, 'algorithm.counter', 16);
  // The length must specify an integer between 1 and 128. While
  // there is no default, this should typically be 64.
  if (typeof length !== 'number' ||
      length <= 0 ||
      length > kMaxCounterLength) {
    throw lazyDOMException(
      'AES-CTR algorithm.length must be between 1 and 128',
      'OperationError');
  }
 
  return jobPromise(new AESCipherJob(
    kCryptoJobAsync,
    mode,
    key[kKeyObject][kHandle],
    data,
    getVariant('AES-CTR', key.algorithm.length),
    counter,
    length));
}
 
function asyncAesCbcCipher(mode, key, data, { iv }) {
  iv = getArrayBufferOrView(iv, 'algorithm.iv');
  validateByteLength(iv, 'algorithm.iv', 16);
  return jobPromise(new AESCipherJob(
    kCryptoJobAsync,
    mode,
    key[kKeyObject][kHandle],
    data,
    getVariant('AES-CBC', key.algorithm.length),
    iv));
}
 
function asyncAesKwCipher(mode, key, data) {
  return jobPromise(new AESCipherJob(
    kCryptoJobAsync,
    mode,
    key[kKeyObject][kHandle],
    data,
    getVariant('AES-KW', key.algorithm.length)));
}
 
function asyncAesGcmCipher(
  mode,
  key,
  data,
  { iv, additionalData, tagLength = 128 }) {
  if (!ArrayPrototypeIncludes(kTagLengths, tagLength)) {
    return PromiseReject(lazyDOMException(
      `${tagLength} is not a valid AES-GCM tag length`,
      'OperationError'));
  }
 
  iv = getArrayBufferOrView(iv, 'algorithm.iv');
  validateMaxBufferLength(iv, 'algorithm.iv');
 
  if (additionalData !== undefined) {
    additionalData =
      getArrayBufferOrView(additionalData, 'algorithm.additionalData');
    validateMaxBufferLength(additionalData, 'algorithm.additionalData');
  }
 
  const tagByteLength = MathFloor(tagLength / 8);
  let tag;
  switch (mode) {
    case kWebCryptoCipherDecrypt: {
      const slice = ArrayBufferIsView(data) ?
        TypedArrayPrototypeSlice : ArrayBufferPrototypeSlice;
      tag = slice(data, -tagByteLength);
 
      // Refs: https://www.w3.org/TR/WebCryptoAPI/#aes-gcm-operations
      //
      // > If *plaintext* has a length less than *tagLength* bits, then `throw`
      // > an `OperationError`.
      if (tagByteLength > tag.byteLength) {
        return PromiseReject(lazyDOMException(
          'The provided data is too small.',
          'OperationError'));
      }
 
      data = slice(data, 0, -tagByteLength);
      break;
    }
    case kWebCryptoCipherEncrypt:
      tag = tagByteLength;
      break;
  }
 
  return jobPromise(new AESCipherJob(
    kCryptoJobAsync,
    mode,
    key[kKeyObject][kHandle],
    data,
    getVariant('AES-GCM', key.algorithm.length),
    iv,
    tag,
    additionalData));
}
 
function aesCipher(mode, key, data, algorithm) {
  switch (algorithm.name) {
    case 'AES-CTR': return asyncAesCtrCipher(mode, key, data, algorithm);
    case 'AES-CBC': return asyncAesCbcCipher(mode, key, data, algorithm);
    case 'AES-GCM': return asyncAesGcmCipher(mode, key, data, algorithm);
    case 'AES-KW': return asyncAesKwCipher(mode, key, data);
  }
}
 
async function aesGenerateKey(algorithm, extractable, keyUsages) {
  const { name, length } = algorithm;
  validateInteger(length, 'algorithm.length');
  validateOneOf(length, 'algorithm.length', kAesKeyLengths);
 
  const usageSet = new SafeSet(keyUsages);
 
  if (hasAnyNotIn(usageSet, ['encrypt', 'decrypt', 'wrapKey', 'unwrapKey'])) {
    throw lazyDOMException(
      'Unsupported key usage for an AES key',
      'SyntaxError');
  }
  return new Promise((resolve, reject) => {
    generateKey('aes', { length }, (err, key) => {
      if (err) {
        return reject(lazyDOMException(
          'The operation failed for an operation-specific reason ' +
          `[${err.message}]`,
          'OperationError'));
      }
 
      resolve(new InternalCryptoKey(
        key,
        { name, length },
        ArrayFrom(usageSet),
        extractable));
    });
  });
}
 
async function aesImportKey(
  algorithm,
  format,
  keyData,
  extractable,
  keyUsages) {
  const { name } = algorithm;
  const checkUsages = ['wrapKey', 'unwrapKey'];
  if (name !== 'AES-KW')
    ArrayPrototypePush(checkUsages, 'encrypt', 'decrypt');
 
  const usagesSet = new SafeSet(keyUsages);
  if (hasAnyNotIn(usagesSet, checkUsages)) {
    throw lazyDOMException(
      'Unsupported key usage for an AES key',
      'SyntaxError');
  }
 
  let keyObject;
  let length;
  switch (format) {
    case 'node.keyObject': {
      if (!isKeyObject(keyData))
        throw new ERR_INVALID_ARG_TYPE('keyData', 'KeyObject', keyData);

      if (keyData.type !== 'secret') {
        throw lazyDOMException(
          `Unable to import AES key with format ${format}`,
          'NotSupportedError');
      }

      keyObject = keyData;
      break;
    }
    case 'raw': {
      validateKeyLength(keyData.byteLength * 8);
      keyObject = createSecretKey(keyData);
      break;
    }
    case 'jwk': {
      if (keyData == null || typeof keyData !== 'object')
        throw lazyDOMException('Invalid JWK keyData', 'DataError');
 
      if (keyData.kty !== 'oct')
        throw lazyDOMException('Invalid key type', 'DataError');
 
      if (usagesSet.size > 0 &&
          keyData.use !== undefined &&
          keyData.use !== 'enc') {
        throw lazyDOMException('Invalid use type', 'DataError');
      }
 
      validateKeyOps(keyData.key_ops, usagesSet);
 
      if (keyData.ext !== undefined &&
          keyData.ext === false &&
          extractable === true) {
        throw lazyDOMException('JWK is not extractable', 'DataError');
      }
 
      const handle = new KeyObjectHandle();
      handle.initJwk(keyData);
 
      ({ length } = handle.keyDetail({ }));
      validateKeyLength(length);
 
      if (keyData.alg !== undefined) {
        if (typeof keyData.alg !== 'string')
          throw lazyDOMException('Invalid alg', 'DataError');
        if (keyData.alg !== getAlgorithmName(algorithm.name, length))
          throw lazyDOMException('Algorithm mismatch', 'DataError');
      }
 
      keyObject = new SecretKeyObject(handle);
      break;
    }
    default:
      throw lazyDOMException(
        `Unable to import AES key with format ${format}`,
        'NotSupportedError');
  }
 
  if (length === undefined) {
    ({ length } = keyObject[kHandle].keyDetail({ }));
    validateKeyLength(length);
  }
 
  return new InternalCryptoKey(
    keyObject,
    { name, length },
    keyUsages,
    extractable);
}
 
module.exports = {
  aesCipher,
  aesGenerateKey,
  aesImportKey,
  getAlgorithmName,
};