CVE-2022-23552 (published 2023-01-27T23:15Z)

Grafana is an open-source platform for monitoring and observability. Starting with the 8.1 branch and prior to versions 8.5.16, 9.2.10, and 9.3.4, Grafana had a stored XSS vulnerability affecting the core plugin GeoMap. The stored XSS vulnerability was possible because SVG files weren't properly sanitized and allowed arbitrary JavaScript to be executed in the context of the currently authorized user of the Grafana instance. \n\nAn attacker needs to have the Editor role in order to change a panel to include either an external URL to a SVG-file containing JavaScript, or use the `data:` scheme to load an inline SVG-file containing JavaScript. This means that vertical privilege escalation is possible, where a user with Editor role can change to a known password for a user having Admin role if the user with Admin role executes malicious JavaScript viewing a dashboard.   \n\nUsers may upgrade to version 8.5.16, 9.2.10, or 9.3.4 to receive a fix.

CVSS v3 base score: 5.4, MEDIUM (CVSS:3.1/AV:N/AC:L/PR:L/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/grafana/grafana
commit_details: repo_url: https://github.com/grafana/grafana
author: Nathan Marrs
author_date: 2023-01-25 11:37:29-07:00
msg: SVG: Add dompurify preprocessor step (#62143)

Co-authored-by: Ryan McKinley <ryantxu@gmail.com>
repository: repo_url: https://github.com/grafana/grafana
repo_name: grafana/grafana
description: The open and composable observability and data visualization platform. Visualize metrics, logs, and traces from multiple sources like Prometheus, Loki, Elasticsearch, InfluxDB, Postgres and many more. 
repo_language: TypeScript
owner: grafana
file_changes: filename: package.json
change_type: ModificationType.MODIFY
diff: @@ -123,6 +123,7 @@
     "@types/d3-force": "^2.1.0",
     "@types/d3-scale-chromatic": "1.3.1",
     "@types/debounce-promise": "3.1.5",
+    "@types/dompurify": "^2",
     "@types/eslint": "8.4.9",
     "@types/file-saver": "2.0.5",
     "@types/glob": "^8.0.0",
@@ -316,6 +317,7 @@
     "dangerously-set-html-content": "1.0.9",
     "date-fns": "2.29.3",
     "debounce-promise": "3.1.2",
+    "dompurify": "^2.4.1",
     "emotion": "11.0.0",
     "eventemitter3": "4.0.7",
     "fast-deep-equal": "^3.1.3",

programming_language: JavaScript
filename: Icon.tsx
change_type: ModificationType.MODIFY
diff: @@ -57,9 +57,13 @@ export const Icon = React.forwardRef<HTMLDivElement, IconProps>(
       console.warn('Icon component passed an invalid icon name', name);
     }
 
+    if (!name || name.includes('..')) {
+      return <div ref={ref}>invalid icon name</div>;
+    }
+
     const svgSize = getSvgSize(size);
     const svgHgt = svgSize;
-    const svgWid = name?.startsWith('gf-bar-align') ? 16 : name?.startsWith('gf-interp') ? 30 : svgSize;
+    const svgWid = name.startsWith('gf-bar-align') ? 16 : name.startsWith('gf-interp') ? 30 : svgSize;
     const subDir = getIconSubDir(name, type);
     const svgPath = `${iconRoot}${subDir}/${name}.svg`;
 

programming_language: TypeScript
filename: SanitizedSVG.tsx
change_type: ModificationType.ADD
diff: @@ -0,0 +1,18 @@
+import * as DOMPurify from 'dompurify';
+import React from 'react';
+import SVG, { Props } from 'react-inlinesvg';
+
+export const SanitizedSVG = (props: Props) => {
+  return <SVG {...props} cacheRequests={true} preProcessor={getCleanSVG} />;
+};
+
+let cache = new Map<string, string>();
+
+function getCleanSVG(code: string): string {
+  let clean = cache.get(code);
+  if (!clean) {
+    clean = DOMPurify.sanitize(code, { USE_PROFILES: { svg: true, svgFilters: true } });
+    cache.set(code, clean);
+  }
+  return clean;
+}

programming_language: TypeScript
filename: icon.tsx
change_type: ModificationType.MODIFY
diff: @@ -1,8 +1,8 @@
 import { css } from '@emotion/css';
 import { isString } from 'lodash';
 import React, { CSSProperties } from 'react';
-import SVG from 'react-inlinesvg';
 
+import { SanitizedSVG } from 'app/core/components/SVG/SanitizedSVG';
 import {
   ColorDimensionConfig,
   ResourceDimensionConfig,
@@ -59,7 +59,7 @@ export function IconDisplay(props: CanvasElementProps) {
   };
 
   return (
-    <SVG
+    <SanitizedSVG
       onClick={onClick}
       src={data.path}
       style={svgStyle}

programming_language: TypeScript
filename: FileUploader.tsx
change_type: ModificationType.MODIFY
diff: @@ -1,11 +1,12 @@
 import { css } from '@emotion/css';
 import React, { Dispatch, SetStateAction, useState } from 'react';
-import SVG from 'react-inlinesvg';
 
 import { GrafanaTheme2 } from '@grafana/data';
 import { FileDropzone, useStyles2, Button, DropzoneFile, Field } from '@grafana/ui';
+import { SanitizedSVG } from 'app/core/components/SVG/SanitizedSVG';
 
 import { MediaType } from '../types';
+
 interface Props {
   setFormData: Dispatch<SetStateAction<FormData>>;
   mediaType: MediaType;
@@ -36,7 +37,7 @@ export const FileUploader = ({ mediaType, setFormData, setUpload, error }: Props
   const Preview = () => (
     <Field label="Preview">
       <div className={styles.iconPreview}>
-        {mediaType === MediaType.Icon && <SVG src={file} className={styles.img} />}
+        {mediaType === MediaType.Icon && <SanitizedSVG src={file} className={styles.img} />}
         {mediaType === MediaType.Image && <img src={file} alt="Preview of the uploaded file" className={styles.img} />}
       </div>
     </Field>

programming_language: TypeScript
filename: ResourceCards.tsx
change_type: ModificationType.MODIFY
diff: @@ -1,11 +1,11 @@
 import { css, cx } from '@emotion/css';
 import React, { memo, CSSProperties } from 'react';
-import SVG from 'react-inlinesvg';
 import AutoSizer from 'react-virtualized-auto-sizer';
 import { areEqual, FixedSizeGrid as Grid } from 'react-window';
 
 import { GrafanaTheme2 } from '@grafana/data';
 import { useTheme2, stylesFactory } from '@grafana/ui';
+import { SanitizedSVG } from 'app/core/components/SVG/SanitizedSVG';
 
 import { ResourceItem } from './FolderPickerTab';
 
@@ -38,7 +38,7 @@ function Cell(props: CellProps) {
           onClick={() => onChange(card.value)}
         >
           {card.imgUrl.endsWith('.svg') ? (
-            <SVG src={card.imgUrl} className={styles.img} />
+            <SanitizedSVG src={card.imgUrl} className={styles.img} />
           ) : (
             <img src={card.imgUrl} alt="" className={styles.img} />
           )}

programming_language: TypeScript
filename: ResourcePicker.tsx
change_type: ModificationType.MODIFY
diff: @@ -1,6 +1,5 @@
 import { css } from '@emotion/css';
 import React, { createRef } from 'react';
-import SVG from 'react-inlinesvg';
 
 import { GrafanaTheme2 } from '@grafana/data';
 import {
@@ -15,6 +14,7 @@ import {
   useTheme2,
 } from '@grafana/ui';
 import { closePopover } from '@grafana/ui/src/utils/closePopover';
+import { SanitizedSVG } from 'app/core/components/SVG/SanitizedSVG';
 
 import { getPublicOrAbsoluteUrl } from '../resource';
 import { MediaType, ResourceFolderName, ResourcePickerSize } from '../types';
@@ -56,7 +56,7 @@ export const ResourcePicker = (props: Props) => {
 
   const renderSmallResourcePicker = () => {
     if (value && sanitizedSrc) {
-      return <SVG src={sanitizedSrc} className={styles.icon} style={{ ...colorStyle }} />;
+      return <SanitizedSVG src={sanitizedSrc} className={styles.icon} style={{ ...colorStyle }} />;
     } else {
       return (
         <LinkButton variant="primary" fill="text" size="sm">
@@ -73,7 +73,7 @@ export const ResourcePicker = (props: Props) => {
           value={name}
           placeholder={placeholder}
           readOnly={true}
-          prefix={sanitizedSrc && <SVG src={sanitizedSrc} className={styles.icon} style={{ ...colorStyle }} />}
+          prefix={sanitizedSrc && <SanitizedSVG src={sanitizedSrc} className={styles.icon} style={{ ...colorStyle }} />}
           suffix={<Button icon="times" variant="secondary" fill="text" size="sm" onClick={onClear} />}
         />
       </InlineField>

programming_language: TypeScript
filename: URLPickerTab.tsx
change_type: ModificationType.MODIFY
diff: @@ -1,9 +1,9 @@
 import { css } from '@emotion/css';
 import React, { Dispatch, SetStateAction } from 'react';
-import SVG from 'react-inlinesvg';
 
 import { GrafanaTheme2 } from '@grafana/data';
 import { Field, Input, Label, useStyles2 } from '@grafana/ui';
+import { SanitizedSVG } from 'app/core/components/SVG/SanitizedSVG';
 
 import { getPublicOrAbsoluteUrl } from '../resource';
 import { MediaType } from '../types';
@@ -33,7 +33,7 @@ export const URLPickerTab = (props: Props) => {
       <div className={styles.iconContainer}>
         <Field label="Preview">
           <div className={styles.iconPreview}>
-            {mediaType === MediaType.Icon && <SVG src={imgSrc} className={styles.img} />}
+            {mediaType === MediaType.Icon && <SanitizedSVG src={imgSrc} className={styles.img} />}
             {mediaType === MediaType.Image && newValue && (
               <img src={imgSrc} alt="Preview of the selected URL" className={styles.img} />
             )}

programming_language: TypeScript
filename: QueryEditorDrawerHeader.tsx
change_type: ModificationType.MODIFY
diff: @@ -1,9 +1,9 @@
 import { css, cx } from '@emotion/css';
 import React, { useEffect, useRef, useState } from 'react';
-import InlineSVG from 'react-inlinesvg/esm';
 
 import { GrafanaTheme2 } from '@grafana/data/src';
 import { Button, HorizontalGroup, Icon, IconName, useStyles2 } from '@grafana/ui';
+import { SanitizedSVG } from 'app/core/components/SVG/SanitizedSVG';
 
 import { useAppNotification } from '../../../core/copy/appNotification';
 import { SavedQuery } from '../api/SavedQueriesApi';
@@ -150,7 +150,7 @@ export const QueryEditorDrawerHeader = ({ savedQuery, onDismiss, onSavedQueryCha
                       <a onClick={implementationComingSoonAlert}>
                         <div>
                           {option.src ? (
-                            <InlineSVG src={option.src} className={styles.optionSvg} />
+                            <SanitizedSVG src={option.src} className={styles.optionSvg} />
                           ) : (
                             <Icon name={option.icon} className={styles.menuIconClassName} />
                           )}

programming_language: TypeScript
filename: FileView.tsx
change_type: ModificationType.MODIFY
diff: @@ -1,12 +1,12 @@
 import { css } from '@emotion/css';
 import { isString } from 'lodash';
 import React, { useMemo } from 'react';
-import SVG from 'react-inlinesvg';
 import { useAsync } from 'react-use';
 import AutoSizer from 'react-virtualized-auto-sizer';
 
 import { DataFrame, GrafanaTheme2 } from '@grafana/data';
 import { CodeEditor, useStyles2 } from '@grafana/ui';
+import { SanitizedSVG } from 'app/core/components/SVG/SanitizedSVG';
 
 import { getGrafanaStorage } from './storage';
 import { StorageView } from './types';
@@ -55,7 +55,7 @@ export function FileView({ listing, path, onPathChange, view }: Props) {
     case 'svg':
       return (
         <div>
-          <SVG src={src} className={styles.icon} />
+          <SanitizedSVG src={src} className={styles.icon} />
         </div>
       );
     case 'image':

programming_language: TypeScript
filename: MarkersLegend.tsx
change_type: ModificationType.MODIFY
diff: @@ -1,7 +1,6 @@
 import { css, cx } from '@emotion/css';
 import BaseLayer from 'ol/layer/Base';
 import React, { useMemo } from 'react';
-import SVG from 'react-inlinesvg';
 import { useObservable } from 'react-use';
 import { of } from 'rxjs';
 
@@ -9,6 +8,7 @@ import { DataFrame, formattedValueToString, getFieldColorModeForField, GrafanaTh
 import { getMinMaxAndDelta } from '@grafana/data/src/field/scale';
 import { useStyles2, VizLegendItem } from '@grafana/ui';
 import { ColorScale } from 'app/core/components/ColorScale/ColorScale';
+import { SanitizedSVG } from 'app/core/components/SVG/SanitizedSVG';
 import { config } from 'app/core/config';
 import { DimensionSupplier } from 'app/features/dimensions';
 import { getThresholdItems } from 'app/plugins/panel/state-timeline/utils';
@@ -58,7 +58,7 @@ export function MarkersLegend(props: MarkersLegendProps) {
       <div className={style.infoWrap}>
         <div className={style.layerName}>{layerName}</div>
         <div className={cx(style.layerBody, style.fixedColorContainer)}>
-          <SVG
+          <SanitizedSVG
             src={`public/${symbol}`}
             className={style.legendSymbol}
             title={'Symbol'}

programming_language: TypeScript
filename: markers.ts
change_type: ModificationType.MODIFY
diff: @@ -1,3 +1,4 @@
+import * as DOMPurify from 'dompurify';
 import { Fill, RegularShape, Stroke, Circle, Style, Icon, Text } from 'ol/style';
 import tinycolor from 'tinycolor2';
 
@@ -247,6 +248,8 @@ async function prepareSVG(url: string, size?: number): Promise<string> {
       return res.text();
     })
     .then((text) => {
+      text = DOMPurify.sanitize(text, { USE_PROFILES: { svg: true, svgFilters: true } });
+
       const parser = new DOMParser();
       const doc = parser.parseFromString(text, 'image/svg+xml');
       const svg = doc.getElementsByTagName('svg')[0];

programming_language: TypeScript
filename: yarn.lock
change_type: ModificationType.MODIFY
diff: @@ -10809,6 +10809,15 @@ __metadata:
   languageName: node
   linkType: hard
 
+"@types/dompurify@npm:^2":
+  version: 2.4.0
+  resolution: "@types/dompurify@npm:2.4.0"
+  dependencies:
+    "@types/trusted-types": "*"
+  checksum: b48cd81e997794ebc390c7c5bef1a67ec14a6f2f0521973e07e06af186c7583abe114d94d24868c0632b9573f5bd77131a4b76f3fffdf089ba99a4e53dd46c39
+  languageName: node
+  linkType: hard
+
 "@types/eslint-scope@npm:^3.7.3":
   version: 3.7.4
   resolution: "@types/eslint-scope@npm:3.7.4"
@@ -11990,6 +11999,13 @@ __metadata:
   languageName: node
   linkType: hard
 
+"@types/trusted-types@npm:*":
+  version: 2.0.2
+  resolution: "@types/trusted-types@npm:2.0.2"
+  checksum: 3371eef5f1c50e1c3c07a127c1207b262ba65b83dd167a1c460fc1b135a3fb0c97b9f508efebd383f239cc5dd5b7169093686a692a501fde9c3f7208657d9b0d
+  languageName: node
+  linkType: hard
+
 "@types/uglify-js@npm:*":
   version: 3.13.1
   resolution: "@types/uglify-js@npm:3.13.1"
@@ -18333,6 +18349,13 @@ __metadata:
   languageName: node
   linkType: hard
 
+"dompurify@npm:^2.4.1":
+  version: 2.4.3
+  resolution: "dompurify@npm:2.4.3"
+  checksum: b440981f2a38cada2085759cc3d1e2f94571afc34343d011a8a6aa1ad91ae6abf651adbfa4994b0e2283f0ce81f7891cdb04b67d0b234c8d190cb70e9691f026
+  languageName: node
+  linkType: hard
+
 "domutils@npm:^2.5.2, domutils@npm:^2.6.0":
   version: 2.8.0
   resolution: "domutils@npm:2.8.0"
@@ -21665,6 +21688,7 @@ __metadata:
     "@types/d3-force": ^2.1.0
     "@types/d3-scale-chromatic": 1.3.1
     "@types/debounce-promise": 3.1.5
+    "@types/dompurify": ^2
     "@types/eslint": 8.4.9
     "@types/file-saver": 2.0.5
     "@types/glob": ^8.0.0
@@ -21747,6 +21771,7 @@ __metadata:
     dangerously-set-html-content: 1.0.9
     date-fns: 2.29.3
     debounce-promise: 3.1.2
+    dompurify: ^2.4.1
     emotion: 11.0.0
     esbuild: 0.16.17
     esbuild-loader: 2.21.0

programming_language: Markdown