csharp.razor.security.html-raw-json.html-raw-json

profile photo of returntocorpreturntocorp
Author
unknown
Download Count*

Unencoded JSON in HTML context is vulnerable to cross-site scripting, because </script> is not properly encoded.

Run Locally

Run in CI

Defintion

rules:
  - id: html-raw-json
    patterns:
      - pattern-either:
          - pattern: "@Html.Raw(Json.Encode(...))"
          - pattern: "@Html.Raw(JsonConvert.SerializeObject(...))"
          - pattern: "@Html.Raw(...ToJson(...))"
    message: Unencoded JSON in HTML context is vulnerable to cross-site scripting,
      because `</script>` is not properly encoded.
    languages:
      - generic
    metadata:
      cwe:
        - "CWE-79: Improper Neutralization of Input During Web Page Generation
          ('Cross-site Scripting')"
      category: security
      technology:
        - razor
      owasp:
        - A07:2017 - Cross-Site Scripting (XSS)
        - A03:2021 - Injection
      references:
        - https://owasp.org/Top10/A03_2021-Injection
      cwe2022-top25: true
      cwe2021-top25: true
      subcategory:
        - audit
      likelihood: LOW
      impact: MEDIUM
      confidence: LOW
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
    paths:
      include:
        - "*.cshtml"
    severity: ERROR

Examples

html-raw-json.cshtml

<script>
    // ruleid: html-raw-json
    var a = @Html.Raw(SomeFunc(Model).ToJson());
</script>
<script type="text/javascript">
    SomeOtherCall();
    // ruleid: html-raw-json
    var obj = @Html.Raw(Json.Encode(Model));
    alert("hello world");
</script>
<script>
    // ruleid: html-raw-json
    var obj = @Html.Raw(JsonConvert.SerializeObject(Model));
</script>
<script>
    // ok: html-raw-json
    var obj = @Html.Raw(Model.HtmlField);
</script>
// ok: html-raw-json
<div data-json="@Json.Encode(Model)"></div>