Created
February 26, 2015 20:03
-
-
Save rpiesnikowski/6a5c097cf7dd4f10b4ac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.regex.Pattern; | |
trait XssFilter { | |
def filter(input: String): String = { | |
var value: String = input; | |
if (value != null) { | |
// NOTE: It's highly recommended to use the ESAPI library and uncomment the following line to | |
// avoid encoded attacks. | |
// value = ESAPI.encoder().canonicalize(value); | |
// Avoid null characters | |
value = value.replaceAll("", ""); | |
// Avoid anything between script tags | |
var scriptPattern: Pattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE) | |
value = scriptPattern.matcher(value).replaceAll(""); | |
// Avoid anything in a src='...' type of expression | |
scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); | |
value = scriptPattern.matcher(value).replaceAll(""); | |
scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); | |
value = scriptPattern.matcher(value).replaceAll(""); | |
// Remove any lonesome </script> tag | |
scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE); | |
value = scriptPattern.matcher(value).replaceAll(""); | |
// Remove any lonesome <script ...> tag | |
scriptPattern = Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); | |
value = scriptPattern.matcher(value).replaceAll(""); | |
// Avoid eval(...) expressions | |
scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); | |
value = scriptPattern.matcher(value).replaceAll(""); | |
// Avoid expression(...) expressions | |
scriptPattern = Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); | |
value = scriptPattern.matcher(value).replaceAll(""); | |
// Avoid javascript:... expressions | |
scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE); | |
value = scriptPattern.matcher(value).replaceAll(""); | |
// Avoid vbscript:... expressions | |
scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE); | |
value = scriptPattern.matcher(value).replaceAll(""); | |
// Avoid onload= expressions | |
scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); | |
value = scriptPattern.matcher(value).replaceAll(""); | |
} | |
return value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment