skip to Main Content

I found many similar questions, but not one that would discuss this scenario.

app.get('/', function(req, res) {
  res.set('Content-Type', 'text/html');
  res.send(`<html>
<body>
Hello, World!
</body>
<script>
const test = ${JSON.stringify({html: '</script><script>alert(1)</script>'})};
</script>
  
</html>`);
});

This will produce HTML as follows:

<html>
<body>
Hello, World!
</body>
<script>
const test = {"html":"</script><script>alert(1)</script>"};
</script>
  
</html>

which as you can see, allows injection from JSON.

Here is a quick replit: https://stylishtrustysupercollider.gajus.repl.co/

Assuming that JSON contains arbitrary content that we have no control over, what is the correct way to handle this scenario?

Considering producing base64 encoded string but it feels like an overkill.

2

Answers


  1. Chosen as BEST ANSWER

    I am surprised this is necessary, but it appears that the answer is a variation of:

    // arbitrary JSON document
    const json = {
      html: '</script><script>alert(1)</script>'
    };
    
    const html = `
    <script>
    const test = JSON.parse(
      decodeURI(
        "${encodeURI(
          JSON.stringify(json)
        )}"
      )
    );
    </script>
    `;
    

    or to break it down...

    1. we are creating a JSON string with JSON.stringify
    2. we are encoding characters such as < and > using encodeURI
    3. we render the encoded string
    4. we decode the string with decodeURI
    5. we parse JSON

    encodeURI / decodeURI could also be replaced with alternative encoding mechanisms.

    As pointed out by Quentin, this is not safe unless you explicitly wrap the output with " rather than '. This seems like an easy mistake to make and not worth the risk.

    I took a quick glance at existing libraries for escaping/unescaping HTML and identified that it basically falls down to escaping &, <, >, ' and " characters.

    The following code is taken from html-escaper:

    /**
     * Copyright (C) 2017-present by Andrea Giammarchi - @WebReflection
     *
     * Permission is hereby granted, free of charge, to any person obtaining a copy
     * of this software and associated documentation files (the "Software"), to deal
     * in the Software without restriction, including without limitation the rights
     * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     * copies of the Software, and to permit persons to whom the Software is
     * furnished to do so, subject to the following conditions:
     *
     * The above copyright notice and this permission notice shall be included in
     * all copies or substantial portions of the Software.
     *
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
     * THE SOFTWARE.
     */
    
    const {replace} = '';
    
    // escape
    const es = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g;
    const ca = /[&<>'"]/g;
    
    const esca = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      "'": '&#39;',
      '"': '&quot;'
    };
    const pe = m => esca[m];
    
    /**
     * Safely escape HTML entities such as `&`, `<`, `>`, `"`, and `'`.
     * @param {string} es the input to safely escape
     * @returns {string} the escaped input, and it **throws** an error if
     *  the input type is unexpected, except for boolean and numbers,
     *  converted as string.
     */
    export const escape = es => replace.call(es, ca, pe);
    
    
    // unescape
    const unes = {
      '&amp;': '&',
      '&#38;': '&',
      '&lt;': '<',
      '&#60;': '<',
      '&gt;': '>',
      '&#62;': '>',
      '&apos;': "'",
      '&#39;': "'",
      '&quot;': '"',
      '&#34;': '"'
    };
    const cape = m => unes[m];
    
    /**
     * Safely unescape previously escaped entities such as `&`, `<`, `>`, `"`,
     * and `'`.
     * @param {string} un a previously escaped string
     * @returns {string} the unescaped input, and it **throws** an error if
     *  the input type is unexpected, except for boolean and numbers,
     *  converted as string.
     */
    export const unescape = un => replace.call(un, es, cape);
    

    Using the latter approach/library is preferable over attempting to escape with encodeURI or similar approaches.


    1. Use an HTML aware template language (which will take care of any escaping needed to make it safe to insert the string in a "normal" (i.e. not in the middle of a <script> element) part of document
    2. Store the data in an attribute instead of treating JSON as JS source code (so that HTML escaping is sufficient).

    e.g.

    server.js

    const express = require('express');
    const app = express();
    
    app.set('view engine', 'ejs');
    
    app.get('/', function (req, res) {
        const foo = JSON.stringify({ html: '</script><script>alert(1)</script>' });
        res.render('index', { foo });
    });
    
    app.listen(8080);
    console.log('Server is listening on port 8080');
    

    views/index.ejs

    <!DOCTYPE html>
    <html>
        <body>
            Hello, World!
        </body>
        <script data-foo="<%= foo %>">
            const test = JSON.parse(document.currentScript.dataset.foo);
            console.log(test);
        </script>
    </html>
    

    You could replace step 1 with your own HTML escaping routines, but I generally prefer something tried and tested.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search