UNPKG

eslint-plugin-sonarjs

Version:
326 lines (325 loc) 12.7 kB
"use strict"; /* * SonarQube JavaScript Plugin * Copyright (C) SonarSource Sàrl * mailto:info AT sonarsource DOT com * * You can redistribute and/or modify this program under the terms of * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the Sonar Source-Available License for more details. * * You should have received a copy of the Sonar Source-Available License * along with this program; if not, see https://sonarsource.com/license/ssal/ */ // https://sonarsource.github.io/rspec/#/rspec/S4790/javascript var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.rule = void 0; const generate_meta_js_1 = require("../helpers/generate-meta.js"); const module_js_1 = require("../helpers/module.js"); const ancestor_js_1 = require("../helpers/ancestor.js"); const ast_js_1 = require("../helpers/ast.js"); const meta = __importStar(require("./generated-meta.js")); const message = 'Make sure this weak hash algorithm is not used in a sensitive context here.'; const CRYPTO_UNSECURE_HASH_ALGORITHMS = new Set([ 'md2', 'md4', 'md5', 'md6', 'haval128', 'hmacmd5', 'dsa', 'ripemd', 'ripemd128', 'ripemd160', 'hmacripemd160', 'sha1', ]); const SUBTLE_UNSECURE_HASH_ALGORITHMS = new Set(['sha-1']); const TRUNCATION_METHODS = new Set(['slice', 'substring']); exports.rule = { meta: (0, generate_meta_js_1.generateMeta)(meta), create(context) { function checkNodejsCrypto(fqn, node) { // crypto#createHash const { callee, arguments: args } = node; if (fqn === 'crypto.createHash' && !isDigestTruncated(context, node)) { checkUnsecureAlgorithm(callee, args[0], CRYPTO_UNSECURE_HASH_ALGORITHMS); } } function checkSubtleCrypto(fqn, node) { // crypto.subtle#digest const { callee, arguments: args } = node; if (fqn === 'crypto.subtle.digest' && !isSubtleDigestTruncated(context, node)) { checkUnsecureAlgorithm(callee, args[0], SUBTLE_UNSECURE_HASH_ALGORITHMS); } } function checkUnsecureAlgorithm(method, hash, unsecureAlgorithms) { const hashAlgorithm = (0, ast_js_1.getUniqueWriteUsageOrNode)(context, hash); if ((0, ast_js_1.isStringLiteral)(hashAlgorithm) && unsecureAlgorithms.has(hashAlgorithm.value.toLocaleLowerCase())) { context.report({ message, node: method, }); } } return { 'CallExpression[arguments.length > 0]': (node) => { const callExpr = node; const fqn = (0, module_js_1.getFullyQualifiedName)(context, callExpr); checkNodejsCrypto(fqn, callExpr); checkSubtleCrypto(fqn, callExpr); }, }; }, }; // A truncated digest cannot serve password storage, signing, or integrity checks — those all need the // full output — so the use is non-cryptographic (short identifier, cache key, ETag). function isDigestTruncated(context, createHashCall) { let node = createHashCall; let digestCall = null; while (true) { const parent = (0, ancestor_js_1.getNodeParent)(node); if (parent?.type !== 'MemberExpression' || parent.object !== node) { break; } const grandParent = (0, ancestor_js_1.getNodeParent)(parent); if (grandParent?.type !== 'CallExpression' || grandParent.callee !== parent) { break; } const methodName = parent.property.type === 'Identifier' ? parent.property.name : null; if (digestCall && isTruncationCall(context, grandParent)) { return true; } if (methodName === 'digest') { digestCall = grandParent; } node = grandParent; } return digestCall !== null && isBoundToTruncatedReference(context, digestCall); } // Only suppress when every read of the bound digest is truncated — otherwise a mixed-use binding // (one full + one sliced) would silently silence the sensitive use. Write refs are skipped: the // declarator init is itself a write and reassignments don't consume the value. function isBoundToTruncatedReference(context, initNode) { const declarator = (0, ancestor_js_1.getNodeParent)(initNode); if (declarator?.type !== 'VariableDeclarator' || declarator.init !== initNode || declarator.id.type !== 'Identifier') { return false; } const variable = (0, ast_js_1.getVariableFromName)(context, declarator.id.name, declarator.id); return !!variable && hasOnlyTruncatedReads(context, variable); } function hasOnlyTruncatedReads(context, variable) { const reads = variable.references.filter(ref => ref.isRead()); return reads.length > 0 && reads.every(ref => isIdentifierTruncated(context, ref.identifier)); } // crypto.subtle.digest(...) returns Promise<ArrayBuffer>. Truncation can happen via .then callback, // after await on a binding, or immediately on the awaited value. function isSubtleDigestTruncated(context, digestCall) { if (isPromiseThenTruncated(context, digestCall)) { return true; } const parent = (0, ancestor_js_1.getNodeParent)(digestCall); const valueNode = parent?.type === 'AwaitExpression' ? parent : digestCall; return (isIdentifierTruncated(context, valueNode) || isBoundToTruncatedReference(context, valueNode)); } function isPromiseThenTruncated(context, digestCall) { const member = (0, ancestor_js_1.getNodeParent)(digestCall); if (member?.type !== 'MemberExpression' || member.object !== digestCall || member.property.type !== 'Identifier' || member.property.name !== 'then') { return false; } const thenCall = (0, ancestor_js_1.getNodeParent)(member); if (thenCall?.type !== 'CallExpression' || thenCall.callee !== member || thenCall.arguments.length === 0) { return false; } const callback = thenCall.arguments[0]; if ((callback.type !== 'ArrowFunctionExpression' && callback.type !== 'FunctionExpression') || callback.params.length === 0 || callback.params[0].type !== 'Identifier') { return false; } const param = callback.params[0]; const variable = (0, ast_js_1.getVariableFromName)(context, param.name, param); return !!variable && hasOnlyTruncatedReads(context, variable); } function isIdentifierTruncated(context, identifier) { const parent = (0, ancestor_js_1.getNodeParent)(identifier); if (parent?.type !== 'MemberExpression' || parent.object !== identifier) { return false; } const grandParent = (0, ancestor_js_1.getNodeParent)(parent); return (grandParent?.type === 'CallExpression' && grandParent.callee === parent && isTruncationCall(context, grandParent)); } const UNKNOWN_VALUE = Symbol('unknown'); // Treat `slice` / `substring` as truncation unless the argument pattern obviously preserves the // whole output. This keeps named constants and unresolved bounds in scope while excluding simple // no-op forms like `.slice()`, `.slice(0, undefined)`, or `.substring('foo')`. Other shortening // helpers (`substr`, `at`, `charAt`, `subarray`, transform-based extraction, etc.) are // intentionally left out here to keep this PR scoped to the existing `slice` / `substring` idiom. function isTruncationCall(context, call) { if (call.callee.type !== 'MemberExpression' || call.callee.property.type !== 'Identifier') { return false; } const method = call.callee.property.name; if (!TRUNCATION_METHODS.has(method)) { return false; } return !isObviouslyFullOutput(context, method, call.arguments); } function isObviouslyFullOutput(context, method, args) { if (args.length === 0) { return true; } if (method === 'slice') { return isSliceFullOutput(context, args); } return isSubstringFullOutput(context, args); } function isSliceFullOutput(context, args) { if (!isSliceNoOpStart(resolveStaticValue(context, args[0]))) { return false; } return args.length === 1 || isSliceFullOutputEnd(resolveStaticValue(context, args[1])); } function isSubstringFullOutput(context, args) { const startKind = getSubstringStartKind(resolveStaticValue(context, args[0])); if (args.length === 1) { return startKind === 'zero'; } const endKind = getSubstringEndKind(resolveStaticValue(context, args[1])); return ((startKind === 'zero' && endKind === 'length') || (startKind === 'length' && endKind === 'zero')); } function isSliceNoOpStart(value) { return value === undefined || (typeof value === 'number' && (value === 0 || Number.isNaN(value))); } function isSliceFullOutputEnd(value) { return value === undefined || value === Infinity; } function getSubstringStartKind(value) { if (value === undefined) { return 'zero'; } if (typeof value === 'number') { if (value === Infinity) { return 'length'; } if (value <= 0 || Number.isNaN(value)) { return 'zero'; } } return 'other'; } function getSubstringEndKind(value) { if (value === undefined) { return 'length'; } if (typeof value === 'number') { if (value === Infinity) { return 'length'; } if (value <= 0 || Number.isNaN(value)) { return 'zero'; } } return 'other'; } function resolveStaticValue(context, node) { if (node.type === 'SpreadElement') { return UNKNOWN_VALUE; } return getStaticValue((0, ast_js_1.getUniqueWriteUsageOrNode)(context, node, true)); } function getStaticValue(node) { if (node.type === 'Literal') { return coerceLiteralValue(node.value); } if (node.type === 'Identifier') { return getIdentifierStaticValue(node); } if (node.type === 'UnaryExpression' && (node.operator === '+' || node.operator === '-')) { return getUnaryStaticValue(node); } return UNKNOWN_VALUE; } function getIdentifierStaticValue(node) { switch (node.name) { case 'undefined': return undefined; case 'Infinity': return Infinity; case 'NaN': return Number.NaN; default: return UNKNOWN_VALUE; } } function getUnaryStaticValue(node) { const value = getStaticValue(node.argument); if (value === UNKNOWN_VALUE) { return UNKNOWN_VALUE; } if (value === undefined) { return Number.NaN; } return node.operator === '+' ? value : -value; } function coerceLiteralValue(value) { switch (typeof value) { case 'number': return value; case 'string': case 'boolean': case 'bigint': return Number(value); case 'object': return value === null ? 0 : UNKNOWN_VALUE; default: return UNKNOWN_VALUE; } }