Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug in Text Visualization Code #1226

Open
peiyangL opened this issue Dec 23, 2023 · 0 comments
Open

Bug in Text Visualization Code #1226

peiyangL opened this issue Dec 23, 2023 · 0 comments

Comments

@peiyangL
Copy link

Overview

The affected code snippet can be found here: https://github.com/pytorch/captum/blob/master/captum/attr/_utils/visualization.py#L829-L836

Within the format_word_importances function, the word variable is not being properly escaped before being incorporated into the HTML template. This oversight could potentially result in incorrect visualization outputs or even present a security vulnerability if untrusted input is used. Below, I provide two examples to demonstrate these issues:

To Reproduce

Case 1: Commented-out User Input

from captum.attr import visualization

words = ['hello', 'world', 'entrar<!--#exec', 'cmd', '"ls', '-->']
scores = [0 for _ in words]

_ = visualization.visualize_text([visualization.VisualizationDataRecord(
    word_attributions=scores,
    raw_input_ids=words,
    attr_score=sum(scores),
    pred_class=0,
    pred_prob=0,
    true_class=0,
    attr_class=0,
    convergence_score=0
)])
image

The last four words are not displayed correctly.

Case 2: Cross-Site Scripting (XSS) in a Jupyter Environment

from captum.attr import visualization

words = ['hello', 'world', "x<script>alert('xss');</script>x"]
scores = [-1, 0, 1]

_ = visualization.visualize_text([visualization.VisualizationDataRecord(
    word_attributions=scores,
    raw_input_ids=words,
    attr_score=sum(scores),
    pred_class=0,
    pred_prob=0,
    true_class=0,
    attr_class=0,
    convergence_score=0
)])
image

Solution

the fix for this issue is straightforward—by implementing proper escaping for the word variable. Just modify the line 829.

word = format_special_tokens(word)

->

import html
word = html.escape(word)
# word = html.escape(format_special_tokens(word)) # if you want to keep the format_special_tokens function
@peiyangL peiyangL changed the title Bug in Text Visualization Code - Improper Escaping Leading to Incorrect Visualization and Security Issues Bug in Text Visualization Code Dec 23, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant