vercel / arg

Simple argument parsing
https://npmjs.com/arg
MIT License
1.23k stars 54 forks source link

ReDoS vulnerability in index.js #70

Open d1tto opened 1 year ago

d1tto commented 1 year ago

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 ^-?\d*(\.(?=\d))?\d*$ that can be triggered by the below PoC:

const arg = require('arg');
const args = arg(
    {
        '--foo': String
    },        {
        argv: ['hello', '--foo', '-' + '0'.repeat(60000) + '-']
    }
);

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 safeMatch(string) {
    const RE2 = require("re2")
    let re = new RE2(/^-?\d*(\.)?(\d*)$/)
    let res = re.match(string)
    if (res != null) {
        group1 = res[1]
        if (group1 !== null) {
            group2 = res[2]
            if (/^\d/.test(group2)) {
                return res
            } else {
                return null
            }
        }
        return res
    }
    return res
}

console.log(safeMatch("-1.1")) // [ '-1.1', '.', '1', index: 0, input: '-1.1', groups: undefined ]
console.log(safeMatch("-1."))  // null
console.log(safeMatch("."))    // null

Using this code snippet to replace the code in line 156 argv[i + 1].match(/^-?\d*(\.(?=\d))?\d*$/) can repair this vulnerability. The match semantics of the new regex + code constraint above is equivalent to the original regex.

I hope the author can adopt this repair solution and I would be very grateful. Thanks!