logo

Database

Javascript Dangerously Set Innerhtml

Description

Detects potentially dangerous uses of innerHTML in JavaScript code where unsanitized or user-controlled input could be inserted into the DOM, creating Cross-Site Scripting (XSS) vulnerabilities. When untrusted content is directly assigned to innerHTML, malicious JavaScript can be executed in the context of the application.

Weakness:

371 - DOM-Based cross-site scripting (XSS)

Category: Unexpected Injection

Detection Strategy

    Look for assignments or modifications to element.innerHTML properties in JavaScript code

    Check if the value being assigned to innerHTML comes from untrusted sources like user input, network responses, or URL parameters

    Verify if the input is properly sanitized before being assigned to innerHTML - mark as vulnerable if raw/unsanitized data is used

    Report a vulnerability when innerHTML is set with potentially dangerous content without proper HTML escaping or sanitization

Vulnerable code example

import React from 'react';

const VulnerableComponent = () => {
  // Unsafe: directly using user input in dangerouslySetInnerHTML without sanitization
  const userProvidedHtml = req.params.content;
  
  return (
    <div>...

✅ Secure code example

import React from 'react';
import DOMPurify from 'dompurify'; // Import DOMPurify for sanitization

const SecureComponent = () => {
  const userProvidedHtml = req.params.content;
  // Sanitize user input to prevent XSS attacks
  const sanitizedHtml = DOMPurify.sanitize(userProvidedHtml);
  ...