diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/UrlUtil.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/UrlUtil.java
index 727d27793b4..765876b176c 100644
--- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/UrlUtil.java
+++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/UrlUtil.java
@@ -163,7 +163,16 @@ public class UrlUtil {
if (theString != null) {
for (int i = 0; i < theString.length(); 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;
}
}
@@ -348,7 +357,17 @@ public class UrlUtil {
/**
* This method specifically HTML-encodes the " and
- * < characters in order to prevent injection attacks
+ * < characters in order to prevent injection attacks.
+ *
+ * The following characters are escaped:
+ *
+ * - '
+ * - "
+ * - <
+ * - >
+ * - \n (newline)
+ *
+ *
*/
public static String sanitizeUrlPart(CharSequence theString) {
if (theString == null) {
@@ -364,6 +383,10 @@ public class UrlUtil {
char nextChar = theString.charAt(j);
switch (nextChar) {
+ /*
+ * NB: If you add a constant here, you also need to add it
+ * to isNeedsSanitization()!!
+ */
case '\'':
buffer.append("'");
break;
@@ -373,8 +396,19 @@ public class UrlUtil {
case '<':
buffer.append("<");
break;
+ case '>':
+ buffer.append(">");
+ break;
+ case '\n':
+ buffer.append("
");
+ break;
+ case '\r':
+ buffer.append("
");
+ break;
default:
- buffer.append(nextChar);
+ if (nextChar >= ' ') {
+ buffer.append(nextChar);
+ }
break;
}
diff --git a/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/UrlUtilTest.java b/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/UrlUtilTest.java
index e949a6275dd..0083ba8e09f 100644
--- a/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/UrlUtilTest.java
+++ b/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/UrlUtilTest.java
@@ -59,4 +59,15 @@ public class UrlUtilTest {
}
+ @Test
+ public void testSanitize() {
+ assertEquals(" ' ", UrlUtil.sanitizeUrlPart(" ' "));
+ assertEquals(" < ", UrlUtil.sanitizeUrlPart(" < "));
+ assertEquals(" > ", UrlUtil.sanitizeUrlPart(" > "));
+ assertEquals(" " ", UrlUtil.sanitizeUrlPart(" \" "));
+ assertEquals("
", UrlUtil.sanitizeUrlPart(" \n "));
+ assertEquals("
", UrlUtil.sanitizeUrlPart(" \r "));
+ assertEquals(" ", UrlUtil.sanitizeUrlPart(" \0 "));
+ }
+
}