Skip to content

Digest auth new #2098

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 52 additions & 37 deletions client/src/main/java/org/asynchttpclient/Realm.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,18 @@

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;
import static org.asynchttpclient.util.HttpConstants.Methods.GET;
import static org.asynchttpclient.util.MessageDigestUtils.pooledMd5MessageDigest;
import static org.asynchttpclient.util.MiscUtils.isNonEmpty;
import static org.asynchttpclient.util.StringUtils.appendBase16;
import static org.asynchttpclient.util.StringUtils.toHexString;
import org.asynchttpclient.util.MessageDigestUtils;

/**
* This class is required when authentication is needed. The class support
Expand Down Expand Up @@ -275,13 +276,15 @@ public static class Builder {
private String ntlmHost = "localhost";
private boolean useAbsoluteURI;
private boolean omitQuery;
private Charset digestCharset = ISO_8859_1; // RFC default
/**
* Kerberos/Spnego properties
*/
private @Nullable Map<String, String> customLoginConfig;
private @Nullable String servicePrincipalName;
private boolean useCanonicalHostname;
private @Nullable String loginContextName;
private @Nullable String cs;

public Builder() {
principal = null;
Expand Down Expand Up @@ -424,6 +427,10 @@ public Builder parseWWWAuthenticateHeader(String headerLine) {
.setOpaque(match(headerLine, "opaque"))
.setScheme(isNonEmpty(nonce) ? AuthScheme.DIGEST : AuthScheme.BASIC);
String algorithm = match(headerLine, "algorithm");
String cs = match(headerLine, "charset");
if ("UTF-8".equalsIgnoreCase(cs)) {
this.digestCharset = UTF_8;
}
if (isNonEmpty(algorithm)) {
setAlgorithm(algorithm);
}
Expand Down Expand Up @@ -452,62 +459,68 @@ public Builder parseProxyAuthenticateHeader(String headerLine) {
return this;
}

private void newCnonce(MessageDigest md) {
byte[] b = new byte[8];
ThreadLocalRandom.current().nextBytes(b);
b = md.digest(b);
cnonce = toHexString(b);
}

/**
* TODO: A Pattern/Matcher may be better.
* Extracts the value of a token from a WWW-Authenticate or Proxy-Authenticate header line.
* Example: match('Digest realm="test", nonce="abc"', "realm") returns "test"
*/
private static @Nullable String match(String headerLine, String token) {
if (headerLine == null) {
return null;
}

int match = headerLine.indexOf(token);
if (match <= 0) {
return null;
}
if (headerLine == null || token == null) return null;
String pattern = token + "=\"";
int start = headerLine.indexOf(pattern);
if (start == -1) return null;
start += pattern.length();
int end = headerLine.indexOf('"', start);
if (end == -1) return null;
return headerLine.substring(start, end);
}

// = to skip
match += token.length() + 1;
int trailingComa = headerLine.indexOf(',', match);
String value = headerLine.substring(match, trailingComa > 0 ? trailingComa : headerLine.length());
value = value.length() > 0 && value.charAt(value.length() - 1) == '"'
? value.substring(0, value.length() - 1)
: value;
return value.charAt(0) == '"' ? value.substring(1) : value;
private void newCnonce(MessageDigest md) {
byte[] b = new byte[8];
ThreadLocalRandom.current().nextBytes(b);
byte[] full = md.digest(b);
// trim to first 8 bytes → 16 hex chars
byte[] small = Arrays.copyOf(full, Math.min(8, full.length));
cnonce = toHexString(small);
}

private static byte[] md5FromRecycledStringBuilder(StringBuilder sb, MessageDigest md) {
md.update(StringUtils.charSequence2ByteBuffer(sb, ISO_8859_1));
private static byte[] digestFromRecycledStringBuilder(StringBuilder sb, MessageDigest md, Charset enc) {
md.update(StringUtils.charSequence2ByteBuffer(sb, enc));
sb.setLength(0);
return md.digest();
}

private static MessageDigest getDigestInstance(String algorithm) {
if ("SHA-512/256".equalsIgnoreCase(algorithm)) algorithm = "SHA-512-256";
if (algorithm == null || "MD5".equalsIgnoreCase(algorithm) || "MD5-sess".equalsIgnoreCase(algorithm)) {
return MessageDigestUtils.pooledMd5MessageDigest();
} else if ("SHA-256".equalsIgnoreCase(algorithm) || "SHA-256-sess".equalsIgnoreCase(algorithm)) {
return MessageDigestUtils.pooledSha256MessageDigest();
} else if ("SHA-512-256".equalsIgnoreCase(algorithm) || "SHA-512-256-sess".equalsIgnoreCase(algorithm)) {
return MessageDigestUtils.pooledSha512_256MessageDigest();
} else {
throw new UnsupportedOperationException("Digest algorithm not supported: " + algorithm);
}
}

private byte[] ha1(StringBuilder sb, MessageDigest md) {
// if algorithm is "MD5" or is unspecified => A1 = username ":" realm-value ":"
// passwd
// if algorithm is "MD5-sess" => A1 = MD5( username-value ":" realm-value ":"
// passwd ) ":" nonce-value ":" cnonce-value

sb.append(principal).append(':').append(realmName).append(':').append(password);
byte[] core = md5FromRecycledStringBuilder(sb, md);
byte[] core = digestFromRecycledStringBuilder(sb, md, digestCharset);

if (algorithm == null || "MD5".equals(algorithm)) {
if (algorithm == null || "MD5".equalsIgnoreCase(algorithm) || "SHA-256".equalsIgnoreCase(algorithm) || "SHA-512-256".equalsIgnoreCase(algorithm)) {
// A1 = username ":" realm-value ":" passwd
return core;
}
if ("MD5-sess".equals(algorithm)) {
// A1 = MD5(username ":" realm-value ":" passwd ) ":" nonce ":" cnonce
if ("MD5-sess".equalsIgnoreCase(algorithm) || "SHA-256-sess".equalsIgnoreCase(algorithm) || "SHA-512-256-sess".equalsIgnoreCase(algorithm)) {
// A1 = HASH(username ":" realm-value ":" passwd ) ":" nonce ":" cnonce
appendBase16(sb, core);
sb.append(':').append(nonce).append(':').append(cnonce);
return md5FromRecycledStringBuilder(sb, md);
return digestFromRecycledStringBuilder(sb, md, digestCharset);
}

throw new UnsupportedOperationException("Digest algorithm not supported: " + algorithm);
}

Expand All @@ -526,7 +539,7 @@ private byte[] ha2(StringBuilder sb, String digestUri, MessageDigest md) {
throw new UnsupportedOperationException("Digest qop not supported: " + qop);
}

return md5FromRecycledStringBuilder(sb, md);
return digestFromRecycledStringBuilder(sb, md, digestCharset);
}

private void appendMiddlePart(StringBuilder sb) {
Expand All @@ -553,7 +566,7 @@ private void newResponse(MessageDigest md) {
appendMiddlePart(sb);
appendBase16(sb, ha2);

byte[] responseDigest = md5FromRecycledStringBuilder(sb, md);
byte[] responseDigest = digestFromRecycledStringBuilder(sb, md, digestCharset);
response = toHexString(responseDigest);
}
}
Expand All @@ -567,7 +580,9 @@ public Realm build() {

// Avoid generating
if (isNonEmpty(nonce)) {
MessageDigest md = pooledMd5MessageDigest();
// Defensive: if algorithm is null, default to MD5
String algo = (algorithm != null) ? algorithm : "MD5";
MessageDigest md = getDigestInstance(algo);
newCnonce(md);
newResponse(md);
}
Expand All @@ -585,7 +600,7 @@ public Realm build() {
cnonce,
uri,
usePreemptive,
charset,
(scheme == AuthScheme.DIGEST ? digestCharset : charset),
ntlmDomain,
ntlmHost,
useAbsoluteURI,
Expand Down
Loading
Loading