CVE-2024-22420 (published 2024-01-19T21:15Z)

JupyterLab is an extensible environment for interactive and reproducible computing, based on the Jupyter Notebook and Architecture. This vulnerability depends on user interaction by opening a malicious Markdown file using JupyterLab preview feature. A malicious user can access any data that the attacked user has access to as well as perform arbitrary requests acting as the attacked user. JupyterLab version 4.0.11 has been patched. Users are advised to upgrade. Users unable to upgrade should disable the table of contents extension.

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/jupyterlab/jupyterlab
commit_details: repo_url: https://github.com/jupyterlab/jupyterlab
author: Michał Krassowski
author_date: 2024-01-19 12:43:25+00:00
msg: Merge pull request from GHSA-4m77-cmpx-vjc4

* Fix sanitization and escaping for MD headings in ToC

* Add a unit test for `getHeadingId`

* Make `sanitizer` argument optional in getHeadingId, integrity update
repository: repo_url: https://github.com/jupyterlab/jupyterlab
repo_name: jupyterlab/jupyterlab
description: JupyterLab computational environment.
repo_language: TypeScript
owner: jupyterlab
file_changes: filename: index.ts
change_type: ModificationType.MODIFY
diff: @@ -10,7 +10,7 @@ import {
   JupyterFrontEnd,
   JupyterFrontEndPlugin
 } from '@jupyterlab/application';
