From: Mike Gabriel <sunweaver@debian.org>
Date: Tue, 5 Jun 2018 14:04:07 +0200
Subject: CVE-2018-7225

Bug-Debian: https://bugs.debian.org/894045
Origin: https://github.com/LibVNC/libvncserver/commit/b0c77391e6bd0a2305bbc9b37a2499af74ddd9ee

[sunweaver] port libvncserver patch over to tightvnc's VNC server code

---
 libvncserver/rfbserver.c | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)


--- a/Xvnc/programs/Xserver/hw/vnc/rfbserver.c
+++ b/Xvnc/programs/Xserver/hw/vnc/rfbserver.c
@@ -43,6 +43,9 @@
 #include <vncserverctrl.h>
 #endif
 
+/* PRIu32 */
+#include <inttypes.h>
+
 char updateBuf[UPDATE_BUF_SIZE];
 int ublen;
 
@@ -889,7 +892,23 @@
 
 	msg.cct.length = Swap32IfLE(msg.cct.length);
 
-	str = (char *)xalloc(msg.cct.length);
+	/* uint32_t input is passed to malloc()'s size_t argument,
+	 * to rfbReadExact()'s int argument, to rfbStatRecordMessageRcvd()'s int
+	 * argument increased of sz_rfbClientCutTextMsg, and to setXCutText()'s int
+	 * argument. Here we impose a limit of 1 MB so that the value fits
+	 * into all of the types to prevent from misinterpretation and thus
+	 * from accessing uninitialized memory (CVE-2018-7225) and also to
+	 * prevent from a denial-of-service by allocating to much memory in
+	 * the server. */
+	if (msg.cct.length > 1<<20) {
+	    rfbLog("rfbClientCutText: too big cut text length requested: %" PRIu32 "\n",
+	            msg.cct.length);
+	    rfbCloseSock(cl->sock);
+	    return;
+	}
+
+	/* Allow zero-length client cut text. */
+	str = (char *)calloc(msg.cct.length ? msg.cct.length : 1, 1);
 
 	if (str == NULL) {
 		rfbLogPerror("rfbProcessClientNormalMessage: not enough memory");
