From 242a10fbb12dbdc12d254bd8fc8669a0ac055304 Mon Sep 17 00:00:00 2001
From: Patrick Griffis <pgriffis@igalia.com>
Date: Wed, 5 Feb 2025 14:39:42 -0600
Subject: [PATCH] sniffer: Fix potential overflow

Upstream-Status: Backport [https://gitlab.gnome.org/GNOME/libsoup/-/commit/242a10fbb12dbdc12d254bd8fc8669a0ac055304]
CVE: CVE-2025-2784
Signed-off-by: Vijay Anusuri <vanusuri@mvista.com>
---
 libsoup/content-sniffer/soup-content-sniffer.c | 2 +-
 tests/meson.build                              | 4 +++-
 tests/sniffing-test.c                          | 5 +++++
 tests/soup-tests.gresource.xml                 | 1 +
 4 files changed, 10 insertions(+), 2 deletions(-)

diff --git a/libsoup/content-sniffer/soup-content-sniffer.c b/libsoup/content-sniffer/soup-content-sniffer.c
index d7c46c8..648ea04 100644
--- a/libsoup/content-sniffer/soup-content-sniffer.c
+++ b/libsoup/content-sniffer/soup-content-sniffer.c
@@ -666,7 +666,7 @@ sniff_feed_or_html (SoupContentSniffer *sniffer, GBytes *buffer)
 		pos = 3;
 
  look_for_tag:
-	if (pos > resource_length)
+	if (pos >= resource_length)
 		goto text_html;
 
 	if (skip_insignificant_space (resource, &pos, resource_length))
diff --git a/tests/meson.build b/tests/meson.build
index 7851e57..450becb 100644
--- a/tests/meson.build
+++ b/tests/meson.build
@@ -92,7 +92,9 @@ tests = [
   {'name': 'session'},
   {'name': 'server-auth'},
   {'name': 'server'},
-  {'name': 'sniffing'},
+  {'name': 'sniffing',
+    'depends': [test_resources],
+  },
   {'name': 'socket'},
   {'name': 'ssl',
    'dependencies': [gnutls_dep],
diff --git a/tests/sniffing-test.c b/tests/sniffing-test.c
index 6116719..b542817 100644
--- a/tests/sniffing-test.c
+++ b/tests/sniffing-test.c
@@ -512,6 +512,11 @@ main (int argc, char **argv)
 			      "type/text_html; charset=UTF-8/test.html => text/html; charset=UTF-8",
 			      do_sniffing_test);
 
+        /* Test hitting skip_insignificant_space() with number of bytes equaling resource_length. */
+	g_test_add_data_func ("/sniffing/whitespace",
+			      "type/text_html/whitespace.html => text/html",
+			      do_sniffing_test);
+
 	/* Test that disabling the sniffer works correctly */
 	g_test_add_data_func ("/sniffing/disabled",
 			      "/text_or_binary/home.gif",
diff --git a/tests/soup-tests.gresource.xml b/tests/soup-tests.gresource.xml
index 9c08d17..cbef1d4 100644
--- a/tests/soup-tests.gresource.xml
+++ b/tests/soup-tests.gresource.xml
@@ -25,5 +25,6 @@
     <file>resources/text.txt</file>
     <file>resources/text_binary.txt</file>
     <file>resources/tux.webp</file>
+    <file>resources/whitespace.html</file>
   </gresource>
 </gresources>
-- 
2.25.1

