michael-o commented on code in PR #718: URL: https://github.com/apache/httpcomponents-client/pull/718#discussion_r2328742047
########## httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/ScramScheme.java: ########## @@ -0,0 +1,685 @@ +/* + * ==================================================================== + * 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 7804 + * with SCRAM core per RFC 5802/7677. + * <p>HTTP SCRAM uses <em>no channel binding</em> (GS2 header {@code "n,,"}; {@code c=biws}).</p> + * + * @since 5.6 + */ + +/** + * Strict HTTP SCRAM client implementing {@code SCRAM-SHA-256} per RFC 7804 + * with SCRAM core per RFC 5802/7677. + * <p>HTTP SCRAM uses <em>no channel binding</em> (GS2 header {@code "n,,"}; {@code c=biws}).</p> + * + * @since 5.6 + */ + +/** + * Strict HTTP SCRAM client implementing {@code SCRAM-SHA-256} per RFC 7804 + * with SCRAM core per RFC 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 2xx Authentication-Info Review Comment: I believe this header can appear on any status code, but 401: Rationale, consider your auth creds are valid, but the actual request causes 403, 500, 400, redirect, not modified, etc... ########## httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/ScramScheme.java: ########## @@ -0,0 +1,685 @@ +/* + * ==================================================================== + * 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 7804 + * with SCRAM core per RFC 5802/7677. + * <p>HTTP SCRAM uses <em>no channel binding</em> (GS2 header {@code "n,,"}; {@code c=biws}).</p> + * + * @since 5.6 + */ + +/** + * Strict HTTP SCRAM client implementing {@code SCRAM-SHA-256} per RFC 7804 + * with SCRAM core per RFC 5802/7677. + * <p>HTTP SCRAM uses <em>no channel binding</em> (GS2 header {@code "n,,"}; {@code c=biws}).</p> + * + * @since 5.6 + */ + +/** + * Strict HTTP SCRAM client implementing {@code SCRAM-SHA-256} per RFC 7804 + * with SCRAM core per RFC 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) Review Comment: Why does the comment appear three times? ########## httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/ScramScheme.java: ########## @@ -0,0 +1,685 @@ +/* + * ==================================================================== + * 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 7804 + * with SCRAM core per RFC 5802/7677. + * <p>HTTP SCRAM uses <em>no channel binding</em> (GS2 header {@code "n,,"}; {@code c=biws}).</p> + * + * @since 5.6 + */ + +/** + * Strict HTTP SCRAM client implementing {@code SCRAM-SHA-256} per RFC 7804 + * with SCRAM core per RFC 5802/7677. + * <p>HTTP SCRAM uses <em>no channel binding</em> (GS2 header {@code "n,,"}; {@code c=biws}).</p> + * + * @since 5.6 + */ + +/** + * Strict HTTP SCRAM client implementing {@code SCRAM-SHA-256} per RFC 7804 + * with SCRAM core per RFC 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 2xx Authentication-Info + 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 successful 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 2xx {@code Authentication-Info}. + * + * @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) { + // 2xx with no 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 || s == null || i == null) { + 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); + } catch (final IllegalArgumentException e) { + this.state = State.FAILED; + throw new MalformedChallengeException("Invalid base64 salt", e); + } + try { + this.iterations = Integer.parseInt(i); + } catch (final NumberFormatException e) { + this.state = State.FAILED; + throw new MalformedChallengeException("Invalid iteration count", e); + } + + if (this.minIterationsRequired > 0 && this.iterations < this.minIterationsRequired) { + this.state = State.FAILED; + throw new AuthenticationException( + "SCRAM iteration count below required minimum: " + this.iterations + " < " + this.minIterationsRequired); + } + if (this.warnMinIterations > 0 && this.iterations < this.warnMinIterations && LOG.isWarnEnabled()) { + LOG.warn("SCRAM iteration count ({}) lower than recommended ({})", this.iterations, warnMinIterations); + } + + this.serverNonce = r; + this.state = State.SERVER_FIRST_RCVD; + this.complete = false; + zeroAndClearExpectedV(); + return; + } + + // --- 2xx path (Authentication-Info) --- Review Comment: Same here ########## httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/ScramScheme.java: ########## @@ -0,0 +1,685 @@ +/* + * ==================================================================== + * 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 7804 + * with SCRAM core per RFC 5802/7677. + * <p>HTTP SCRAM uses <em>no channel binding</em> (GS2 header {@code "n,,"}; {@code c=biws}).</p> + * + * @since 5.6 + */ + +/** + * Strict HTTP SCRAM client implementing {@code SCRAM-SHA-256} per RFC 7804 + * with SCRAM core per RFC 5802/7677. + * <p>HTTP SCRAM uses <em>no channel binding</em> (GS2 header {@code "n,,"}; {@code c=biws}).</p> + * + * @since 5.6 + */ + +/** + * Strict HTTP SCRAM client implementing {@code SCRAM-SHA-256} per RFC 7804 + * with SCRAM core per RFC 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 2xx Authentication-Info + 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 successful 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 2xx {@code Authentication-Info}. + * + * @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) { + // 2xx with no 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 || s == null || i == null) { + 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); + } catch (final IllegalArgumentException e) { + this.state = State.FAILED; + throw new MalformedChallengeException("Invalid base64 salt", e); + } + try { + this.iterations = Integer.parseInt(i); + } catch (final NumberFormatException e) { + this.state = State.FAILED; + throw new MalformedChallengeException("Invalid iteration count", e); + } + + if (this.minIterationsRequired > 0 && this.iterations < this.minIterationsRequired) { + this.state = State.FAILED; + throw new AuthenticationException( + "SCRAM iteration count below required minimum: " + this.iterations + " < " + this.minIterationsRequired); + } + if (this.warnMinIterations > 0 && this.iterations < this.warnMinIterations && LOG.isWarnEnabled()) { + LOG.warn("SCRAM iteration count ({}) lower than recommended ({})", this.iterations, warnMinIterations); + } + + this.serverNonce = r; + this.state = State.SERVER_FIRST_RCVD; + this.complete = false; + zeroAndClearExpectedV(); + return; + } + + // --- 2xx path (Authentication-Info) --- + // For Authentication-Info, RFC 7804 does NOT mandate a scheme token; do NOT enforce scheme name here. + final String data = params.get("data"); + if (data == null) { + return; + } + final String decoded = b64ToString(data); + final Map<String, String> attrs = parseAttrs(decoded); + final String err = attrs.get("e"); + if (err != null) { + this.state = State.FAILED; + throw new AuthenticationException("SCRAM server error: " + err); + } + final String vB64 = attrs.get("v"); + if (vB64 == null) { + return; + } + + // compare 'v' in constant time; treat bad base64 for v as a signature mismatch (tests expect "signature") + final byte[] expected = this.expectedV; + this.expectedV = null; // clear reference early + + byte[] vBytes = null; + boolean match; + try { + vBytes = B64D.decode(vB64); + match = expected != null && MessageDigest.isEqual(expected, vBytes); + } catch (final IllegalArgumentException e) { + match = false; // invalid base64 for v -> treat as mismatch + } finally { + zero(vBytes); + zero(expected); + } + + if (!match) { + this.state = State.FAILED; + throw new MalformedChallengeException("SCRAM server signature mismatch"); + } + this.complete = true; + this.state = State.COMPLETE; + } + + /** + * @since 5.6 + */ + @Override + public boolean isChallengeComplete() { + return this.complete || this.state == State.COMPLETE || this.state == State.FAILED; + } + + /** + * @since 5.6 + */ + @Override + public String getRealm() { + return this.realm; + } + + /** + * Allow response when: + * - INIT (preemptive client-first) — only if creds have been prepared + * - ANNOUNCED (401 without data) + * - SERVER_FIRST_RCVD (ready to send client-final) + * + * @since 5.6 + */ + @Override + public boolean isResponseReady( + final HttpHost host, + final CredentialsProvider credentialsProvider, + final HttpContext context) throws AuthenticationException { + + if (credentialsProvider == null) { + throw new IllegalArgumentException("CredentialsProvider"); Review Comment: NPE ########## httpclient5/src/main/java/org/apache/hc/client5/http/impl/ScramException.java: ########## @@ -0,0 +1,73 @@ +/* + * ==================================================================== + * 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; + +import org.apache.hc.client5.http.auth.AuthenticationException; + +/** + * Represents an exception that occurs during SCRAM (Salted Challenge Response Authentication Mechanism) authentication. + * <p> + * SCRAM is a family of SASL mechanisms used for secure authentication. This exception is thrown when + * an error or issue is encountered during the SCRAM authentication process. + * </p> + * + * @since 5.5 Review Comment: 5.6? ########## httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/ScramScheme.java: ########## @@ -0,0 +1,685 @@ +/* + * ==================================================================== + * 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 7804 + * with SCRAM core per RFC 5802/7677. + * <p>HTTP SCRAM uses <em>no channel binding</em> (GS2 header {@code "n,,"}; {@code c=biws}).</p> + * + * @since 5.6 + */ + +/** + * Strict HTTP SCRAM client implementing {@code SCRAM-SHA-256} per RFC 7804 + * with SCRAM core per RFC 5802/7677. + * <p>HTTP SCRAM uses <em>no channel binding</em> (GS2 header {@code "n,,"}; {@code c=biws}).</p> + * + * @since 5.6 + */ + +/** + * Strict HTTP SCRAM client implementing {@code SCRAM-SHA-256} per RFC 7804 + * with SCRAM core per RFC 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 2xx Authentication-Info + 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 successful 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 2xx {@code Authentication-Info}. + * + * @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) { + // 2xx with no info: nothing to do Review Comment: Same here ########## httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/ScramScheme.java: ########## @@ -0,0 +1,685 @@ +/* + * ==================================================================== + * 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 7804 + * with SCRAM core per RFC 5802/7677. + * <p>HTTP SCRAM uses <em>no channel binding</em> (GS2 header {@code "n,,"}; {@code c=biws}).</p> + * + * @since 5.6 + */ + +/** + * Strict HTTP SCRAM client implementing {@code SCRAM-SHA-256} per RFC 7804 + * with SCRAM core per RFC 5802/7677. + * <p>HTTP SCRAM uses <em>no channel binding</em> (GS2 header {@code "n,,"}; {@code c=biws}).</p> + * + * @since 5.6 + */ + +/** + * Strict HTTP SCRAM client implementing {@code SCRAM-SHA-256} per RFC 7804 + * with SCRAM core per RFC 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 2xx Authentication-Info + 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 successful 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 2xx {@code Authentication-Info}. Review Comment: Same here ########## httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/ScramScheme.java: ########## @@ -0,0 +1,685 @@ +/* + * ==================================================================== + * 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 7804 + * with SCRAM core per RFC 5802/7677. + * <p>HTTP SCRAM uses <em>no channel binding</em> (GS2 header {@code "n,,"}; {@code c=biws}).</p> + * + * @since 5.6 + */ + +/** + * Strict HTTP SCRAM client implementing {@code SCRAM-SHA-256} per RFC 7804 + * with SCRAM core per RFC 5802/7677. + * <p>HTTP SCRAM uses <em>no channel binding</em> (GS2 header {@code "n,,"}; {@code c=biws}).</p> + * + * @since 5.6 + */ + +/** + * Strict HTTP SCRAM client implementing {@code SCRAM-SHA-256} per RFC 7804 + * with SCRAM core per RFC 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 2xx Authentication-Info + 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 successful 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 2xx {@code Authentication-Info}. + * + * @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) { + // 2xx with no 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 || s == null || i == null) { Review Comment: Can those be empty? ########## httpclient5/src/main/java/org/apache/hc/client5/http/impl/DefaultAuthenticationStrategy.java: ########## @@ -67,10 +67,11 @@ public class DefaultAuthenticationStrategy implements AuthenticationStrategy { public static final DefaultAuthenticationStrategy INSTANCE = new DefaultAuthenticationStrategy(); private static final List<String> DEFAULT_SCHEME_PRIORITY = - Collections.unmodifiableList(Arrays.asList( - StandardAuthScheme.BEARER, - StandardAuthScheme.DIGEST, - StandardAuthScheme.BASIC)); + Collections.unmodifiableList(Arrays.asList( + StandardAuthScheme.BEARER, + StandardAuthScheme.SCRAM_SHA_256, Review Comment: This order is of course questionable because if `Bearer` is peformed via `client_credentials` first it isn't better than SCRAM, from my PoV -- 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]
