Skip to content

Commit

Permalink
security: replace unsafe /X+$/ idiom with rtrim
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 Apr 26, 2018
1 parent 4cc97f6 commit 0ceca90
Showing 1 changed file with 33 additions and 11 deletions.
44 changes: 33 additions & 11 deletions lib/marked.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,32 @@
* https://github.com/markedjs/marked
*/

// 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;
}

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 (0 < curr &&
((allButC && str.charAt(curr - 1) !== c) ||
(!allButC && str.charAt(curr - 1) === c))) {
curr--;
}

return str.substr(0, curr);
}

;(function(root) {
'use strict';

Expand Down Expand Up @@ -216,7 +242,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 All @@ -238,15 +264,11 @@ Lexer.prototype.token = function(src, top) {
src = src.substring(cap[0].length);
// cap[2] might be ' HEADING # '
item = (cap[2] || '').trim();
if (item.slice(-1) === '#') {
// NB replace(/#+$/) is quadratic on mismatch because it's unanchored,
// so we protect with if-check to ensure it won't mismatch.
if (this.options.pedantic) {
item = item.replace(/#+$/, '');
} else {
// CM requires a space before additional #s
item = item.replace(/(\s|^)#+$/, '');
}
if (this.options.pedantic) {
item = rtrim(item, '#');
} else {
// CM requires a space before additional #s
item = item.replace(/(\s|^)#+$/, '');
}
item = item.trim();
this.tokens.push({
Expand Down Expand Up @@ -1278,7 +1300,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

0 comments on commit 0ceca90

Please sign in to comment.