CVE-2022-2589 (published 2022-08-01T15:15Z)

Cross-site Scripting (XSS) - Reflected in GitHub repository beancount/fava prior to 1.22.3.

CVSS v3 base score: 6.1, MEDIUM (CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N)

Weakness information:
cwe_id: CWE-79
cwe_name: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
description: The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
extended_description: 
            Cross-site scripting (XSS) vulnerabilities occur when:
            
               Untrusted data enters a web application, typically from a web request.
               The web application dynamically generates a web page that contains this untrusted data.
               During page generation, the application does not prevent the data from containing content that is executable by a web browser, such as JavaScript, HTML tags, HTML attributes, mouse events, Flash, ActiveX, etc.
               A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data.
               Since the script comes from a web page that was sent by the web server, the victim's web browser executes the malicious script in the context of the web server's domain.
               This effectively violates the intention of the web browser's same-origin policy, which states that scripts in one domain should not be able to access resources or run code in a different domain.
            
            There are three main kinds of XSS:
            
               
                  Type 1: Reflected XSS (or Non-Persistent) - 
         			The server reads data directly from the HTTP request and reflects it back in the HTTP response. Reflected XSS exploits occur when an attacker causes a victim to supply dangerous content to a vulnerable web application, which is then reflected back to the victim and executed by the web browser. The most common mechanism for delivering malicious content is to include it as a parameter in a URL that is posted publicly or e-mailed directly to the victim. URLs constructed in this manner constitute the core of many phishing schemes, whereby an attacker convinces a victim to visit a URL that refers to a vulnerable site. After the site reflects the attacker's content back to the victim, the content is executed by the victim's browser.
               
                  Type 2: Stored XSS (or Persistent) - 
               The application stores dangerous data in a database, message forum, visitor log, or other trusted data store. At a later time, the dangerous data is subsequently read back into the application and included in dynamic content. From an attacker's perspective, the optimal place to inject malicious content is in an area that is displayed to either many users or particularly interesting users. Interesting users typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker. If one of these users executes malicious content, the attacker may be able to perform privileged operations on behalf of the user or gain access to sensitive data belonging to the user. For example, the attacker might inject XSS into a log message, which might not be handled properly when an administrator views the logs.
            
               
                  Type 0: DOM-Based XSS - 
               In DOM-based XSS, the client performs the injection of XSS into the page; in the other types, the server performs the injection. DOM-based XSS generally involves server-controlled, trusted script that is sent to the client, such as Javascript that performs sanity checks on a form before the user submits it. If the server-supplied script processes user-supplied data and then injects it back into the web page (such as with dynamic HTML), then DOM-based XSS is possible.
            
            
            Once the malicious script is injected, the attacker can perform a variety of malicious activities. The attacker could transfer private information, such as cookies that may include session information, from the victim's machine to the attacker. The attacker could send malicious requests to a web site on behalf of the victim, which could be especially dangerous to the site if the victim has administrator privileges to manage that site. Phishing attacks could be used to emulate trusted web sites and trick the victim into entering a password, allowing the attacker to compromise the victim's account on that web site. Finally, the script could exploit a vulnerability in the web browser itself possibly taking over the victim's machine, sometimes referred to as "drive-by hacking."
            In many cases, the attack can be launched without the victim even being aware of it. Even with careful users, attackers frequently use a variety of methods to encode the malicious portion of the attack, such as URL encoding or Unicode, so the request looks less suspicious.
         
         

Fix information:
repo_url: https://github.com/beancount/fava
commit_details: repo_url: https://github.com/beancount/fava
author: Jakob Schnitzer
author_date: 2022-07-30 09:18:04+02:00
msg: create tooltip contents in a xss-safe way
repository: repo_url: https://github.com/beancount/fava
repo_name: beancount/fava
description: Fava - web interface for Beancount
repo_language: Python
owner: beancount
file_changes: filename: ScatterPlot.svelte
change_type: ModificationType.MODIFY
diff: @@ -10,7 +10,7 @@
   import { scatterplotScale } from "./helpers";
   import type { ScatterPlotDatum } from "./scatterplot";
   import type { TooltipFindNode } from "./tooltip";
-  import { positionedTooltip } from "./tooltip";
+  import { domHelpers, positionedTooltip } from "./tooltip";
 
   export let data: ScatterPlotDatum[];
   export let width: number;
@@ -51,7 +51,7 @@
   );
 
   function tooltipText(d: ScatterPlotDatum) {
-    return `${d.description}<em>${day(d.date)}</em>`;
+    return [domHelpers.t(d.description), domHelpers.em(day(d.date))];
   }
 
   const tooltipFindNode: TooltipFindNode = (xPos, yPos) => {

programming_language: TypeScript
filename: Treemap.svelte
change_type: ModificationType.MODIFY
diff: @@ -11,7 +11,7 @@
     AccountHierarchyDatum,
     AccountHierarchyNode,
   } from "./hierarchy";
