Add some more chars to the sanitizer function

This commit is contained in:
James Agnew 2019-08-12 08:16:38 -04:00
parent 7d62064dc0
commit bfaf617142
2 changed files with 48 additions and 3 deletions

View File

@ -163,7 +163,16 @@ public class UrlUtil {
if (theString != null) { if (theString != null) {
for (int i = 0; i < theString.length(); i++) { for (int i = 0; i < theString.length(); i++) {
char nextChar = theString.charAt(i); char nextChar = theString.charAt(i);
if (nextChar == '<' || nextChar == '"') { switch (nextChar) {
case '\'':
case '"':
case '<':
case '>':
case '\n':
case '\r':
return true;
}
if (nextChar < ' ') {
return true; return true;
} }
} }
@ -348,7 +357,17 @@ public class UrlUtil {
/** /**
* This method specifically HTML-encodes the &quot; and * This method specifically HTML-encodes the &quot; and
* &lt; characters in order to prevent injection attacks * &lt; characters in order to prevent injection attacks.
*
* The following characters are escaped:
* <ul>
* <li>&apos;</li>
* <li>&quot;</li>
* <li>&lt;</li>
* <li>&gt;</li>
* <li>\n (newline)</li>
* </ul>
*
*/ */
public static String sanitizeUrlPart(CharSequence theString) { public static String sanitizeUrlPart(CharSequence theString) {
if (theString == null) { if (theString == null) {
@ -364,6 +383,10 @@ public class UrlUtil {
char nextChar = theString.charAt(j); char nextChar = theString.charAt(j);
switch (nextChar) { switch (nextChar) {
/*
* NB: If you add a constant here, you also need to add it
* to isNeedsSanitization()!!
*/
case '\'': case '\'':
buffer.append("&apos;"); buffer.append("&apos;");
break; break;
@ -373,8 +396,19 @@ public class UrlUtil {
case '<': case '<':
buffer.append("&lt;"); buffer.append("&lt;");
break; break;
case '>':
buffer.append("&gt;");
break;
case '\n':
buffer.append("&#10;");
break;
case '\r':
buffer.append("&#13;");
break;
default: default:
buffer.append(nextChar); if (nextChar >= ' ') {
buffer.append(nextChar);
}
break; break;
} }

View File

@ -59,4 +59,15 @@ public class UrlUtilTest {
} }
@Test
public void testSanitize() {
assertEquals(" &apos; ", UrlUtil.sanitizeUrlPart(" ' "));
assertEquals(" &lt; ", UrlUtil.sanitizeUrlPart(" < "));
assertEquals(" &gt; ", UrlUtil.sanitizeUrlPart(" > "));
assertEquals(" &quot; ", UrlUtil.sanitizeUrlPart(" \" "));
assertEquals(" &#10; ", UrlUtil.sanitizeUrlPart(" \n "));
assertEquals(" &#13; ", UrlUtil.sanitizeUrlPart(" \r "));
assertEquals(" ", UrlUtil.sanitizeUrlPart(" \0 "));
}
} }