-import { WidgetTracker } from '@jupyterlab/apputils';
+import { ISanitizer, WidgetTracker } from '@jupyterlab/apputils';
 import { PathExt } from '@jupyterlab/coreutils';
 import {
   IMarkdownViewerTracker,
@@ -20,6 +20,7 @@ import {
   MarkdownViewerTableOfContentsFactory
 } from '@jupyterlab/markdownviewer';
 import {
+  IRenderMime,
   IRenderMimeRegistry,
   markdownRendererFactory
 } from '@jupyterlab/rendermime';
@@ -49,7 +50,12 @@ const plugin: JupyterFrontEndPlugin<IMarkdownViewerTracker> = {
   description: 'Adds markdown file viewer and provides its tracker.',
   provides: IMarkdownViewerTracker,
   requires: [IRenderMimeRegistry, ITranslator],
-  optional: [ILayoutRestorer, ISettingRegistry, ITableOfContentsRegistry],
+  optional: [
+    ILayoutRestorer,
+    ISettingRegistry,
+    ITableOfContentsRegistry,
+    ISanitizer
+  ],
   autoStart: true
 };
 
@@ -62,7 +68,8 @@ function activate(
   translator: ITranslator,
   restorer: ILayoutRestorer | null,
   settingRegistry: ISettingRegistry | null,
-  tocRegistry: ITableOfContentsRegistry | null
+  tocRegistry: ITableOfContentsRegistry | null,
+  sanitizer: IRenderMime.ISanitizer | null
 ): IMarkdownViewerTracker {
   const trans = translator.load('jupyterlab');
   const { commands, docRegistry } = app;
@@ -182,7 +189,8 @@ function activate(
     tocRegistry.add(
       new MarkdownViewerTableOfContentsFactory(
         tracker,
-        rendermime.markdownParser
+        rendermime.markdownParser,
+        sanitizer ?? rendermime.sanitizer
       )
     );
   }

programming_language: TypeScript
filename: toc.ts
change_type: ModificationType.MODIFY
diff: @@ -2,7 +2,7 @@
 // Distributed under the terms of the Modified BSD License.
 
 import { IWidgetTracker } from '@jupyterlab/apputils';
-import { IMarkdownParser } from '@jupyterlab/rendermime';
+import { IMarkdownParser, IRenderMime } from '@jupyterlab/rendermime';
 import {
   TableOfContents,
   TableOfContentsFactory,
@@ -96,7 +96,8 @@ export class MarkdownViewerTableOfContentsFactory extends TableOfContentsFactory
    */
   constructor(
     tracker: IWidgetTracker<MarkdownDocument>,
-    protected parser: IMarkdownParser | null
+    protected parser: IMarkdownParser | null,
+    protected sanitizer: IRenderMime.ISanitizer
   ) {
     super(tracker);
   }
@@ -165,13 +166,14 @@ export class MarkdownViewerTableOfContentsFactory extends TableOfContentsFactory
         const elementId = await TableOfContentsUtils.Markdown.getHeadingId(
           this.parser!,
           heading.raw,
-          heading.level
+          heading.level,
+          this.sanitizer
         );
 
         if (!elementId) {
           return;
         }
-        const selector = `h${heading.level}[id="${elementId}"]`;
+        const selector = `h${heading.level}[id="${CSS.escape(elementId)}"]`;
 
         headingToElement.set(
           heading,

programming_language: TypeScript
filename: toc.ts
change_type: ModificationType.MODIFY
diff: @@ -649,10 +649,14 @@ export class NotebookToCFactory extends TableOfContentsFactory<NotebookPanel> {
 
     const findHeadingElement = (cell: Cell): void => {
       model.getCellHeadings(cell).forEach(async heading => {
-        const elementId = await getIdForHeading(heading, this.parser!);
+        const elementId = await getIdForHeading(
+          heading,
+          this.parser!,
+          this.sanitizer
+        );
 
         const selector = elementId
-          ? `h${heading.level}[id="${elementId}"]`
+          ? `h${heading.level}[id="${CSS.escape(elementId)}"]`
           : `h${heading.level}`;
 
         if (heading.outputIndex !== undefined) {
@@ -771,7 +775,8 @@ export class NotebookToCFactory extends TableOfContentsFactory<NotebookPanel> {
  */
 export async function getIdForHeading(
   heading: INotebookHeading,
-  parser: IRenderMime.IMarkdownParser
+  parser: IRenderMime.IMarkdownParser,
+  sanitizer: IRenderMime.ISanitizer
 ) {
   let elementId: string | null = null;
   if (heading.type === Cell.HeadingType.Markdown) {
@@ -779,7 +784,8 @@ export async function getIdForHeading(
       parser,
       // Type from TableOfContentsUtils.Markdown.IMarkdownHeading
       (heading as any).raw,
-      heading.level
+      heading.level,
+      sanitizer
     );
   } else if (heading.type === Cell.HeadingType.HTML) {
     // Type from TableOfContentsUtils.IHTMLHeading

programming_language: TypeScript
filename: widget.ts
change_type: ModificationType.MODIFY
diff: @@ -2305,14 +2305,15 @@ export class Notebook extends StaticNotebook {
               id = await TableOfContentsUtils.Markdown.getHeadingId(
                 this.rendermime.markdownParser!,
                 mdHeading.raw,
-                mdHeading.level
+                mdHeading.level,
+                this.rendermime.sanitizer
               );
             }
             break;
         }
         if (id === queryId) {
           const element = this.node.querySelector(
-            `h${heading.level}[id="${id}"]`
+            `h${heading.level}[id="${CSS.escape(id)}"]`
           ) as HTMLElement;
 
           return {

programming_language: TypeScript
filename: index.ts
change_type: ModificationType.MODIFY
diff: @@ -525,10 +525,10 @@ export namespace IRenderMime {
    */
   export interface IMarkdownParser {
     /**
-     * Render a markdown source.
+     * Render a markdown source into unsanitized HTML.
      *
      * @param source - The string to render.
-     * @returns - A promise of the string.
+     * @returns - A promise of the string containing HTML which may require sanitization.
      */
     render(source: string): Promise<string>;
   }

programming_language: TypeScript
filename: package.json
change_type: ModificationType.MODIFY
diff: @@ -46,6 +46,7 @@
     "@jupyterlab/docregistry": "^4.1.0-beta.1",
     "@jupyterlab/observables": "^5.1.0-beta.1",
     "@jupyterlab/rendermime": "^4.1.0-beta.1",
+    "@jupyterlab/rendermime-interfaces": "^3.9.0-beta.1",
     "@jupyterlab/translation": "^4.1.0-beta.1",
     "@jupyterlab/ui-components": "^4.1.0-beta.1",
     "@lumino/coreutils": "^2.1.2",

programming_language: JavaScript
filename: markdown.ts
change_type: ModificationType.MODIFY
diff: @@ -1,7 +1,9 @@
 // Copyright (c) Jupyter Development Team.
 // Distributed under the terms of the Modified BSD License.
 
+import { Sanitizer } from '@jupyterlab/apputils';
 import { IMarkdownParser, renderMarkdown } from '@jupyterlab/rendermime';
+import { IRenderMime } from '@jupyterlab/rendermime-interfaces';
 import { TableOfContents } from '../tokens';
 
 /**
@@ -24,27 +26,35 @@ export interface IMarkdownHeading extends TableOfContents.IHeading {
  *
  * @param raw Raw markdown heading
  * @param level Heading level
+ * @param sanitizer HTML sanitizer
  */
 export async function getHeadingId(
-  parser: IMarkdownParser,
+  markdownParser: IMarkdownParser,
   raw: string,
-  level: number
+  level: number,
+  sanitizer?: IRenderMime.ISanitizer
 ): Promise<string | null> {
   try {
-    const innerHTML = await parser.render(raw);
+    const host = document.createElement('div');
 
-    if (!innerHTML) {
-      return null;
-    }
+    await renderMarkdown({
+      markdownParser,
+      host,
+      source: raw,
+      trusted: false,
+      sanitizer: sanitizer ?? new Sanitizer(),
+      shouldTypeset: false,
+      resolver: null,
+      linkHandler: null,
+      latexTypesetter: null
+    });
 
-    const container = document.createElement('div');
-    container.innerHTML = innerHTML;
-    const header = container.querySelector(`h${level}`);
+    const header = host.querySelector(`h${level}`);
     if (!header) {
       return null;
     }
 
-    return renderMarkdown.createHeaderId(header);
+    return header.id;
   } catch (reason) {
     console.error('Failed to parse a heading.', reason);
   }

programming_language: TypeScript
filename: markdown.spec.ts
change_type: ModificationType.MODIFY
diff: @@ -2,9 +2,33 @@
 // Distributed under the terms of the Modified BSD License.
 
 import { TableOfContentsUtils } from '@jupyterlab/toc';
+import { Sanitizer } from '@jupyterlab/apputils';
+import { createMarkdownParser } from '@jupyterlab/markedparser-extension';
+import { IMarkdownParser } from '@jupyterlab/rendermime';
+import {
+  EditorLanguageRegistry,
+  IEditorLanguageRegistry
+} from '@jupyterlab/codemirror';
 
 describe('TableOfContentsUtils', () => {
   describe('Markdown', () => {
+    describe('#getHeadingId', () => {
+      const languages: IEditorLanguageRegistry = new EditorLanguageRegistry();
+      const parser: IMarkdownParser = createMarkdownParser(languages);
+      const sanitizer = new Sanitizer();
+      it.each<[string, string]>([
+        ['# Title', 'Title'],
+        [`# test'"></title><img>test {#'"><img>}`, `test'\">test-{#'\">}`]
+      ])('should derive ID from markdown', async (markdown, expectedId) => {
+        const headingId = await TableOfContentsUtils.Markdown.getHeadingId(
+          parser,
+          markdown,
+          1,
+          sanitizer
+        );
+        expect(headingId).toEqual(expectedId);
+      });
+    });
     describe('#getHeadings', () => {
       it.each<[string, TableOfContentsUtils.Markdown.IMarkdownHeading[]]>([
         [

programming_language: TypeScript
filename: tsconfig.json
change_type: ModificationType.MODIFY
diff: @@ -26,6 +26,9 @@
     },
     {
       "path": "../ui-components"
+    },
+    {
+      "path": "../rendermime-interfaces"
     }
   ]
 }

programming_language: JavaScript
filename: tsconfig.test.json
change_type: ModificationType.MODIFY
diff: @@ -26,6 +26,9 @@
     {
       "path": "../ui-components"
     },
+    {
+      "path": "../rendermime-interfaces"
+    },
     {
       "path": "."
     },

programming_language: TypeScript
filename: yarn.lock
change_type: ModificationType.MODIFY
diff: @@ -4908,6 +4908,7 @@ __metadata:
     "@jupyterlab/docregistry": ^4.1.0-beta.1
     "@jupyterlab/observables": ^5.1.0-beta.1
     "@jupyterlab/rendermime": ^4.1.0-beta.1
+    "@jupyterlab/rendermime-interfaces": ^3.9.0-beta.1
     "@jupyterlab/testing": ^4.1.0-beta.1
     "@jupyterlab/translation": ^4.1.0-beta.1
     "@jupyterlab/ui-components": ^4.1.0-beta.1

programming_language: Markdown