chungen0126 commented on code in PR #11061:
URL: https://github.com/apache/ozone/pull/11061#discussion_r3839903334
##########
hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/EndpointBase.java:
##########
@@ -856,10 +901,14 @@ protected int getIOBufferSize(long fileLength) {
protected static final class S3ChunkInputStreamInfo {
private final MultiDigestInputStream multiDigestInputStream;
private final long effectiveLength;
+ /** The signed chunk stream, if the payload is a signed multi-chunk
upload. */
+ private final SignedChunksInputStream signedChunksInputStream;
Review Comment:
I think the purpose of this field is a bit unclear. If we only need to
indicate whether `S3ChunkInputStreamInfo` is a signed stream, adding a boolean
flag would suffice. Furthermore, if we need to get the
`signedChunksInputStream` instance, we could probably retrieve it from
`multiDigestInputStream` instead.
##########
hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/signature/ChunksValidator.java:
##########
@@ -0,0 +1,126 @@
+/*
+ * 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.s3.signature;
+
+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 javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import org.apache.hadoop.ozone.s3.exception.OS3Exception;
+import org.apache.kerby.util.Hex;
+
+/**
+ * Verifies the per-chunk signatures of a SigV4 chunked upload
+ * ({@code STREAMING-AWS4-HMAC-SHA256-PAYLOAD}).
+ * <p>
+ * Each chunk signature is {@code hex(HMAC-SHA256(signingKey, stringToSign))},
+ * where the string-to-sign is:
+ * <pre>
+ * AWS4-HMAC-SHA256-PAYLOAD\n
+ * <date-time>\n
+ * <credential-scope>\n
+ * <previous-signature>\n
+ * <SHA-256("")>\n
+ * <SHA-256(chunk-payload)>
+ * </pre>
+ * The signatures are chained: the first chunk uses the request (seed)
signature
+ * as the previous signature, and each subsequent chunk uses the previous
+ * chunk's computed signature. The signing key is the SigV4 signing key derived
+ * from the caller's secret; it is provided by the caller so that the S3
Gateway
+ * does not have to handle the secret directly (see HDDS-15140).
+ *
+ * @see <a
href="https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html">
+ * Signature Calculation: Transfer Payload in Multiple Chunks</a>
+ */
+public class ChunksValidator {
+
+ private static final String CHUNK_STRING_TO_SIGN_ALGORITHM =
+ "AWS4-HMAC-SHA256-PAYLOAD";
+ private static final String HMAC_SHA256 = "HmacSHA256";
+ private static final String SHA_256 = "SHA-256";
+ 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 final byte[] signingKey;
+ private final String dateTime;
+ private final String credentialScope;
+ private String previousSignature;
+
+ public ChunksValidator(byte[] signingKey, String dateTime,
+ String credentialScope, String seedSignature) {
+ this.signingKey = signingKey.clone();
+ this.dateTime = dateTime;
+ this.credentialScope = credentialScope;
+ this.previousSignature = seedSignature;
+ }
+
+ /**
+ * Verify one chunk and advance the signature chain.
+ *
+ * @param chunkSignature the signature parsed from the chunk header line
+ * @param payloadSha256Hex hex SHA-256 of the chunk payload
+ * @throws OS3Exception if the computed signature does not match
+ */
+ public void validateChunk(String chunkSignature, String payloadSha256Hex)
+ throws OS3Exception {
+ String stringToSign = String.join(NEWLINE,
+ CHUNK_STRING_TO_SIGN_ALGORITHM, dateTime, credentialScope,
+ previousSignature, EMPTY_STRING_SHA256, payloadSha256Hex);
+ String expected = hex(hmacSha256(signingKey, stringToSign));
+ // Constant-time comparison to avoid leaking the signature via timing.
+ if (chunkSignature == null || !MessageDigest.isEqual(
+ expected.getBytes(StandardCharsets.UTF_8),
+ chunkSignature.getBytes(StandardCharsets.UTF_8))) {
+ throw newError(SIGNATURE_DOES_NOT_MATCH, "chunk-signature");
+ }
+ previousSignature = expected;
+ }
+
+ /** @return hex SHA-256 of {@code data[off, off+len)}. */
+ public static String sha256Hex(byte[] data, int off, int len) {
+ try {
+ MessageDigest md = MessageDigest.getInstance(SHA_256);
+ md.update(data, off, len);
+ return hex(md.digest());
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException(SHA_256 + " not available", e);
+ }
+ }
+
+ private static byte[] hmacSha256(byte[] key, String msg) {
+ try {
+ Mac mac = Mac.getInstance(HMAC_SHA256);
Review Comment:
Calling `Mac.getInstance()` every time here can incur some performance
overhead. A better approach would be to cache it using a `ThreadLocal` instance
to improve performance.
##########
hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/SignedChunksInputStream.java:
##########
@@ -72,10 +77,22 @@
public class SignedChunksInputStream extends InputStream {
private final Pattern signatureLinePattern =
- Pattern.compile("([0-9A-Fa-f]+);chunk-signature=.*");
+ Pattern.compile("([0-9A-Fa-f]+);chunk-signature=(.*)");
private final InputStream originalStream;
+ /** Verifies each chunk signature, or {@code null} to skip verification. */
+ private ChunksValidator validator;
+
+ /** SHA-256 of the current chunk payload; {@code null} when not verifying. */
+ private MessageDigest chunkDigest;
+
+ /** Set on the first read; blocks attaching a validator once reading began.
*/
+ private boolean readStarted;
Review Comment:
Could you clarify under what scenario the validator would be attached after
the reading has already started?
##########
hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/TestSignedChunksInputStream.java:
##########
@@ -229,6 +250,97 @@ void testMultiChunksWithTrailer() throws Exception {
}
}
+ @Test
+ void verifiesRealChunkSignatures() throws IOException {
+ String content = signedChunkedBody('a');
+ try (InputStream is = new SignedChunksInputStream(
+ new ByteArrayInputStream(content.getBytes(UTF_8)), newValidator())) {
+ assertEquals(repeat('a', 66560), IOUtils.toString(is, UTF_8));
+ }
+ }
+
+ @Test
+ void rejectsTamperedChunkPayload() {
+ // Same signatures, but the first chunk carries different bytes.
+ String content = signedChunkedBody('b');
+ InputStream is = new SignedChunksInputStream(
+ new ByteArrayInputStream(content.getBytes(UTF_8)), newValidator());
+ assertThrows(OS3Exception.class, () -> IOUtils.toString(is, UTF_8));
+ }
+
+ @Test
+ void attachValidatorEnablesVerification() throws IOException {
+ // The signing key is only known after the key is opened, so the validator
+ // is attached to an already-constructed stream (HDDS-15140/15141).
+ String content = signedChunkedBody('a');
+ try (SignedChunksInputStream is = new SignedChunksInputStream(
+ new ByteArrayInputStream(content.getBytes(UTF_8)))) {
+ is.attachValidator(newValidator());
+ assertEquals(repeat('a', 66560), IOUtils.toString(is, UTF_8));
+ }
+ }
+
+ @Test
+ void attachedValidatorRejectsTamperedChunkPayload() {
+ String content = signedChunkedBody('b');
+ SignedChunksInputStream is = new SignedChunksInputStream(
+ new ByteArrayInputStream(content.getBytes(UTF_8)));
+ is.attachValidator(newValidator());
+ assertThrows(OS3Exception.class, () -> IOUtils.toString(is, UTF_8));
+ }
+
+ @Test
+ void attachValidatorAfterReadStartedFails() throws IOException {
+ SignedChunksInputStream is = new SignedChunksInputStream(
+ new ByteArrayInputStream(signedChunkedBody('a').getBytes(UTF_8)));
+ is.read();
+ assertThrows(IllegalStateException.class, () ->
is.attachValidator(newValidator()));
+ }
+
+ @Test
+ void attachValidatorTwiceFails() {
+ SignedChunksInputStream is = new SignedChunksInputStream(
+ new ByteArrayInputStream(signedChunkedBody('a').getBytes(UTF_8)));
+ is.attachValidator(newValidator());
+ assertThrows(IllegalStateException.class, () ->
is.attachValidator(newValidator()));
+ }
+
+ private static String signedChunkedBody(char payloadChar) {
+ return "10000;chunk-signature=" + CHUNK1_SIGNATURE + "\r\n"
+ + repeat(payloadChar, 65536) + "\r\n"
+ + "400;chunk-signature=" + CHUNK2_SIGNATURE + "\r\n"
+ + repeat(payloadChar, 1024) + "\r\n"
+ + "0;chunk-signature=" + FINAL_CHUNK_SIGNATURE + "\r\n";
+ }
+
+ private static ChunksValidator newValidator() {
+ return new ChunksValidator(signingKey("20130524", "us-east-1", "s3"),
+ DATE_TIME, SCOPE, SEED_SIGNATURE);
+ }
+
+ private static String repeat(char c, int count) {
+ char[] chars = new char[count];
+ Arrays.fill(chars, c);
+ return new String(chars);
+ }
+
+ private static byte[] signingKey(String date, String region, String service)
{
+ byte[] key = hmac(("AWS4" + SECRET_KEY).getBytes(UTF_8), date);
+ key = hmac(key, region);
+ key = hmac(key, service);
+ return hmac(key, "aws4_request");
+ }
+
+ private static byte[] hmac(byte[] key, String msg) {
+ try {
+ Mac mac = Mac.getInstance("HmacSHA256");
+ mac.init(new SecretKeySpec(key, "HmacSHA256"));
+ return mac.doFinal(msg.getBytes(UTF_8));
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
+ }
+ }
Review Comment:
It looks like this is actually calculating the HMAC here, but I don't think
this logic belongs in this specific test class. Could we extract these signing
helpers into a shared test utility class (or perhaps mock them) to keep this
class focused solely on testing the stream's behavior?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]