eduardoboucas / staticman

💪 User-generated content for Git-powered websites
https://staticman.net
MIT License
2.41k stars 534 forks source link

Prevent javascript injection #436

Open MichaelRumpler opened 2 years ago

MichaelRumpler commented 2 years ago

Somebody sent a comment in my blog which injected some javascript. This may do some bad things, so I prevented it. This was very easy once I found out how the Transforms work.

I added these lines to lib/Transforms.js:

const antixss = (value) => {
  return String(value)
          .replace(/<script([^>]*)>(.*?)<\/script>/g, "&lt;script$1&gt;$2&lt;\/script&gt;")
          .replace(/(<a [^>]*?)href="javascript:[^"]*"/g, "$1")
          .replace(/(<a [^>]*?)href='javascript:[^']*'/g, "$1")
          .replace(/(<[^>]*) on\w+="[^"]*"/g, "$1")
          .replace(/(<[^>]*) on\w+='[^']*'/g, "$1");
}

module.exports = {
  md5,
  upcase,
  downcase,
  antixss
}

And then I just needed to activate that transform function for some fields in staticman.yml:

  transforms:
    email: md5
    name: antixss
    message: antixss

Now script tags do not get executed anymore and javascript event handlers get removed.

This may be something which others are also interested in.