Skip to content

Commit

Permalink
security: rtrim, not unsafe /X+$/ idiom
Browse files Browse the repository at this point in the history
Problem:
replace(/X+$/, '') is vulnerable to REDOS

Solution:
Replace all instances I could find with a custom rtrim
  • Loading branch information
davisjam committed May 9, 2018
1 parent 579f7bf commit 7e5a727
Showing 1 changed file with 34 additions and 2 deletions.
36 changes: 34 additions & 2 deletions lib/marked.js
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ Lexer.prototype.token = function(src, top) {
this.tokens.push({
type: 'code',
text: !this.options.pedantic
? cap.replace(/\n+$/, '')
? rtrim(cap, '\n')
: cap
});
continue;
Expand Down Expand Up @@ -1303,7 +1303,7 @@ function resolveUrl(base, href) {
if (/^[^:]+:\/*[^/]*$/.test(base)) {
baseUrls[' ' + base] = base + '/';
} else {
baseUrls[' ' + base] = base.replace(/[^/]*$/, '');
baseUrls[' ' + base] = rtrim(base, '/', true);
}
}
base = baseUrls[' ' + base];
Expand Down Expand Up @@ -1355,6 +1355,38 @@ function splitCells(tableRow, count) {
return cells;
}

// Return str with all trailing {c | all but c} removed
// allButC: Default false
function rtrim(str, c, allButC) {
if (typeof allButC === 'undefined') {
allButC = false;
} else {
allButC = true;
}
var mustMatchC = !allButC;

if (str.length === 0) {
return '';
}

// ix+1 of leftmost that fits description
// i.e. the length of the string we should return
var curr = str.length;

while (curr > 0) {
var currChar = str.charAt(curr - 1);
if (mustMatchC && currChar === c) {
curr--;
} else if (!mustMatchC && currChar !== c) {
curr--;
} else {
break;
}
}

return str.substr(0, curr);
}

/**
* Marked
*/
Expand Down

0 comments on commit 7e5a727

Please sign in to comment.