b3b6ef
diff --git a/ssh-keyscan.c b/ssh-keyscan.c
b3b6ef
index d29a03b4..d7283136 100644
b3b6ef
--- a/ssh-keyscan.c
b3b6ef
+++ b/ssh-keyscan.c
b3b6ef
@@ -490,6 +490,15 @@ congreet(int s)
b3b6ef
 		return;
b3b6ef
 	}
b3b6ef
 
b3b6ef
+	/*
b3b6ef
+	 * Read the server banner as per RFC4253 section 4.2.  The "SSH-"
b3b6ef
+	 * protocol identification string may be preceeded by an arbitarily
b3b6ef
+	 * large banner which we must read and ignore.  Loop while reading
b3b6ef
+	 * newline-terminated lines until we have one starting with "SSH-".
b3b6ef
+	 * The ID string cannot be longer than 255 characters although the
b3b6ef
+	 * preceeding banner lines may (in which case they'll be discarded
b3b6ef
+	 * in multiple iterations of the outer loop).
b3b6ef
+	 */
b3b6ef
 	for (;;) {
b3b6ef
 		memset(buf, '\0', sizeof(buf));
b3b6ef
 		bufsiz = sizeof(buf);
b3b6ef
@@ -517,6 +526,11 @@ congreet(int s)
b3b6ef
 		conrecycle(s);
b3b6ef
 		return;
b3b6ef
 	}
b3b6ef
+	if (cp >= buf + sizeof(buf)) {
b3b6ef
+		error("%s: greeting exceeds allowable length", c->c_name);
b3b6ef
+		confree(s);
b3b6ef
+		return;
b3b6ef
+	}
b3b6ef
 	if (*cp != '\n' && *cp != '\r') {
b3b6ef
 		error("%s: bad greeting", c->c_name);
b3b6ef
 		confree(s);