-  import { followingTooltip } from "./tooltip";
+  import { domHelpers, followingTooltip } from "./tooltip";
 
   export let data: AccountHierarchyNode;
   export let width: number;
@@ -35,9 +35,12 @@
     const val = d.value ?? 0;
     const rootValue = root.value || 1;
 
-    return `${$ctx.amount(val, currency)} (${formatPercentage(
-      val / rootValue
-    )})<em>${d.data.account}</em>`;
+    return [
+      domHelpers.t(
+        `${$ctx.amount(val, currency)} (${formatPercentage(val / rootValue)})`
+      ),
+      domHelpers.em(d.data.account),
+    ];
   }
 
   function setVisibility(

programming_language: TypeScript
filename: bar.ts
change_type: ModificationType.MODIFY
diff: @@ -7,6 +7,8 @@ import type { Result } from "../lib/result";
 import { array, date, number, object, record } from "../lib/validation";
 
 import type { ChartContext } from "./context";
+import type { TooltipContent } from "./tooltip";
+import { domHelpers } from "./tooltip";
 
 export interface BarChartDatumValue {
   currency: string;
@@ -38,7 +40,11 @@ export interface BarChart {
     /** Whether this chart contains any stacks (or is just a single account). */
     hasStackedData: boolean;
   };
-  tooltipText: (c: FormatterContext, d: BarChartDatum, e: string) => string;
+  tooltipText: (
+    c: FormatterContext,
+    d: BarChartDatum,
+    e: string
+  ) => TooltipContent;
 }
 
 const bar_validator = array(
@@ -91,24 +97,31 @@ export function bar(
     type: "barchart" as const,
     data: { accounts, bar_groups, stacks, hasStackedData },
     tooltipText: (c, d, e) => {
-      let text = "";
+      const content: TooltipContent = [];
       if (e === "") {
         d.values.forEach((a) => {
-          text += c.amount(a.value, a.currency);
-          if (a.budget) {
-            text += ` / ${c.amount(a.budget, a.currency)}`;
-          }
-          text += "<br>";
+          content.push(
+            domHelpers.t(
+              a.budget
+                ? `${c.amount(a.value, a.currency)} / ${c.amount(
+                    a.budget,
+                    a.currency
+                  )}`
+                : c.amount(a.value, a.currency)
+            )
+          );
+          content.push(domHelpers.br());
         });
       } else {
-        text += `<em>${e}</em>`;
+        content.push(domHelpers.em(e));
         d.values.forEach((a) => {
           const value = d.account_balances[e]?.[a.currency] ?? 0;
-          text += `${c.amount(value, a.currency)}<br>`;
+          content.push(domHelpers.t(`${c.amount(value, a.currency)}`));
+          content.push(domHelpers.br());
         });
       }
-      text += `<em>${d.label}</em>`;
-      return text;
+      content.push(domHelpers.em(d.label));
+      return content;
     },
   });
 }

programming_language: TypeScript
filename: context.ts
change_type: ModificationType.MODIFY
diff: @@ -2,7 +2,7 @@ import type { Readable } from "svelte/store";
 import { derived } from "svelte/store";
 
 import { currentDateFormat } from "../format";
