This is an automated email from the ASF dual-hosted git repository.
pjfanning pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/poi.git
The following commit(s) were added to refs/heads/trunk by this push:
new 064406bd5a TimeStampSimpleHttpClient: drop credentials on cross-origin
redirect (#1456)
064406bd5a is described below
commit 064406bd5a2ac5b7e38f060882ffe4b48cc16615
Author: Nayyar <[email protected]>
AuthorDate: Fri Oct 23 02:09:08 2026 +0530
TimeStampSimpleHttpClient: drop credentials on cross-origin redirect (#1456)
handleRedirect copied every configured header, including the Basic
Authorization header built from tspUser/tspPass, onto the connection
for the redirect target. HttpURLConnection follows same-protocol
redirects itself and drops Authorization there, so the redirects that
reach this code are the scheme-changing ones: https to http sent the
credentials in cleartext, and the Location could name any host.
Only resend Authorization to the same host on the same scheme and
port, or on an http to https upgrade with default ports.
---
.../dsig/services/TimeStampSimpleHttpClient.java | 39 ++++++-
.../services/TestTimeStampSimpleHttpClient.java | 120 +++++++++++++++++++++
2 files changed, 157 insertions(+), 2 deletions(-)
diff --git
a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/TimeStampSimpleHttpClient.java
b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/TimeStampSimpleHttpClient.java
index 6c3965e3c1..ad7947bba2 100644
---
a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/TimeStampSimpleHttpClient.java
+++
b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/TimeStampSimpleHttpClient.java
@@ -32,6 +32,7 @@ import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.HashMap;
+import java.util.Locale;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
@@ -207,6 +208,10 @@ public class TimeStampSimpleHttpClient implements
TimeStampHttpClient {
}
protected TimeStampHttpClientResponse handleRedirect(String url,
MethodHandler handler, boolean followRedirect) throws IOException {
+ return handleRedirect(url, handler, followRedirect, true);
+ }
+
+ private TimeStampHttpClientResponse handleRedirect(String url,
MethodHandler handler, boolean followRedirect, boolean sendAuth) throws
IOException {
final HttpURLConnection huc;
try {
huc = (HttpURLConnection)new
URI(url).toURL().openConnection(proxy);
@@ -219,7 +224,11 @@ public class TimeStampSimpleHttpClient implements
TimeStampHttpClient {
huc.setConnectTimeout(20000);
huc.setReadTimeout(20000);
- header.forEach(huc::setRequestProperty);
+ header.forEach((name, value) -> {
+ if (sendAuth || !BASIC_AUTH.equals(name)) {
+ huc.setRequestProperty(name, value);
+ }
+ });
try {
handler.handle(huc);
@@ -236,7 +245,8 @@ public class TimeStampSimpleHttpClient implements
TimeStampHttpClient {
String newUrl = huc.getHeaderField(REDIRECT_LOCATION);
if (newUrl != null && followRedirect) {
LOG.atWarn().log("Received redirect: {} -> {}", url,
newUrl);
- return handleRedirect(newUrl, handler, false);
+ // don't send the TSP credentials to another origin or
downgrade them to http
+ return handleRedirect(newUrl, handler, false, sendAuth
&& isAuthForwardable(url, newUrl));
}
LOG.atWarn().log("Redirect ignored - giving up: {} -> {}",
url, newUrl);
@@ -266,6 +276,31 @@ public class TimeStampSimpleHttpClient implements
TimeStampHttpClient {
}
}
+ /**
+ * Credentials are only resent to the same host, either on the same scheme
and port or
+ * on an http to https upgrade with default ports.
+ */
+ private static boolean isAuthForwardable(String fromUrl, String toUrl) {
+ final URI from, to;
+ try {
+ from = new URI(fromUrl);
+ to = new URI(toUrl);
+ } catch (URISyntaxException e) {
+ return false;
+ }
+ if (from.getHost() == null ||
!from.getHost().equalsIgnoreCase(to.getHost())) {
+ return false;
+ }
+ final String fromScheme =
String.valueOf(from.getScheme()).toLowerCase(Locale.ROOT);
+ final String toScheme =
String.valueOf(to.getScheme()).toLowerCase(Locale.ROOT);
+ if (fromScheme.equals(toScheme)) {
+ return from.getPort() == to.getPort();
+ }
+ return "http".equals(fromScheme) && "https".equals(toScheme)
+ && (from.getPort() == -1 || from.getPort() == 80)
+ && (to.getPort() == -1 || to.getPort() == 443);
+ }
+
protected void recklessConnection(HttpURLConnection conn) throws
IOException {
if (!(conn instanceof HttpsURLConnection conns)) {
return;
diff --git
a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/services/TestTimeStampSimpleHttpClient.java
b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/services/TestTimeStampSimpleHttpClient.java
new file mode 100644
index 0000000000..ed3f5bc0ed
--- /dev/null
+++
b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/services/TestTimeStampSimpleHttpClient.java
@@ -0,0 +1,120 @@
+/* ====================================================================
+ 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.poi.poifs.crypt.dsig.services;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyStore;
+import java.security.cert.Certificate;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+
+import org.apache.poi.poifs.crypt.dsig.DummyKeystore;
+import org.apache.poi.poifs.crypt.dsig.DummyKeystore.KeyCertPair;
+import org.apache.poi.poifs.crypt.dsig.SignatureConfig;
+import org.junit.jupiter.api.Test;
+
+class TestTimeStampSimpleHttpClient {
+ private static final String STORE_PASS = "test";
+ private static final String LOCALHOST = "127.0.0.1";
+
+ @Test
+ void basicAuthNotForwardedOnHttpsToHttpRedirect() throws Exception {
+ KeyCertPair pair = new DummyKeystore(STORE_PASS).createDummyKey();
+ KeyStore ks = KeyStore.getInstance("PKCS12");
+ ks.load(null, null);
+ ks.setKeyEntry("tsp", pair.getKey(), STORE_PASS.toCharArray(),
pair.getX509Chain().toArray(new Certificate[0]));
+ KeyManagerFactory kmf =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+ kmf.init(ks, STORE_PASS.toCharArray());
+ SSLContext ctx = SSLContext.getInstance("TLS");
+ ctx.init(kmf.getKeyManagers(), null, null);
+
+ InetAddress lo = InetAddress.getByName(LOCALHOST);
+ try (ServerSocket tsp =
ctx.getServerSocketFactory().createServerSocket(0, 1, lo);
+ ServerSocket other = new ServerSocket(0, 1, lo)) {
+ String otherUrl = "http://" + LOCALHOST + ":" +
other.getLocalPort() + "/";
+ CompletableFuture<List<String>> tspReq = serve(tsp,
+ "HTTP/1.1 302 Found\r\nLocation: " + otherUrl +
"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
+ CompletableFuture<List<String>> otherReq = serve(other,
+ "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection:
close\r\n\r\nok");
+
+ SignatureConfig config = new SignatureConfig();
+ config.setTspUser("user");
+ config.setTspPass("secret");
+ TimeStampSimpleHttpClient client = new TimeStampSimpleHttpClient();
+ client.init(config);
+ client.setIgnoreHttpsCertificates(true);
+ client.setFollowRedirects(true);
+
+ String tspUrl = "https://" + LOCALHOST + ":" + tsp.getLocalPort()
+ "/";
+ TimeStampHttpClient.TimeStampHttpClientResponse resp =
client.post(tspUrl, new byte[]{1, 2, 3});
+ assertEquals(200, resp.getResponseCode());
+ assertArrayEquals("ok".getBytes(StandardCharsets.US_ASCII),
resp.getResponseBytes());
+
+ assertTrue(hasAuthorization(tspReq.get(10, TimeUnit.SECONDS)));
+ assertFalse(hasAuthorization(otherReq.get(10, TimeUnit.SECONDS)),
+ "Basic credentials were sent to the redirect target over plain
http");
+ }
+ }
+
+ private static boolean hasAuthorization(List<String> headers) {
+ return headers.stream().anyMatch(h ->
h.toLowerCase(Locale.ROOT).startsWith("authorization:"));
+ }
+
+ private static CompletableFuture<List<String>> serve(ServerSocket server,
String response) {
+ return CompletableFuture.supplyAsync(() -> {
+ try (Socket s = server.accept()) {
+ BufferedReader r = new BufferedReader(new
InputStreamReader(s.getInputStream(), StandardCharsets.ISO_8859_1));
+ List<String> headers = new ArrayList<>();
+ int contentLength = 0;
+ for (String line; (line = r.readLine()) != null &&
!line.isEmpty(); ) {
+ headers.add(line);
+ if
(line.toLowerCase(Locale.ROOT).startsWith("content-length:")) {
+ contentLength =
Integer.parseInt(line.substring(15).trim());
+ }
+ }
+ for (int i = 0; i < contentLength; i++) {
+ r.read();
+ }
+ OutputStream os = s.getOutputStream();
+ os.write(response.getBytes(StandardCharsets.ISO_8859_1));
+ os.flush();
+ return headers;
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
+ }
+ });
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]