ruleHelper.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. /**
  2. * @fileoverview ESLint helpers for checking sanitization
  3. * @author Frederik Braun et al.
  4. * @copyright 2015-2017 Mozilla Corporation. All rights reserved.
  5. */
  6. "use strict";
  7. // names of escaping functions that we acknowledge
  8. const VALID_ESCAPERS = ["Sanitizer.escapeHTML", "escapeHTML"];
  9. const VALID_UNWRAPPERS = ["Sanitizer.unwrapSafeHTML", "unwrapSafeHTML"];
  10. /** Change this to class RuleHelper when <4.2.6 is no longer an issue
  11. *
  12. * @constructor
  13. * @param {Object} context ESLint configuration context
  14. * @param {Object} defaultRuleChecks Default rules to merge with
  15. * this.context
  16. *
  17. */
  18. function RuleHelper(context, defaultRuleChecks) {
  19. this.context = context;
  20. this.ruleChecks = this.combineRuleChecks(defaultRuleChecks);
  21. }
  22. RuleHelper.prototype = {
  23. /**
  24. * Returns true if the expression contains allowed syntax, otherwise false.
  25. *
  26. * The function will be called recursively for Template Strings with interpolation
  27. * (e.g. `Hello ${name}`), Binary Expressions (e.g. |foo+bar|), and more.
  28. *
  29. * @param {Object} expression Checks whether this node is an allowed expression.
  30. * @param {Object} escapeObject contains keys "methods" and "taggedTemplates" which are arrays of strings
  31. * of matching escaping function names.
  32. * @param {Object} details Additional linter violation state information, in case this function was called
  33. * recursively.
  34. * @returns {boolean} Returns whether the expression is allowed.
  35. *
  36. */
  37. allowedExpression(expression, escapeObject, details) {
  38. if (!escapeObject) {
  39. escapeObject = {};
  40. }
  41. /*
  42. expression = { right-hand side of innerHTML or 2nd param to insertAdjacentHTML
  43. */
  44. let allowed;
  45. /* check the stringish-part, which is either the right-hand-side of
  46. an inner/outerHTML assignment or the 2nd parameter to insertAdjacentTML
  47. */
  48. switch(expression.type) {
  49. case"Literal":
  50. /* surely, someone could have an evil literal in there, but that"s malice
  51. we can just check for unsafe coding practice, not outright malice
  52. example literal "<script>eval(location.hash.slice(1)</script>"
  53. (it"s the task of the tagger-function to be the gateway here.)
  54. */
  55. allowed = true;
  56. break;
  57. case "TemplateElement":
  58. // Raw text from a template
  59. allowed = true;
  60. break;
  61. case "TemplateLiteral":
  62. // check only the ${..} expressions
  63. allowed = this.allowedExpression(expression.expressions, escapeObject, details);
  64. break;
  65. case "TaggedTemplateExpression":
  66. allowed = this.isAllowedCallExpression(expression.tag, escapeObject.taggedTemplates || VALID_ESCAPERS);
  67. break;
  68. case "CallExpression":
  69. allowed = this.isAllowedCallExpression(expression.callee, escapeObject.methods || VALID_UNWRAPPERS);
  70. break;
  71. case "BinaryExpression":
  72. allowed = ((this.allowedExpression(expression.left, escapeObject, details))
  73. && (this.allowedExpression(expression.right, escapeObject, details)));
  74. break;
  75. case "TSAsExpression":
  76. // TSAsExpressions contain the raw javascript value in 'expression'
  77. allowed = this.allowedExpression(expression.expression, escapeObject, details);
  78. break;
  79. case "TypeCastExpression":
  80. allowed = this.allowedExpression(expression.expression, escapeObject, details);
  81. break;
  82. case "Identifier":
  83. allowed = this.isAllowedIdentifier(expression, escapeObject, details);
  84. break;
  85. default:
  86. // everything that doesn't match is considered unsafe:
  87. allowed = false;
  88. break;
  89. }
  90. if (Array.isArray(expression)) {
  91. allowed = expression.every((e) => this.allowedExpression(e, escapeObject, details));
  92. }
  93. return allowed;
  94. },
  95. /**
  96. * Check if an identifier is allowed
  97. * - only if variableTracing is enabled in the first place.
  98. * - find its declarations and see if it's const or let
  99. * - if so, allow if the declaring statement is an allowed expression
  100. * - ensure that following assignments to that identifier are also allowed
  101. *
  102. * @param {Object} expression Identifier expression
  103. * @param {Object} escapeObject contains keys "methods" and "taggedTemplates" which are arrays of strings
  104. * of matching escaping function names.
  105. * @param {Object} details Additional linter violation state information, in case this function was called
  106. * recursively.
  107. * @returns {boolean} Returns whether the Identifier is deemed safe.
  108. */
  109. isAllowedIdentifier(expression, escapeObject, details) {
  110. // respect the custom config property `variableTracing`:
  111. if (!this.ruleChecks["variableTracing"]) {
  112. return false;
  113. }
  114. // find declared variables and see which are literals
  115. const scope = this.context.getScope(expression);
  116. const variableInfo = scope.set.get(expression.name);
  117. let allowed = false;
  118. // If we can't get info on the variable, we just can't allow it
  119. if (!variableInfo ||
  120. !variableInfo.defs ||
  121. variableInfo.defs.length == 0 ||
  122. !variableInfo.references ||
  123. variableInfo.references.length == 0) {
  124. // FIXME Fix/Adjust towards a helpful message here and update tests accordingly.
  125. // details.message = `Variable ${expression.name} considered unsafe: variable initialization not found`;
  126. return false;
  127. }
  128. // look if the var was defined as allowable
  129. let definedAsAllowed = false;
  130. for (const def of variableInfo.defs) {
  131. if (def.node.type !== "VariableDeclarator") {
  132. // identifier wasn't declared as a variable
  133. // e.g., it shows up as a parameter to an
  134. // ArrowFunctionExpression, FunctionDeclaration or FunctionExpression
  135. const {line, column} = def.node.loc.start;
  136. if ((def.node.type === "FunctionDeclaration") || (def.node.type == "ArrowFunctionExpression") || (def.node.type === "FunctionExpression"))
  137. {
  138. details.message = `Variable '${expression.name}' declared as function parameter, which is considered unsafe. '${def.node.type}' at ${line}:${column}`;
  139. } else {
  140. details.message = `Variable '${expression.name}' initialized with unknown declaration '${def.node.type}' at ${line}:${column}`;
  141. }
  142. definedAsAllowed = false;
  143. break;
  144. }
  145. if ((def.kind !== "let") && (def.kind !== "const")) {
  146. // We do not allow for identifiers declared with "var", as they can be overridden in a
  147. // way that is hard for us to follow (e.g., assignments to globalThis[theirNameAsString]).
  148. definedAsAllowed = false;
  149. break;
  150. }
  151. // the `init` property carries the right-hand side of the variable definition:
  152. const varInitAs = def.node.init;
  153. // When the variable is only declared but not initialized, `init` is `null`.
  154. if (varInitAs && !this.allowedExpression(varInitAs, escapeObject, details)) {
  155. // if one variable definition is considered unsafe, all are.
  156. // NB: order of definition is unclear. See issue #168.
  157. if (!details.message) {
  158. const {line, column} = varInitAs.loc.start;
  159. details.message = `Variable '${expression.name}' initialized with unsafe value at ${line}:${column}`;
  160. }
  161. definedAsAllowed = false;
  162. break;
  163. }
  164. // keep iterating through other definitions.
  165. definedAsAllowed = true;
  166. }
  167. if (definedAsAllowed) {
  168. // the variable was declared as a safe value (e.g., literal)
  169. // now inspect writing references to that variable
  170. let allWritingRefsAllowed = false;
  171. // With no write variable references, if it was defined as allowed
  172. // then we should consider it safe.
  173. if (variableInfo.references.filter(ref => ref.isWrite()).length === 0) {
  174. allWritingRefsAllowed = true;
  175. }
  176. for (const ref of variableInfo.references) {
  177. // only look into writing references
  178. if (ref.isWrite()) {
  179. const writeExpr = ref.writeExpr;
  180. // if one is unsafe we'll consider all unsafe.
  181. // this is because code occurring doesn't guarantee it being executed
  182. // due to dynamic behavior if-conditions and such
  183. if (!this.allowedExpression(writeExpr, escapeObject, details)) {
  184. if (!details.message) {
  185. const {line, column} = writeExpr.loc.start;
  186. details.message = `Variable '${expression.name}' reassigned with unsafe value at ${line}:${column}`;
  187. }
  188. allWritingRefsAllowed = false;
  189. break;
  190. }
  191. allWritingRefsAllowed = true;
  192. }
  193. }
  194. // allow this variable, because all writing references to it were allowed.
  195. allowed = allWritingRefsAllowed;
  196. }
  197. return allowed;
  198. },
  199. /**
  200. * Check if a callee is in the list allowed sanitizers
  201. *
  202. * @param {Object} callee Function that is being called expression.tag
  203. * or expression.callee
  204. * @param {Array} allowedSanitizers List of valid wrapping expressions
  205. * @returns {boolean} Returns whether call to the callee is allowed
  206. */
  207. isAllowedCallExpression(callee, allowedSanitizers) {
  208. const funcName = this.getCodeName(callee);
  209. let allowed = false;
  210. if (funcName && allowedSanitizers.indexOf(funcName) !== -1) {
  211. allowed = true;
  212. }
  213. return allowed;
  214. },
  215. /**
  216. * Captures safely any new node types that have been missed and throw when we don't support them
  217. * this normalizes the passed in identifier type to return the same shape
  218. *
  219. * @param {Object} node A callable expression to be simplified
  220. * @returns {Object} Method and (if applicable) object name
  221. */
  222. normalizeMethodCall(node) {
  223. let methodName;
  224. let objectName;
  225. switch (node.type) {
  226. case "Identifier":
  227. methodName = node.name;
  228. break;
  229. case "MemberExpression":
  230. methodName = node.property.name;
  231. objectName = node.object.name || this.context.getSource(node.object);
  232. break;
  233. case "ConditionalExpression":
  234. case "CallExpression":
  235. case "ArrowFunctionExpression":
  236. methodName = "";
  237. break;
  238. case "AssignmentExpression":
  239. methodName = this.normalizeMethodCall(node.right);
  240. break;
  241. case "Import":
  242. methodName = "import";
  243. break;
  244. default:
  245. this.reportUnsupported(node, "Unexpected callable", `unexpected ${node.type} in normalizeMethodCall`);
  246. }
  247. return {
  248. objectName,
  249. methodName
  250. };
  251. },
  252. /**
  253. * Returns functionName or objectName.methodName of an expression
  254. *
  255. * @param {Object} node A callable expression
  256. * @returns {String} A nice name to expression call
  257. */
  258. getCodeName(node) {
  259. const normalizedMethodCall = this.normalizeMethodCall(node);
  260. let codeName = normalizedMethodCall.methodName;
  261. if (normalizedMethodCall.objectName) {
  262. codeName = `${normalizedMethodCall.objectName}.${codeName}`;
  263. }
  264. return codeName;
  265. },
  266. /**
  267. * Checks to see if a method or function should be called
  268. * If objectMatches isn't present or blank array the code should not be checked
  269. * If we do have object filters and the call is a function then it should not be checked
  270. *
  271. * Checks if there are objectMatches we need to apply
  272. * @param {Object} node Call expression node
  273. * @param {Object} objectMatches Strings that are checked as regex to
  274. * match an object name
  275. * @returns {Boolean} Returns whether to run checks expression
  276. */
  277. shouldCheckMethodCall(node, objectMatches) {
  278. const normalizedMethodCall = this.normalizeMethodCall(node.callee);
  279. let matched = false;
  280. // Allow methods named "import":
  281. if (normalizedMethodCall.methodName === "import"
  282. && node.callee && node.callee.type === "MemberExpression") {
  283. return false;
  284. }
  285. // If objectMatches isn't present we should match all
  286. if (!objectMatches) {
  287. return true;
  288. }
  289. // if blank array the code should not be checked, this is a quick way to disable rules
  290. // TODO should we make this match all instead and let the $ruleCheck be false instead?
  291. if (objectMatches.length === 0) {
  292. return false;
  293. }
  294. // If we do have object filters and the call is a function then it should not be checked
  295. if ("objectName" in normalizedMethodCall && normalizedMethodCall.objectName) {
  296. for (const objectMatch of objectMatches) {
  297. const match = new RegExp(objectMatch, "gi");
  298. if (normalizedMethodCall.objectName.match(match)) {
  299. matched = true;
  300. break;
  301. }
  302. }
  303. }
  304. // if we don't have a objectName return false as bare function call
  305. // if we didn't match also return false
  306. return matched;
  307. },
  308. /**
  309. * Algorithm used to decide on merging ruleChecks with this.context
  310. * @param {Object} defaultRuleChecks Object containing default rules
  311. * @returns {Object} The merged ruleChecks
  312. */
  313. combineRuleChecks(defaultRuleChecks) {
  314. const parentRuleChecks = this.context.options[0] || {};
  315. let childRuleChecks = Object.assign({}, this.context.options[1]);
  316. const ruleCheckOutput = {};
  317. if (!("defaultDisable" in parentRuleChecks)
  318. || !parentRuleChecks.defaultDisable) {
  319. childRuleChecks = Object.assign({}, defaultRuleChecks, childRuleChecks);
  320. }
  321. // default to variable back tracing enabled.
  322. ruleCheckOutput["variableTracing"] = true;
  323. if ("variableTracing" in parentRuleChecks) {
  324. ruleCheckOutput["variableTracing"] = !!parentRuleChecks["variableTracing"];
  325. }
  326. // If we have defined child rules lets ignore default rules
  327. Object.keys(childRuleChecks).forEach((ruleCheckKey) => {
  328. // However if they have missing keys merge with default
  329. const ruleCheck = Object.assign(
  330. "defaultDisable" in parentRuleChecks ? {} :
  331. {
  332. escape: {
  333. taggedTemplates: ["Sanitizer.escapeHTML", "escapeHTML"],
  334. methods: ["Sanitizer.unwrapSafeHTML", "unwrapSafeHTML"]
  335. }
  336. },
  337. defaultRuleChecks[ruleCheckKey],
  338. parentRuleChecks,
  339. childRuleChecks[ruleCheckKey]);
  340. ruleCheckOutput[ruleCheckKey] = ruleCheck;
  341. });
  342. return ruleCheckOutput;
  343. },
  344. /**
  345. * Runs the checks against a CallExpression
  346. * @param {Object} node Call expression node
  347. * @returns {undefined} Does not return
  348. */
  349. checkMethod(node) {
  350. const normalizeMethodCall = this.normalizeMethodCall(node.callee);
  351. const methodName = normalizeMethodCall.methodName;
  352. if (Object.prototype.hasOwnProperty.call(this.ruleChecks, methodName)) {
  353. const ruleCheck = this.ruleChecks[methodName];
  354. if (!Array.isArray(ruleCheck.properties)) {
  355. this.context.report(node, `Method check requires properties array in eslint rule ${methodName}`);
  356. return;
  357. }
  358. ruleCheck.properties.forEach((propertyId) => {
  359. const argument = node.arguments[propertyId];
  360. if (!argument) {
  361. // We bail out if arguments is supplied as a SpreadElement like `...args`
  362. // It would be better if we tried a bit harder. That's #214
  363. return;
  364. }
  365. const details = {};
  366. if (this.shouldCheckMethodCall(node, ruleCheck.objectMatches)
  367. && !this.allowedExpression(argument, ruleCheck.escape, details)) {
  368. // Include the additional details if available (e.g. name of a disallowed variable
  369. // and the position of the expression that made it disallowed).
  370. if (details.message) {
  371. this.context.report(node, `Unsafe call to ${this.getCodeName(node.callee)} for argument ${propertyId} (${details.message})`);
  372. return;
  373. }
  374. this.context.report(node, `Unsafe call to ${this.getCodeName(node.callee)} for argument ${propertyId}`);
  375. }
  376. });
  377. }
  378. },
  379. /**
  380. * Runs the checks against an assignment expression
  381. * @param {Object} node Assignment expression node
  382. * @returns {undefined} Does not return
  383. */
  384. checkProperty(node) {
  385. if (Object.prototype.hasOwnProperty.call(this.ruleChecks, node.left.property.name)) {
  386. const ruleCheck = this.ruleChecks[node.left.property.name];
  387. const details = {};
  388. if (!this.allowedExpression(node.right, ruleCheck.escape, details)) {
  389. // Include the additional details if available (e.g. name of a disallowed variable
  390. // and the position of the expression that made it disallowed).
  391. if (details.message) {
  392. this.context.report(node, `Unsafe assignment to ${node.left.property.name} (${details.message})`);
  393. return;
  394. }
  395. this.context.report(node, `Unsafe assignment to ${node.left.property.name}`);
  396. }
  397. }
  398. },
  399. reportUnsupported(node, reason, errorTitle) {
  400. const bugPath = `https://github.com/mozilla/eslint-plugin-no-unsanitized/issues/new?title=${encodeURIComponent(errorTitle)}`;
  401. this.context.report(node, `Error in no-unsanitized: ${reason}. Please report a minimal code snippet to the developers at ${bugPath}`);
  402. }
  403. };
  404. module.exports = RuleHelper;