From 1e6893546c526c0961930b6b60a6aba42692dba9 Mon Sep 17 00:00:00 2001
From: Harlan Stenn <stenn@ntp.org>
Date: Sat, 13 May 2023 05:23:33 UTC
Subject: [PATCH] refclock_palisade:fix an out-of-bounds write in praecis_parse

Conflict:NA
Reference:https://www.eecis.udel.edu/~ntp/ntp_spool//ntp4/ntp-4.2.8p15-3806-3807.patch

---
 ntpd/refclock_palisade.c | 50 ++++++++++++++++++++++++++++++++++------
 1 file changed, 43 insertions(+), 7 deletions(-)

diff --git a/ntpd/refclock_palisade.c b/ntpd/refclock_palisade.c
index cb68255..66bfbc8 100644
--- a/ntpd/refclock_palisade.c
+++ b/ntpd/refclock_palisade.c
@@ -1225,9 +1225,9 @@ palisade_poll (
 		return;  /* using synchronous packet input */
 
 	if(up->type == CLK_PRAECIS) {
-		if(write(peer->procptr->io.fd,"SPSTAT\r\n",8) < 0)
+		if (write(peer->procptr->io.fd,"SPSTAT\r\n",8) < 0) {
 			msyslog(LOG_ERR, "Palisade(%d) write: %m:",unit);
-		else {
+		} else {
 			praecis_msg = 1;
 			return;
 		}
@@ -1249,20 +1249,53 @@ praecis_parse (
 
 	pp = peer->procptr;
 
-	memcpy(buf+p,rbufp->recv_space.X_recv_buffer, rbufp->recv_length);
+	if (p + rbufp->recv_length >= sizeof buf) {
+		struct palisade_unit *up;
+		up = pp->unitptr;
+
+		/*
+		 * We COULD see if there is a \r\n in the incoming
+		 * buffer before it overflows, and then process the
+		 * current line.
+		 *
+		 * Similarly, if we already have a hunk of data that
+		 * we're now flushing, that will cause the line of
+		 * data we're in the process of collecting to be garbage.
+		 *
+		 * Since we now check for this overflow and log when it
+		 * happens, we're now in a better place to easily see
+		 * what's going on and perhaps better choices can be made.
+		 */
+
+		/* Do we need to log the size of the overflow? */
+		msyslog(LOG_ERR, "Palisade(%d) praecis_parse(): input buffer overflow",
+			up->unit);
+
+		p = 0;
+		praecis_msg = 0;
+
+		refclock_report(peer, CEVNT_BADREPLY);
+
+		return;
+	}
+
+	memcpy(buf+p, rbufp->recv_buffer, rbufp->recv_length);
 	p += rbufp->recv_length;
 
-	if(buf[p-2] == '\r' && buf[p-1] == '\n') {
+	if (   p >= 2
+	    && buf[p-2] == '\r' 
+	    && buf[p-1] == '\n') {
 		buf[p-2] = '\0';
 		record_clock_stats(&peer->srcadr, buf);
 
 		p = 0;
 		praecis_msg = 0;
 
-		if (HW_poll(pp) < 0)
+		if (HW_poll(pp) < 0) {
 			refclock_report(peer, CEVNT_FAULT);
-
+		}
 	}
+	return;
 }
 
 static void
@@ -1407,7 +1440,10 @@ HW_poll (
 
 	/* Edge trigger */
 	if (up->type == CLK_ACUTIME)
-		write (pp->io.fd, "", 1);
+		if (write (pp->io.fd, "", 1) != 1)
+			msyslog(LOG_WARNING,
+				"Palisade(%d) HW_poll: failed to send trigger: %m",
+				up->unit);
 		
 	if (ioctl(pp->io.fd, TIOCMSET, &x) < 0) { 
 #ifdef DEBUG
-- 
2.33.0


