From eea5868120509c245216c4b5c2d4b5db1c593d0e Mon Sep 17 00:00:00 2001
From: Nobuyoshi Nakada <nobu@ruby-lang.org>
Date: Thu, 27 Jul 2023 16:16:30 +0800
Subject: [PATCH] ruby: Fix quadratic backtracking on invalid port number

Upstream-Status: Backport [https://github.com/ruby/uri/commit/9d7bcef1e6ad23c9c6e4932f297fb737888144c8]
CVE: CVE-2023-36617
Signed-off-by: Meenali Gupta <meenali.gupta@windriver.com>
---
 lib/uri/rfc3986_parser.rb |  2 +-
 test/uri/test_parser.rb   | 10 ++++++++++
 2 files changed, 11 insertions(+), 1 deletion(-)

diff --git a/lib/uri/rfc3986_parser.rb b/lib/uri/rfc3986_parser.rb
index 3c89311..cde3ea7 100644
--- a/lib/uri/rfc3986_parser.rb
+++ b/lib/uri/rfc3986_parser.rb
@@ -101,7 +101,7 @@ module URI
         QUERY: /\A(?:%\h\h|[!$&-.0-;=@-Z_a-z~\/?])*\z/,
         FRAGMENT: /\A(?:%\h\h|[!$&-.0-;=@-Z_a-z~\/?])*\z/,
         OPAQUE: /\A(?:[^\/].*)?\z/,
-        PORT: /\A[\x09\x0a\x0c\x0d ]*\d*[\x09\x0a\x0c\x0d ]*\z/,
+        PORT: /\A[\x09\x0a\x0c\x0d ]*+\d*[\x09\x0a\x0c\x0d ]*\z/,
       }
     end

diff --git a/test/uri/test_parser.rb b/test/uri/test_parser.rb
index 01ed32a..81c2210 100644
--- a/test/uri/test_parser.rb
+++ b/test/uri/test_parser.rb
@@ -75,4 +75,14 @@ class URI::TestParser < Test::Unit::TestCase
       end
     end
   end
+
+  def test_rfc3986_port_check
+    pre = ->(length) {"\t" * length + "a"}
+    uri = URI.parse("http://my.example.com")
+    assert_linear_performance((1..5).map {|i| 10**i}, pre: pre) do |port|
+      assert_raise(URI::InvalidComponentError) do
+        uri.port = port
+      end
+    end
+  end
 end
--
2.40.0
