From 298460a2adaabd2f28f417a0f106cb3b68d27df9 Mon Sep 17 00:00:00 2001
From: Fabian Ising <Murgeye@users.noreply.github.com>
Date: Fri, 24 Jul 2020 19:40:48 +0200
Subject: [PATCH 2/2] Detect extra data after STARTTLS responses in SMTP and
 POP3 and exit (#388)

* Detect extra data after STLS response and return error

* Detect extra data after SMTP STARTTLS response and return error
---
 src/low-level/pop3/mailpop3.c | 8 ++++++++
 src/low-level/smtp/mailsmtp.c | 8 ++++++++
 2 files changed, 16 insertions(+)

diff --git a/src/low-level/pop3/mailpop3.c b/src/low-level/pop3/mailpop3.c
index ab9535b..e2124bf 100644
--- a/src/low-level/pop3/mailpop3.c
+++ b/src/low-level/pop3/mailpop3.c
@@ -959,6 +959,14 @@ int mailpop3_stls(mailpop3 * f)
 
   if (r != RESPONSE_OK)
     return MAILPOP3_ERROR_STLS_NOT_SUPPORTED;
+
+  // Detect if the server send extra data after the STLS response.
+  // This *may* be a "response injection attack".
+  if (f->pop3_stream->read_buffer_len != 0) {
+    // Since it is also protocol violation, exit.
+    // There is no error type for STARTTLS errors in POP3
+    return MAILPOP3_ERROR_SSL;
+  }
   
   return MAILPOP3_NO_ERROR;
 }
diff --git a/src/low-level/smtp/mailsmtp.c b/src/low-level/smtp/mailsmtp.c
index b7fc459..3145cad 100644
--- a/src/low-level/smtp/mailsmtp.c
+++ b/src/low-level/smtp/mailsmtp.c
@@ -1111,6 +1111,14 @@ int mailesmtp_starttls(mailsmtp * session)
     return MAILSMTP_ERROR_STREAM;
   r = read_response(session);
 
+  // Detect if the server send extra data after the STARTTLS response.
+  // This *may* be a "response injection attack".
+  if (session->stream->read_buffer_len != 0) {
+    // Since it is also protocol violation, exit.
+    // There is no general error type for STARTTLS errors in SMTP
+    return MAILSMTP_ERROR_SSL;
+  }
+
   switch (r) {
   case 220:
     return MAILSMTP_NO_ERROR;
-- 
2.26.2

