From 383d5465ef649594f7c4fbce557655240164b779 Mon Sep 17 00:00:00 2001
From: Eric Covener <covener@apache.org>
Date: Mon, 1 Dec 2025 12:06:00 +0000
Subject: [PATCH] Merge r1930163 from trunk:

envvars from HTTP headers low precedence



git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x@1930167 13f79535-47bb-0310-9956-ffa450edef68
---
 server/util_script.c | 26 +++++++++++++++++++++++---
 1 file changed, 23 insertions(+), 3 deletions(-)

Index: apache2-2.4.29/server/util_script.c
===================================================================
--- apache2-2.4.29.orig/server/util_script.c	2026-05-20 18:25:55.172997044 +0100
+++ apache2-2.4.29/server/util_script.c	2026-05-20 18:25:55.165997029 +0100
@@ -114,6 +114,8 @@
         }
     }
     for (i = 0; i < env_arr->nelts; ++i) {
+        int changed = 0;
+
         if (!elts[i].key) {
             continue;
         }
@@ -121,18 +123,36 @@
         whack = env[j];
         if (apr_isdigit(*whack)) {
             *whack++ = '_';
+            changed = 1;
         }
         while (*whack != '=') {
 #ifdef WIN32
-            if (!apr_isalnum(*whack) && *whack != '(' && *whack != ')') {
+            if (!apr_isalnum(*whack) && *whack != '_' && *whack != '(' && *whack != ')') {
 #else
-            if (!apr_isalnum(*whack)) {
+            if (!apr_isalnum(*whack) && *whack != '_') {
 #endif
                 *whack = '_';
+                changed = 1;
             }
             ++whack;
         }
-        ++j;
+        if (changed) {
+            *whack = '\0';
+            /*
+             * If after cleaning up the key the key is identical to an existing key
+             * in the table drop this environment variable. This also prevents
+             * to override CGI reserved environment variables with variables whose
+             * names have an invalid character instead of '_', but are otherwise
+             * equal to the names CGI reserved environment variables.
+             */
+            if (!apr_table_get(t, env[j])) {
+                ++j;
+                *whack = '=';
+            }
+        }
+        else {
+            ++j;
+        }
     }
 
     env[j] = NULL;
