From 7e7b8ed89c93b5f95367eeab1b4f06fc2ac83581 Mon Sep 17 00:00:00 2001
From: Daiki Ueno <ueno@gnu.org>
Date: Wed, 7 Jun 2023 16:44:00 +0200
Subject: [PATCH] lib: suppress false-positive -Wanalyzer-out-of-bounds

GCC analyzer from GCC 13 reports this:

  verify-high.c:1471:21: error: stack-based buffer over-read [CWE-126] [-Werror=analyzer-out-of-bounds]
   1471 |                 if (gnutls_x509_trust_list_get_issuer(
        |                     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   1472 |                             list, cert_list[i - 1], &issuer,

This is false-positive, as i is always in a range 0 < i < cert_list_size.

Signed-off-by: Daiki Ueno <ueno@gnu.org>

Reference: https://gitlab.com/gnutls/gnutls/-/commit/7e7b8ed89c93b5f95367eeab1b4f06fc2ac83581
Conflict: NA

---
 lib/x509/verify-high.c | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)

diff --git a/lib/x509/verify-high.c b/lib/x509/verify-high.c
index 2c070b0..02d2f0f 100644
--- a/lib/x509/verify-high.c
+++ b/lib/x509/verify-high.c
@@ -1421,7 +1421,7 @@ gnutls_x509_trust_list_verify_crt2(gnutls_x509_trust_list_t list,
 	for (i = 0; i < cert_list_size &&
 		     cert_list_size <= DEFAULT_MAX_VERIFY_DEPTH; ) {
 		unsigned int sorted_size = 1;
-		unsigned int j;
+		unsigned int j, k;
 		gnutls_x509_crt_t issuer;
 
 		if (!(flags & GNUTLS_VERIFY_DO_NOT_ALLOW_UNSORTED_CHAIN)) {
@@ -1429,6 +1429,8 @@ gnutls_x509_trust_list_verify_crt2(gnutls_x509_trust_list_t list,
 							 cert_list_size - i);
 		}
 
+		assert(sorted_size > 0);
+
 		/* Remove duplicates. Start with index 1, as the first element
 		 * may be re-checked after issuer retrieval. */
 		for (j = 0; j < sorted_size; j++) {
@@ -1448,13 +1450,20 @@ gnutls_x509_trust_list_verify_crt2(gnutls_x509_trust_list_t list,
 		}
 
 		/* Record the certificates seen. */
-		for (j = 0; j < sorted_size; j++, i++) {
+		for (k = 0; k < sorted_size; k++, i++) {
 			if (!gl_list_nx_add_last(records, cert_list[i])) {
 				ret = gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
 				goto cleanup;
 			}
 		}
 
+		/* Pacify GCC analyzer: the condition always holds
+		 * true as sorted_size > 0 is checked above, and the
+		 * following loop should iterate at least once so i++
+		 * is called.
+		 */
+		assert(i > 0);
+
 		/* If the issuer of the certificate is known, no need
 		 * for further processing. */
 		if (gnutls_x509_trust_list_get_issuer(list,
-- 
2.33.0

