This is an automated email from the ASF dual-hosted git repository.
markt-asf pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tomcat.git
The following commit(s) were added to refs/heads/main by this push:
new da607436f4 Do not break HTTP/2 streams with invalid response header
fields (#1154)
da607436f4 is described below
commit da607436f4293d2a0b6eec6dd5a2302adcf0ad7a
Author: Arturo Bernal <[email protected]>
AuthorDate: Tue Nov 17 17:04:53 2026 +0100
Do not break HTTP/2 streams with invalid response header fields (#1154)
An application can set a response header field that cannot be sent in a
valid HTTP/2 message. A value with a character that is not in the range
0 to 255 made the HPACK encoder throw part way through the header block,
so the client received no HEADERS frame, an empty DATA frame and a
RST_STREAM with INTERNAL_ERROR, and some clients dropped the whole
connection. A shorter value was truncated to one byte per character, and
NUL, CR and LF or leading and trailing whitespace were sent unchanged,
which RFC 9113, section 8.2.1 does not permit.
Handle these as HTTP/1.1 does. Remove a header field with a name that is
not a token or a value that contains a character above 255 and log a
warning, replace control characters in a value with a space and remove
leading and trailing whitespace. The check is in doWriteHeaders() so it
also covers trailer fields and early hints.
---
.../apache/coyote/http2/Http2UpgradeHandler.java | 80 +++++++++++++++
.../apache/coyote/http2/LocalStrings.properties | 1 +
.../coyote/http2/TestHttp2Section_8_2_1.java | 114 +++++++++++++++++++++
3 files changed, 195 insertions(+)
diff --git a/java/org/apache/coyote/http2/Http2UpgradeHandler.java
b/java/org/apache/coyote/http2/Http2UpgradeHandler.java
index b26a2525bc..fd1491d03c 100644
--- a/java/org/apache/coyote/http2/Http2UpgradeHandler.java
+++ b/java/org/apache/coyote/http2/Http2UpgradeHandler.java
@@ -49,6 +49,7 @@ import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.http.MimeHeaders;
+import org.apache.tomcat.util.http.parser.HttpParser;
import org.apache.tomcat.util.http.parser.Priority;
import org.apache.tomcat.util.log.UserDataHelper;
import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState;
@@ -863,6 +864,8 @@ class Http2UpgradeHandler extends AbstractStream implements
InternalHttpUpgradeH
return null;
}
+ removeInvalidHeaders(stream, mimeHeaders);
+
HeaderFrameBuffers headerFrameBuffers =
getHeaderFrameBuffers(payloadSize);
boolean first = true;
@@ -918,6 +921,83 @@ class Http2UpgradeHandler extends AbstractStream
implements InternalHttpUpgradeH
return headerFrameBuffers;
}
+
+ /**
+ * Removes the header fields that cannot be sent in a valid HTTP/2
message, as HTTP/1.1 does. A header field with a
+ * name that is not a token, or with a value that contains a character
that is not in the range 0 to 255, would
+ * otherwise make the encoder fail after it had updated its dynamic table.
Control characters in a value are
+ * replaced with a space and leading and trailing whitespace is removed
(RFC 9113, section 8.2.1).
+ *
+ * @param stream the stream the headers are written to
+ * @param headers the headers to check. Invalid header fields are removed
and invalid values are corrected.
+ */
+ private void removeInvalidHeaders(Stream stream, MimeHeaders headers) {
+ for (int i = 0; i < headers.size(); i++) {
+ String name = headers.getName(i).toString();
+ if (name.startsWith(":")) {
+ // Pseudo header fields are always generated by Tomcat
+ continue;
+ }
+ String value = headers.getValue(i).toString();
+ String validValue = HttpParser.isToken(name) ?
sanitizeHeaderValue(value) : null;
+ if (validValue == null) {
+ log.warn(sm.getString("upgradeHandler.response.invalidHeader",
connectionId, stream.getIdAsString(),
+ name, value));
+ headers.removeHeader(i--);
+ } else if (validValue != value) {
+ // sanitizeHeaderValue() returns the same instance if the
value was valid
+ headers.getValue(i).setString(validValue);
+ }
+ }
+ }
+
+
+ /**
+ * Corrects a header value so that it is valid in an HTTP/2 message.
+ *
+ * @param value the value to correct
+ *
+ * @return the corrected value or {@code null} if the value contains a
character that cannot be sent
+ */
+ static String sanitizeHeaderValue(String value) {
+ int length = value.length();
+ boolean valid = true;
+ if (length > 0 &&
+ (HttpParser.isWhiteSpace(value.charAt(0)) ||
HttpParser.isWhiteSpace(value.charAt(length - 1)))) {
+ valid = false;
+ }
+ for (int i = 0; i < length; i++) {
+ char c = value.charAt(i);
+ if (c > 255) {
+ return null;
+ }
+ // Control characters other than tab are not valid
+ if (!HttpParser.isFieldContent(c)) {
+ valid = false;
+ }
+ }
+ if (valid) {
+ return value;
+ }
+
+ char[] result = value.toCharArray();
+ int first = 0;
+ int last = length;
+ for (int i = 0; i < length; i++) {
+ if (!HttpParser.isFieldContent(result[i])) {
+ result[i] = ' ';
+ }
+ }
+ while (first < last && HttpParser.isWhiteSpace(result[first])) {
+ first++;
+ }
+ while (last > first && HttpParser.isWhiteSpace(result[last - 1])) {
+ last--;
+ }
+ return new String(result, first, last - first);
+ }
+
+
/**
* Creates header frame buffers for writing headers.
*
diff --git a/java/org/apache/coyote/http2/LocalStrings.properties
b/java/org/apache/coyote/http2/LocalStrings.properties
index c7deec4db5..84f9c6ccee 100644
--- a/java/org/apache/coyote/http2/LocalStrings.properties
+++ b/java/org/apache/coyote/http2/LocalStrings.properties
@@ -165,6 +165,7 @@ upgradeHandler.releaseBacklog=Connection [{0}], Stream
[{1}] released from backl
upgradeHandler.replace.duplicate=Connection [{0}], Stream [{1}] duplicate
attempt to replace stream with lightweight implementation has been ignored
upgradeHandler.replace.first=Connection [{0}], Stream [{1}] replaced with
lightweight stream implementation
upgradeHandler.reset.receive=Connection [{0}], Stream [{1}], Reset received
due to [{2}]
+upgradeHandler.response.invalidHeader=Connection [{0}], Stream [{1}], The HTTP
response header [{2}] with value [{3}] has been removed from the response
because it is invalid
upgradeHandler.rst.debug=Connection [{0}], Stream [{1}], Error [{2}], Message
[{3}], RST (closing stream)
upgradeHandler.sendPrefaceFail=Connection [{0}], Failed to send preface to
client
upgradeHandler.sendfile.reservation=Connection [{0}], Stream [{1}], Connection
reservation [{2}], Stream reservation [{3}] prior to sendfile write
diff --git a/test/org/apache/coyote/http2/TestHttp2Section_8_2_1.java
b/test/org/apache/coyote/http2/TestHttp2Section_8_2_1.java
new file mode 100644
index 0000000000..1f070e1354
--- /dev/null
+++ b/test/org/apache/coyote/http2/TestHttp2Section_8_2_1.java
@@ -0,0 +1,114 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.coyote.http2;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServlet;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.catalina.Context;
+import org.apache.catalina.startup.Tomcat;
+
+/**
+ * Unit tests for Section 8.2.1 of <a
href="https://tools.ietf.org/html/rfc9113">RFC 9113</a>. <br>
+ * The order of the tests in this class is determined by the order of the
requirements in the RFC.
+ */
+public class TestHttp2Section_8_2_1 extends Http2TestBase {
+
+ /*
+ * A response header field that cannot be sent in a valid HTTP/2 message
must not break the stream, the connection
+ * or the HPACK state shared by later responses. As for HTTP/1.1, a value
with a character that is not in the range
+ * 0 to 255 removes the header field and other invalid values are
corrected.
+ */
+ @Test
+ public void testInvalidResponseHeaders() throws Exception {
+ enableHttp2();
+
+ Tomcat tomcat = getTomcatInstance();
+
+ Context ctxt = getProgrammaticRootContext();
+ Tomcat.addServlet(ctxt, "simple", new SimpleServlet());
+ ctxt.addServletMapping("/simple", "simple");
+ Tomcat.addServlet(ctxt, "invalid", new InvalidHeadersServlet());
+ ctxt.addServletMapping("/invalid", "invalid");
+
+ tomcat.start();
+
+ openClientConnection();
+ doHttpUpgrade();
+ sendClientPreface();
+ validateHttp2InitialResponse();
+
+ // The second request checks that the HPACK dynamic table is still
consistent
+ for (int streamId = 3; streamId < 7; streamId += 2) {
+ byte[] frameHeader = new byte[9];
+ ByteBuffer headersPayload = ByteBuffer.allocate(128);
+ buildGetRequest(frameHeader, headersPayload, null, streamId,
"/invalid");
+ writeFrame(frameHeader, headersPayload);
+
+ // Headers
+ parser.readFrame();
+ // Body
+ parser.readFrame();
+
+ String id = Integer.toString(streamId);
+ String trace = output.getTrace();
+ Assert.assertTrue(trace, trace.contains(id +
"-Header-[x-latin1]-[caf\u00e9]\n"));
+ Assert.assertTrue(trace, trace.contains(id + "-Header-[x-lf]-[a
b]\n"));
+ Assert.assertTrue(trace, trace.contains(id + "-Header-[x-cr]-[a
b]\n"));
+ Assert.assertTrue(trace, trace.contains(id + "-Header-[x-nul]-[a
b]\n"));
+ Assert.assertTrue(trace, trace.contains(id +
"-Header-[x-space]-[padded]\n"));
+ Assert.assertTrue(trace, trace.contains(id +
"-Header-[x-last]-[ok]\n"));
+ Assert.assertFalse(trace, trace.contains("x-long-unicode"));
+ Assert.assertFalse(trace, trace.contains("x-short-unicode"));
+ Assert.assertFalse(trace, trace.contains("x-bad"));
+ Assert.assertTrue(trace, trace.contains(id + "-Body-2\n"));
+ Assert.assertTrue(trace, trace.contains(id + "-EndOfStream\n"));
+ output.clearTrace();
+ }
+ }
+
+
+ private static class InvalidHeadersServlet extends HttpServlet {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
+ // The default ISO-8859-1 response encoding cannot represent the
euro sign
+ resp.setContentType("text/plain");
+ // Longer than five characters so the value is Huffman encoded
+ resp.setHeader("X-Long-Unicode", "abcdefg\u20ac");
+ resp.setHeader("X-Short-Unicode", "\u20acx");
+ resp.setHeader("X Bad", "value");
+ resp.setHeader("X-Latin1", "caf\u00e9");
+ resp.setHeader("X-Lf", "a\nb");
+ resp.setHeader("X-Cr", "a\rb");
+ resp.setHeader("X-Nul", "a\u0000b");
+ resp.setHeader("X-Space", " \tpadded \t");
+ resp.setHeader("X-Last", "ok");
+ resp.getWriter().print("OK");
+ }
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]