-import { conversion, operating_currency } from "../stores";
+import { conversion, currencies, operating_currency } from "../stores";
 
 export type ChartContext = {
   currencies: string[];
@@ -13,17 +13,12 @@ export type ChartContext = {
  * The list of operating currencies, adding in the current conversion currency.
  */
 const operatingCurrenciesWithConversion = derived(
-  [operating_currency, conversion],
-  ([operating_currency_val, conversion_val]) => {
-    if (
-      !conversion_val ||
-      ["at_cost", "at_value", "units"].includes(conversion_val) ||
-      operating_currency_val.includes(conversion_val)
-    ) {
-      return operating_currency_val;
-    }
-    return [...operating_currency_val, conversion_val];
-  }
+  [operating_currency, currencies, conversion],
+  ([operating_currency_val, currencies_val, conversion_val]) =>
+    currencies_val.includes(conversion_val) &&
+    !operating_currency_val.includes(conversion_val)
+      ? [...operating_currency_val, conversion_val]
+      : operating_currency_val
 );
 
 export const chartContext: Readable<ChartContext> = derived(

programming_language: TypeScript
filename: line.ts
change_type: ModificationType.MODIFY
diff: @@ -12,6 +12,9 @@ import {
   tuple,
 } from "../lib/validation";
 
+import type { TooltipContent } from "./tooltip";
+import { domHelpers } from "./tooltip";
+
 export interface LineChartDatum {
   name: string;
   date: Date;
@@ -26,7 +29,7 @@ export type LineChartData = {
 export interface LineChart {
   type: "linechart";
   data: LineChartData[];
-  tooltipText: (c: FormatterContext, d: LineChartDatum) => string;
+  tooltipText: (c: FormatterContext, d: LineChartDatum) => TooltipContent;
 }
 
 const balances_validator = array(object({ date, balance: record(number) }));
@@ -57,8 +60,10 @@ export function balances(json: unknown): Result<LineChart, string> {
   return ok({
     type: "linechart" as const,
     data,
-    tooltipText: (c, d) =>
-      `${c.amount(d.value, d.name)}<em>${day(d.date)}</em>`,
+    tooltipText: (c, d) => [
+      domHelpers.t(c.amount(d.value, d.name)),
+      domHelpers.em(day(d.date)),
+    ],
   });
 }
 
@@ -82,8 +87,9 @@ export function commodities(
   return ok({
     type: "linechart" as const,
     data: [{ name: label, values }],
-    tooltipText(c, d) {
-      return `1 ${base} = ${c.amount(d.value, quote)}<em>${day(d.date)}</em>`;
-    },
+    tooltipText: (c, d) => [
+      domHelpers.t(`1 ${base} = ${c.amount(d.value, quote)}`),
+      domHelpers.em(day(d.date)),
+    ],
   });
 }

programming_language: TypeScript
filename: tooltip.ts
change_type: ModificationType.MODIFY
diff: @@ -19,6 +19,19 @@ const hide = (): void => {
   t.style.opacity = "0";
 };
 
+/** Some small utilities to create tooltip contents. */
+export const domHelpers = {
+  br: () => document.createElement("br"),
+  em: (content: string) => {
+    const em = document.createElement("em");
+    em.textContent = content;
+    return em;
+  },
+  t: (text: string) => document.createTextNode(text),
+};
+
+export type TooltipContent = (HTMLElement | Text)[];
+
 /**
  * Svelte action to have the given element act on mouse to show a tooltip.
  *
@@ -27,8 +40,8 @@ const hide = (): void => {
  */
 export function followingTooltip(
   node: SVGElement,
-  text: () => string
-): { destroy: () => void; update: (t: () => string) => void } {
+  text: () => TooltipContent
+): { destroy: () => void; update: (t: () => TooltipContent) => void } {
   let getter = text;
   /** Event listener to have the tooltip follow the mouse. */
   function followMouse(event: MouseEvent): void {
@@ -39,14 +52,14 @@ export function followingTooltip(
   }
   node.addEventListener("mouseenter", () => {
     const t = tooltip();
-    t.innerHTML = getter();
+    t.replaceChildren(...getter());
   });
   node.addEventListener("mousemove", followMouse);
   node.addEventListener("mouseleave", hide);
 
   return {
     destroy: hide,
-    update(t: () => string): void {
+    update(t: () => TooltipContent): void {
       getter = t;
     },
   };
@@ -56,7 +69,7 @@ export function followingTooltip(
 export type TooltipFindNode = (
   x: number,
   y: number
-) => [number, number, string] | undefined;
+) => [number, number, TooltipContent] | undefined;
 
 /**
  * Svelte action to have the given <g> element act on mouse to show a tooltip.
@@ -78,7 +91,7 @@ export function positionedTooltip(
       const [x, y, content] = res;
       const t = tooltip();
       t.style.opacity = "1";
-      t.innerHTML = content;
+      t.replaceChildren(...content);
       t.style.left = `${window.scrollX + x + matrix.e}px`;
       t.style.top = `${window.scrollY + y + matrix.f - 15}px`;
     } else {

programming_language: TypeScript
filename: keyboard-shortcuts.ts
change_type: ModificationType.MODIFY
diff: @@ -10,7 +10,7 @@ function showTooltip(target: HTMLElement): () => void {
     target.classList.remove("hidden");
   }
   tooltip.className = "keyboard-tooltip";
-  tooltip.innerHTML = target.getAttribute("data-key") || "";
+  tooltip.textContent = target.getAttribute("data-key") ?? "";
   document.body.appendChild(tooltip);
   const parentCoords = target.getBoundingClientRect();
   // Padded 10px to the left if there is space or centered otherwise

programming_language: TypeScript
filename: index.ts
change_type: ModificationType.MODIFY
diff: @@ -26,7 +26,7 @@ export function initSidebar(): void {
       errorCountEl.classList.toggle("hidden", errorCount_val === 0);
       const span = errorCountEl.querySelector("span");
       if (span) {
-        span.innerHTML = `${errorCount_val}`;
+        span.textContent = `${errorCount_val}`;
       }
     });
   }

programming_language: TypeScript