6ce3da
From bf22713507fe1fc3a2c4b525cf0a88c2dc87a3a2 Mon Sep 17 00:00:00 2001
6ce3da
From: Joel Hockey <joel.hockey@gmail.com>
6ce3da
Date: Sun, 16 Aug 2020 17:19:35 -0700
6ce3da
Subject: [PATCH] Validate UTF8 in xmlEncodeEntities
6ce3da
6ce3da
Code is currently assuming UTF-8 without validating. Truncated UTF-8
6ce3da
input can cause out-of-bounds array access.
6ce3da
6ce3da
Adds further checks to partial fix in 50f06b3e.
6ce3da
6ce3da
Fixes #178
6ce3da
---
6ce3da
 entities.c | 16 +++++++++++++++-
6ce3da
 1 file changed, 15 insertions(+), 1 deletion(-)
6ce3da
6ce3da
diff --git a/entities.c b/entities.c
6ce3da
index 37b99a56..1a8f86f0 100644
6ce3da
--- a/entities.c
6ce3da
+++ b/entities.c
6ce3da
@@ -704,11 +704,25 @@ xmlEncodeEntitiesInternal(xmlDocPtr doc, const xmlChar *input, int attr) {
6ce3da
 	    } else {
6ce3da
 		/*
6ce3da
 		 * We assume we have UTF-8 input.
6ce3da
+		 * It must match either:
6ce3da
+		 *   110xxxxx 10xxxxxx
6ce3da
+		 *   1110xxxx 10xxxxxx 10xxxxxx
6ce3da
+		 *   11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
6ce3da
+		 * That is:
6ce3da
+		 *   cur[0] is 11xxxxxx
6ce3da
+		 *   cur[1] is 10xxxxxx
6ce3da
+		 *   cur[2] is 10xxxxxx if cur[0] is 111xxxxx
6ce3da
+		 *   cur[3] is 10xxxxxx if cur[0] is 1111xxxx
6ce3da
+		 *   cur[0] is not 11111xxx
6ce3da
 		 */
6ce3da
 		char buf[11], *ptr;
6ce3da
 		int val = 0, l = 1;
6ce3da
 
6ce3da
-		if (*cur < 0xC0) {
6ce3da
+		if (((cur[0] & 0xC0) != 0xC0) ||
6ce3da
+		    ((cur[1] & 0xC0) != 0x80) ||
6ce3da
+		    (((cur[0] & 0xE0) == 0xE0) && ((cur[2] & 0xC0) != 0x80)) ||
6ce3da
+		    (((cur[0] & 0xF0) == 0xF0) && ((cur[3] & 0xC0) != 0x80)) ||
6ce3da
+		    (((cur[0] & 0xF8) == 0xF8))) {
6ce3da
 		    xmlEntitiesErr(XML_CHECK_NOT_UTF8,
6ce3da
 			    "xmlEncodeEntities: input not UTF-8");
6ce3da
 		    if (doc != NULL)
6ce3da
-- 
6ce3da
GitLab
6ce3da