From adba6f0c3e5c5607c4822b9120322eb7e9a77891 Mon Sep 17 00:00:00 2001
From: Shugo Maeda <shugo@ruby-lang.org>
Date: Wed, 7 Jul 2021 16:09:03 +0900
Subject: [PATCH] This fixes CVE-2021-32066. Reported by Alexandr Savca in
 <https://hackerone.com/reports/1178562>.

Reference:https://github.com/ruby/net-imap/commit/adba6f0c3e5c5607c4822b9120322eb7e9a77891
---
 lib/net/imap.rb            |  8 +++++++-
 test/net/imap/test_imap.rb | 31 +++++++++++++++++++++++++++++++
 2 files changed, 38 insertions(+), 1 deletion(-)

diff --git a/lib/net/imap.rb b/lib/net/imap.rb
index da7d0d5..eedcb4f 100644
--- a/lib/net/imap.rb
+++ b/lib/net/imap.rb
@@ -1213,12 +1213,14 @@ module Net
       end
       resp = @tagged_responses.delete(tag)
       case resp.name
+      when /\A(?:OK)\z/ni
+        return resp
       when /\A(?:NO)\z/ni
         raise NoResponseError, resp
       when /\A(?:BAD)\z/ni
         raise BadResponseError, resp
       else
-        return resp
+        raise UnknownResponseError, resp
       end
     end
 
@@ -3714,6 +3716,10 @@ module Net
     class ByeResponseError < ResponseError
     end
 
+    # Error raised upon an unknown response from the server.
+    class UnknownResponseError < ResponseError
+    end
+
     RESPONSE_ERRORS = Hash.new(ResponseError)
     RESPONSE_ERRORS["NO"] = NoResponseError
     RESPONSE_ERRORS["BAD"] = BadResponseError
diff --git a/test/net/imap/test_imap.rb b/test/net/imap/test_imap.rb
index 41f25fe..9247062 100644
--- a/test/net/imap/test_imap.rb
+++ b/test/net/imap/test_imap.rb
@@ -110,6 +110,16 @@ class IMAPTest < Test::Unit::TestCase
         end
       end
     end
+
+    def test_starttls_stripping
+      starttls_stripping_test do |port|
+        imap = Net::IMAP.new("localhost", :port => port)
+        assert_raise(Net::IMAP::UnknownResponseError) do
+          imap.starttls(:ca_file => CA_FILE)
+        end
+        imap
+      end
+    end
   end
 
   if defined?(OpenSSL::SSL)
@@ -760,6 +770,27 @@ EOF
     end
   end
 
+  def starttls_stripping_test
+    server = create_tcp_server
+    port = server.addr[1]
+    start_server do
+      sock = server.accept
+      begin
+        sock.print("* OK test server\r\n")
+        sock.gets
+        sock.print("RUBY0001 BUG unhandled command\r\n")
+      ensure
+        sock.close
+        server.close
+      end
+    end
+    begin
+      imap = yield(port)
+    ensure
+      imap.disconnect if imap && !imap.disconnected?
+    end
+  end
+
   def create_tcp_server
     return TCPServer.new(server_addr, 0)
   end
-- 
1.8.3.1

