michael-o commented on code in PR #718:
URL: 
https://github.com/apache/httpcomponents-client/pull/718#discussion_r2330732592


##########
httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/ScramScheme.java:
##########
@@ -0,0 +1,681 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation.  For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.client5.http.impl.auth;
+
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.security.MessageDigest;
+import java.security.Principal;
+import java.security.SecureRandom;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import javax.crypto.Mac;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.PBEKeySpec;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.apache.hc.client5.http.auth.AuthChallenge;
+import org.apache.hc.client5.http.auth.AuthScheme;
+import org.apache.hc.client5.http.auth.AuthScope;
+import org.apache.hc.client5.http.auth.AuthenticationException;
+import org.apache.hc.client5.http.auth.Credentials;
+import org.apache.hc.client5.http.auth.CredentialsProvider;
+import org.apache.hc.client5.http.auth.MalformedChallengeException;
+import org.apache.hc.client5.http.auth.StandardAuthScheme;
+import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
+import org.apache.hc.client5.http.protocol.HttpClientContext;
+import org.apache.hc.core5.annotation.Contract;
+import org.apache.hc.core5.annotation.ThreadingBehavior;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.NameValuePair;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.util.Args;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Strict HTTP SCRAM client implementing {@code SCRAM-SHA-256} per 
RFC&nbsp;7804
+ * with SCRAM core per RFC&nbsp;5802/7677.
+ * <p>HTTP SCRAM uses <em>no channel binding</em> (GS2 header {@code "n,,"}; 
{@code c=biws}).</p>
+ *
+ * @since 5.6
+ */
+@Contract(threading = ThreadingBehavior.UNSAFE)
+public final class ScramScheme implements AuthScheme {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(ScramScheme.class);
+
+    // RFC 7804 / RFC 5802 fixed no-CB GS2 header and its base64 value for 'c='
+    private static final String GS2_HEADER = "n,,";
+    private static final String C_BIND_B64 = "biws"; // base64("n,,")
+
+    private static final Base64.Encoder B64 = 
Base64.getEncoder().withoutPadding();
+    private static final Base64.Decoder B64D = Base64.getDecoder();
+
+    private enum State {
+        INIT,
+        ANNOUNCED,            // after 401 challenge without data
+        CLIENT_FIRST_SENT,    // after Authorization with client-first
+        SERVER_FIRST_RCVD,    // after 401 with data (r,s,i)
+        CLIENT_FINAL_SENT,    // after Authorization with client-final (p=...)
+        COMPLETE,             // after 2xx with matching v
+        FAILED
+    }
+
+    private final SecureRandom secureRandom;
+    private final int warnMinIterations;
+    private final int minIterationsRequired;
+
+    private State state = State.INIT;
+    private boolean complete;
+
+    private String realm;
+    private String sid;
+
+    private String username;     // SASLprep (query)
+    private char[] password;     // SASLprep (stored), zeroed after use
+    private Principal principal;
+
+    private String clientNonce;
+    private String clientFirstBare;
+    private String serverFirstRaw;
+    private String serverNonce;
+    private byte[] salt;
+    private int iterations;
+
+    // Expected server signature (raw bytes) for constant-time check on 
Authentication-Info
+    // (may appear on any final response status code)
+    private byte[] expectedV;
+
+    /**
+     * Default policy: warn if {@code i < 4096}, no hard enforcement; SHA-256 
only.
+     *
+     * @since 5.6
+     */
+    public ScramScheme() {
+        this(4096, 0, null);
+    }
+
+    /**
+     * Constructor with custom iteration policy.
+     *
+     * @param warnMinIterations     warn if iteration count is lower than this 
(0 disables warnings)
+     * @param minIterationsRequired fail if iteration count is lower than this 
(0 disables enforcement)
+     * @param rnd                   optional secure random source (null uses 
system default)
+     * @since 5.6
+     */
+    public ScramScheme(final int warnMinIterations, final int 
minIterationsRequired, final SecureRandom rnd) {
+        this.warnMinIterations = Math.max(0, warnMinIterations);
+        this.minIterationsRequired = Math.max(0, minIterationsRequired);
+        this.secureRandom = rnd != null ? rnd : new SecureRandom();
+    }
+
+    /**
+     * Returns textual designation of the scheme.
+     *
+     * @since 5.6
+     */
+    @Override
+    public String getName() {
+        return StandardAuthScheme.SCRAM_SHA_256;
+    }
+
+    /**
+     * SCRAM is per-request (no connection binding).
+     *
+     * @since 5.6
+     */
+    @Override
+    public boolean isConnectionBased() {
+        return false;
+    }
+
+    /**
+     * SCRAM must inspect final responses to verify {@code v=} in {@code 
Authentication-Info}.
+     *
+     * @since 5.6
+     */
+    @Override
+    public boolean isChallengeExpected() {
+        return true;
+    }
+
+    /**
+     * Legacy entry point: wraps {@link AuthenticationException} as {@link 
MalformedChallengeException}.
+     *
+     * @since 5.6
+     */
+    @Override
+    public void processChallenge(final AuthChallenge authChallenge, final 
HttpContext context)
+            throws MalformedChallengeException {
+        try {
+            processChallenge(null, true, authChallenge, context);
+        } catch (final AuthenticationException ex) {
+            throw new MalformedChallengeException(ex.getMessage(), ex);
+        }
+    }
+
+    /**
+     * Handles 401 challenges (with/without {@code data}) and final responses 
carrying
+     * {@code Authentication-Info} (any status code).
+     *
+     * @since 5.6
+     */
+    @Override
+    public void processChallenge(
+            final HttpHost host,
+            final boolean challenged,
+            final AuthChallenge authChallenge,
+            final HttpContext context) throws MalformedChallengeException, 
AuthenticationException {
+
+        Args.notNull(context, "HTTP context");
+
+        if (authChallenge == null) {
+            if (!challenged) {
+                // Final response with no Authentication-Info: nothing to do
+                return;
+            }
+            throw new MalformedChallengeException("Null SCRAM challenge");
+        }
+
+        final Map<String, String> params = 
toParamMap(authChallenge.getParams());
+
+        if (challenged) {
+            // --- 401 path (WWW-Authenticate) ---
+            final String scheme = authChallenge.getSchemeName();
+            if (scheme == null || 
!StandardAuthScheme.SCRAM_SHA_256.equalsIgnoreCase(scheme)) {
+                throw new MalformedChallengeException("Unexpected scheme: " + 
scheme);
+            }
+
+            final String data = params.get("data");
+            if (data == null) {
+                // initial announce (no data)
+                this.realm = params.get("realm");
+                this.state = State.ANNOUNCED;
+                this.complete = false;
+                zeroAndClearExpectedV();
+                return;
+            }
+
+            // server-first (data present)
+            final String decoded = b64ToString(data);
+            this.serverFirstRaw = decoded;
+            final Map<String, String> attrs = parseAttrs(decoded);
+
+            final String r = attrs.get("r");
+            final String s = attrs.get("s");
+            final String i = attrs.get("i");
+            if (r == null || r.isEmpty() || s == null || s.isEmpty() || i == 
null || i.isEmpty()) {
+                this.state = State.FAILED;
+                throw new MalformedChallengeException("SCRAM server-first 
missing r/s/i");
+            }
+            if (this.clientNonce == null || !r.startsWith(this.clientNonce)) {
+                this.state = State.FAILED;
+                throw new AuthenticationException("SCRAM server nonce does not 
start with client nonce");
+            }
+
+            this.sid = params.get("sid");
+            try {
+                this.salt = B64D.decode(s);

Review Comment:
   If this doesn't come from us shouldn't it be `MalformedChallengeException`?



-- 
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]

Reply via email to