This is an automated email from the ASF dual-hosted git repository.
chungen0126 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozone.git
The following commit(s) were added to refs/heads/master by this push:
new b55385a2794 HDDS-16662. Share HMAC-SHA256 logic between S3 signature
validators (#11588)
b55385a2794 is described below
commit b55385a2794f52d3cd8875824210af2118468953
Author: KUAN-HAO HUANG <[email protected]>
AuthorDate: Mon Oct 19 10:43:05 2026 +0100
HDDS-16662. Share HMAC-SHA256 logic between S3 signature validators (#11588)
---
.../apache/hadoop/ozone/om/AWSV4AuthValidator.java | 33 ++-----
.../apache/hadoop/ozone/security/HmacSha256.java | 45 +++++++++
.../hadoop/ozone/security/TestHmacSha256.java | 101 +++++++++++++++++++++
.../hadoop/ozone/s3/signature/ChunksValidator.java | 22 ++---
.../ozone/s3/signature/TestChunksValidator.java | 24 +++++
5 files changed, 184 insertions(+), 41 deletions(-)
diff --git
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/AWSV4AuthValidator.java
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/AWSV4AuthValidator.java
index 6a2d5628107..4aa352cb2e9 100644
---
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/AWSV4AuthValidator.java
+++
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/AWSV4AuthValidator.java
@@ -18,11 +18,11 @@
package org.apache.hadoop.ozone.om;
import java.nio.charset.StandardCharsets;
-import java.security.GeneralSecurityException;
+import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
-import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
+import org.apache.hadoop.ozone.security.HmacSha256;
import org.apache.hadoop.util.StringUtils;
import org.apache.kerby.util.Hex;
import org.slf4j.Logger;
@@ -37,21 +37,6 @@ public final class AWSV4AuthValidator {
private static final Logger LOG =
LoggerFactory.getLogger(AWSV4AuthValidator.class);
- private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256";
-
- /**
- * ThreadLocal cache of Mac instances.
- */
- private static final ThreadLocal<Mac> THREAD_LOCAL_MAC =
- ThreadLocal.withInitial(() -> {
- try {
- return Mac.getInstance(HMAC_SHA256_ALGORITHM);
- } catch (NoSuchAlgorithmException nsa) {
- throw new IllegalArgumentException(
- "Failed to initialize Mac instance that implements the " +
- HMAC_SHA256_ALGORITHM + " algorithm.", nsa);
- }
- });
private AWSV4AuthValidator() {
}
@@ -64,14 +49,12 @@ public static String hash(String payload) throws
NoSuchAlgorithmException {
private static byte[] sign(byte[] key, String msg) {
try {
- SecretKeySpec signingKey = new SecretKeySpec(key, HMAC_SHA256_ALGORITHM);
- // Returns the cached Mac instance for the current thread or creates a
- // new one if none exists.
- Mac mac = THREAD_LOCAL_MAC.get();
- mac.init(signingKey);
- return mac.doFinal(msg.getBytes(StandardCharsets.UTF_8));
- } catch (GeneralSecurityException gse) {
- throw new RuntimeException(gse);
+ return HmacSha256.sign(new SecretKeySpec(key, HmacSha256.ALGORITHM),
msg);
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalArgumentException(
+ "Failed to initialize Mac instance that implements the " +
HmacSha256.ALGORITHM + " algorithm.", e);
+ } catch (InvalidKeyException e) {
+ throw new RuntimeException(e);
}
}
diff --git
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/security/HmacSha256.java
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/security/HmacSha256.java
new file mode 100644
index 00000000000..7afb77478ea
--- /dev/null
+++
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/security/HmacSha256.java
@@ -0,0 +1,45 @@
+/*
+ * 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.hadoop.ozone.security;
+
+import java.nio.charset.StandardCharsets;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+/** HMAC-SHA256 signing with a per-thread Mac instance. */
+public final class HmacSha256 {
+
+ public static final String ALGORITHM = "HmacSHA256";
+ private static final ThreadLocal<Mac> MAC = new ThreadLocal<>();
+
+ private HmacSha256() {
+ }
+
+ public static byte[] sign(SecretKeySpec key, String message) throws
NoSuchAlgorithmException, InvalidKeyException {
+ Mac mac = MAC.get();
+ if (mac == null) {
+ mac = Mac.getInstance(ALGORITHM);
+ MAC.set(mac);
+ }
+ // A thread can serve different requests and signing-key derivation steps.
+ mac.init(key);
+ return mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
+ }
+}
diff --git
a/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/security/TestHmacSha256.java
b/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/security/TestHmacSha256.java
new file mode 100644
index 00000000000..a9dfa4f30ff
--- /dev/null
+++
b/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/security/TestHmacSha256.java
@@ -0,0 +1,101 @@
+/*
+ * 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.hadoop.ozone.security;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.Arrays;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+import javax.crypto.spec.SecretKeySpec;
+import org.apache.kerby.util.Hex;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+/** Tests the shared HMAC primitive against independent expected signatures. */
+class TestHmacSha256 {
+
+ private static final String FIRST_SIGNATURE =
"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7";
+ private static final String SECOND_SIGNATURE =
"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843";
+
+ private static byte[] firstKey() {
+ byte[] key = new byte[20];
+ Arrays.fill(key, (byte) 0x0b);
+ return key;
+ }
+
+ static Stream<Arguments> signatures() {
+ // The first two cases are RFC 4231 test cases 1 and 2; the third checks
UTF-8 encoding.
+ return Stream.of(
+ Arguments.of(firstKey(), "Hi There", FIRST_SIGNATURE),
+ Arguments.of("Jefe".getBytes(UTF_8), "what do ya want for nothing?",
SECOND_SIGNATURE),
+ Arguments.of("key".getBytes(UTF_8), "你好 Ozone",
+
"2dc40af6acb137a9137b62f00ec73e96430db1b91003d1d5f7e99f967636ac6f"));
+ }
+
+ @ParameterizedTest
+ @MethodSource("signatures")
+ void matchesKnownSignatures(byte[] key, String message, String expected)
throws Exception {
+ assertEquals(expected, Hex.encode(HmacSha256.sign(new SecretKeySpec(key,
"HmacSHA256"), message)));
+ }
+
+ @Test
+ void reinitializesForDifferentKeys() throws Exception {
+ SecretKeySpec first = new SecretKeySpec(firstKey(), "HmacSHA256");
+ SecretKeySpec second = new SecretKeySpec("Jefe".getBytes(UTF_8),
"HmacSHA256");
+ assertEquals(FIRST_SIGNATURE, Hex.encode(HmacSha256.sign(first, "Hi
There")));
+ assertEquals(SECOND_SIGNATURE, Hex.encode(HmacSha256.sign(second, "what do
ya want for nothing?")));
+ assertEquals(FIRST_SIGNATURE, Hex.encode(HmacSha256.sign(first, "Hi
There")));
+ }
+
+ @Test
+ void independentThreadsUseDifferentKeys() throws Exception {
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ CyclicBarrier barrier = new CyclicBarrier(2);
+ try {
+ Future<?> first = executor.submit(() -> {
+ assertRepeatedSigning(firstKey(), "Hi There", FIRST_SIGNATURE,
barrier);
+ return null;
+ });
+ Future<?> second = executor.submit(() -> {
+ assertRepeatedSigning("Jefe".getBytes(UTF_8), "what do ya want for
nothing?", SECOND_SIGNATURE, barrier);
+ return null;
+ });
+ first.get(30, TimeUnit.SECONDS);
+ second.get(30, TimeUnit.SECONDS);
+ } finally {
+ executor.shutdownNow();
+ }
+ }
+
+ private static void assertRepeatedSigning(byte[] key, String message, String
expected, CyclicBarrier barrier)
+ throws Exception {
+ SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA256");
+ for (int i = 0; i < 100; i++) {
+ barrier.await(10, TimeUnit.SECONDS);
+ assertEquals(expected, Hex.encode(HmacSha256.sign(signingKey, message)));
+ }
+ }
+}
diff --git
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/signature/ChunksValidator.java
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/signature/ChunksValidator.java
index 9e80a911583..63ecdfd8fd7 100644
---
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/signature/ChunksValidator.java
+++
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/signature/ChunksValidator.java
@@ -20,15 +20,14 @@
import static
org.apache.hadoop.ozone.s3.exception.S3ErrorTable.SIGNATURE_DOES_NOT_MATCH;
import static org.apache.hadoop.ozone.s3.exception.S3ErrorTable.newError;
-import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
-import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import org.apache.hadoop.ozone.s3.exception.OS3Exception;
+import org.apache.hadoop.ozone.security.HmacSha256;
/**
* Verifies the per-chunk and trailing-header signatures of a SigV4 chunked
upload
@@ -59,21 +58,12 @@ public class ChunksValidator {
"AWS4-HMAC-SHA256-PAYLOAD";
private static final String TRAILER_STRING_TO_SIGN_ALGORITHM =
"AWS4-HMAC-SHA256-TRAILER";
- private static final String HMAC_SHA256 = "HmacSHA256";
private static final String NEWLINE = "\n";
/** SHA-256 hex of the empty string (the hashed empty headers slot). */
private static final String EMPTY_STRING_SHA256 =
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
- private static final ThreadLocal<Mac> HMAC = ThreadLocal.withInitial(() -> {
- try {
- return Mac.getInstance(HMAC_SHA256);
- } catch (NoSuchAlgorithmException e) {
- throw new IllegalStateException(HMAC_SHA256 + " not available", e);
- }
- });
-
/** The signing key is fixed for the request, so the key spec is built once
instead of per chunk. */
private final SecretKeySpec signingKey;
private final String dateTime;
@@ -83,7 +73,7 @@ public class ChunksValidator {
public ChunksValidator(byte[] signingKey, String dateTime,
String credentialScope, String seedSignature, String resource) {
- this.signingKey = new SecretKeySpec(signingKey, HMAC_SHA256);
+ this.signingKey = new SecretKeySpec(signingKey, HmacSha256.ALGORITHM);
this.dateTime = dateTime;
this.credentialScope = credentialScope;
this.previousSignature = seedSignature;
@@ -141,11 +131,11 @@ private void validateSignature(String signature, String
stringToSign) {
private byte[] hmacSha256(String msg) {
try {
- Mac mac = HMAC.get();
- mac.init(signingKey);
- return mac.doFinal(msg.getBytes(StandardCharsets.UTF_8));
+ return HmacSha256.sign(signingKey, msg);
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException(HmacSha256.ALGORITHM + " not available",
e);
} catch (InvalidKeyException e) {
- throw new IllegalStateException("Failed to compute " + HMAC_SHA256, e);
+ throw new IllegalStateException("Failed to compute " +
HmacSha256.ALGORITHM, e);
}
}
}
diff --git
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/signature/TestChunksValidator.java
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/signature/TestChunksValidator.java
index f902787fd51..498766481b3 100644
---
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/signature/TestChunksValidator.java
+++
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/signature/TestChunksValidator.java
@@ -21,10 +21,13 @@
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.Locale;
+import org.apache.hadoop.ozone.om.AWSV4AuthValidator;
import org.apache.hadoop.ozone.s3.exception.OS3Exception;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
@@ -186,6 +189,27 @@ void
interleavedValidatorsWithDifferentKeysDoNotCrossContaminate() {
assertDoesNotThrow(() -> correct.validateChunk(CHUNK2_SIGNATURE, sha1024));
}
+ @Test
+ void requestAndChunkSignaturesCanBeInterleaved() {
+ String stringToSign =
"AWS4-HMAC-SHA256\n20150830T123600Z\n20150830/us-east-1/iam/aws4_request\n"
+ + "f536975d06c0309214f805bb90ccff089219ecd68b2577efef23edd43b7e1a59";
+ String requestSignature =
"5d672d79c15b13162d9279b0855cfba6789a8edb4c82c400e06b5924a6f2b5d7";
+ String requestKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
+ ChunksValidator validator = newValidator();
+ byte[] chunk1 = repeat('a', 65536);
+ byte[] chunk2 = repeat('a', 1024);
+
+ assertDoesNotThrow(() -> validator.validateChunk(CHUNK1_SIGNATURE,
+ SignatureTestUtils.sha256Hex(chunk1, 0, chunk1.length)));
+ assertTrue(AWSV4AuthValidator.validateRequest(stringToSign,
requestSignature, requestKey));
+ assertDoesNotThrow(() -> validator.validateChunk(CHUNK2_SIGNATURE,
+ SignatureTestUtils.sha256Hex(chunk2, 0, chunk2.length)));
+ assertFalse(AWSV4AuthValidator.validateRequest(stringToSign,
requestSignature, "wrong-secret"));
+ assertDoesNotThrow(() -> validator.validateChunk(FINAL_CHUNK_SIGNATURE,
+ SignatureTestUtils.sha256Hex(new byte[0], 0, 0)));
+ assertTrue(AWSV4AuthValidator.validateRequest(stringToSign,
requestSignature, requestKey));
+ }
+
private static byte[] repeat(char c, int count) {
byte[] bytes = new byte[count];
Arrays.fill(bytes, (byte) c);
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]