Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -237,16 +237,80 @@ public static byte[] getHashToCurve(byte[] message, byte[] domain)
}
}

public static byte[] blind(byte[] password, byte[] blindScalar) throws GeneralSecurityException {
byte[] hashedPoint = getHashToCurve(password, LOGIN_DOMAIN_SEPARATION_TAG.getBytes(UTF_8));
/**
* Decodes a canonical 33-byte compressed secp256r1 point, rejecting the point at infinity,
* non-canonical encodings, and off-curve coordinates per RFC 9497 Section 3.3.1 / RFC 9807.
*/
private static ECPoint decodeCompressedPoint(ECCurve curve, byte[] encoded, String label)
throws GeneralSecurityException {
if (encoded == null) {
throw new GeneralSecurityException("Invalid " + label + ": point bytes must not be null");
}
if (encoded.length != PUBLIC_KEY_LENGTH || (encoded[0] != 0x02 && encoded[0] != 0x03)) {
throw new GeneralSecurityException(
"Invalid "
+ label
+ ": expected "
+ PUBLIC_KEY_LENGTH
+ "-byte compressed secp256r1 point");
}
ECPoint point;
try {
point = curve.decodePoint(encoded);
} catch (IllegalArgumentException e) {
throw new GeneralSecurityException(
"Invalid " + label + ": failed to decode secp256r1 point", e);
}
// Defense-in-depth: unreachable via public API on prime-order secp256r1 after 33-byte
// compressed decoding, kept to fail closed if the curve or decoder ever changes.
if (point.isInfinity() || !point.isValid()) {
throw new GeneralSecurityException(
"Invalid " + label + ": point is at infinity or not on curve");
}
return point;
}

/**
* Validates that a big-endian scalar byte array is non-null, non-empty, and non-zero modulo the
* curve order, returning the reduced value in {@code [1, order - 1]} so scalar inversion and
* BouncyCastle multiplication cannot fail or collapse to infinity.
*/
private static BigInteger validateNonZeroScalar(
byte[] scalarBytes, BigInteger order, String label) throws GeneralSecurityException {
if (scalarBytes == null || scalarBytes.length == 0) {
throw new GeneralSecurityException("Invalid " + label + ": scalar must not be null or empty");
}
BigInteger reduced = new BigInteger(1, scalarBytes).mod(order);
if (reduced.equals(BigInteger.ZERO)) {
throw new GeneralSecurityException(
"Invalid " + label + ": scalar must be non-zero modulo curve order");
}
return reduced;
}

/**
* Normalizes and encodes a curve point in compressed form, failing closed if the multiplication
* result is the point at infinity.
*/
private static byte[] encodeNonInfinityPoint(ECPoint point, String label)
throws GeneralSecurityException {
ECPoint normalized = point.normalize();
// Defense-in-depth: unreachable on prime-order secp256r1 with validated non-zero scalars,
// kept to fail closed if the curve or caller invariants ever change.
if (normalized.isInfinity()) {
throw new GeneralSecurityException("Invalid " + label + ": resulting point is at infinity");
}
return normalized.getEncoded(true);
}

public static byte[] blind(byte[] password, byte[] blindScalar) throws GeneralSecurityException {
X9ECParameters params = CustomNamedCurves.getByName(CURVE_NAME);
ECCurve curve = params.getCurve();
BigInteger scalar = validateNonZeroScalar(blindScalar, params.getN(), "blindScalar");

ECPoint point = curve.decodePoint(hashedPoint);
BigInteger scalar = new BigInteger(1, blindScalar);
byte[] hashedPoint = getHashToCurve(password, LOGIN_DOMAIN_SEPARATION_TAG.getBytes(UTF_8));
ECPoint point = decodeCompressedPoint(params.getCurve(), hashedPoint, "hashedPoint");

return point.multiply(scalar).getEncoded(true);
return encodeNonInfinityPoint(point.multiply(scalar), "blindedPoint");
}

public static byte[] expand(byte[] keyMaterial, byte[] info, int size)
Expand Down Expand Up @@ -323,24 +387,24 @@ public static byte[] mac(byte[] key, byte[] data) throws GeneralSecurityExceptio

public static byte[] finalize(byte[] blind, byte[] evaluatedMessage)
throws GeneralSecurityException {
BigInteger blindBigInt = new BigInteger(1, blind);
X9ECParameters params = CustomNamedCurves.getByName(CURVE_NAME);
BigInteger order = params.getN();
BigInteger blindBigInt = validateNonZeroScalar(blind, order, "blind");
BigInteger inverseBlind = blindBigInt.modInverse(order);

ECCurve curve = params.getCurve();
ECPoint evaluatedPoint = curve.decodePoint(evaluatedMessage);
ECPoint evaluatedPoint =
decodeCompressedPoint(params.getCurve(), evaluatedMessage, "evaluatedMessage");

return evaluatedPoint.multiply(inverseBlind).getEncoded(true);
return encodeNonInfinityPoint(evaluatedPoint.multiply(inverseBlind), "evaluatedMessage");
}

public static byte[] diffieHellman(byte[] privateKey, byte[] peerPublicKey)
throws GeneralSecurityException {
X9ECParameters params = CustomNamedCurves.getByName(CURVE_NAME);
ECCurve curve = params.getCurve();
ECPoint peerPublicPoint = curve.decodePoint(peerPublicKey);
BigInteger priv = new BigInteger(1, privateKey);
return peerPublicPoint.multiply(priv).getEncoded(true);
BigInteger priv = validateNonZeroScalar(privateKey, params.getN(), "privateKey");
ECPoint peerPublicPoint =
decodeCompressedPoint(params.getCurve(), peerPublicKey, "peerPublicKey");
return encodeNonInfinityPoint(peerPublicPoint.multiply(priv), "peerPublicKey");
}

public static byte[] randomOracleSha256(byte[] x, BigInteger max)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,32 @@
package com.google.cloud.spanner.omni;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;

import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.omni.Authentication.HashParameters;
import com.google.cloud.spanner.omni.Authentication.PasswordAuthenticationHandshakeResponse;
import com.google.cloud.spanner.omni.Authentication.PasswordAuthenticationProtocol;
import com.google.cloud.spanner.omni.Login.AccessToken;
import com.google.cloud.spanner.omni.Login.InitialOpaqueLoginRequest;
import com.google.cloud.spanner.omni.Login.InitialOpaqueLoginResponse;
import com.google.cloud.spanner.omni.Login.LoginRequest;
import com.google.cloud.spanner.omni.Login.LoginResponse;
import com.google.cloud.spanner.omni.Login.OpaqueLoginResponse;
import com.google.crypto.tink.InsecureSecretKeyAccess;
import com.google.crypto.tink.util.SecretBytes;
import com.google.protobuf.ByteString;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import io.grpc.stub.StreamObserver;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
Expand All @@ -42,4 +65,239 @@ public void testExpectedEnvelopeSize() {
org.junit.Assert.assertEquals(
"Envelope size should be 97 bytes (33 + 32 + 32)", 97, LoginClient.EXPECTED_ENVELOPE_SIZE);
}

/**
* Verifies that {@link LoginClient#login} aborts with a {@link SpannerException} when a rogue
* server returns the point at infinity ({@code {0x00}}) as {@code evaluated_message}, even if the
* server forges an otherwise valid OPAQUE envelope and server MAC from {@code oprf = {0x00}}.
*/
@Test
public void testLoginRejectsPointAtInfinityEvaluatedMessage() throws Exception {
HashParameters fastHashParams = createFastArgon2HashParameters();
LoginServiceGrpc.LoginServiceImplBase rogueServer =
createRoguePointAtInfinityServer(fastHashParams);

String serverName = InProcessServerBuilder.generateName();
Server server =
InProcessServerBuilder.forName(serverName)
.directExecutor()
.addService(rogueServer)
.build()
.start();
ManagedChannel channel = InProcessChannelBuilder.forName(serverName).directExecutor().build();
try {
LoginClient client = new LoginClient(channel);
SecretBytes password =
SecretBytes.copyFrom(
"super-secret-password".getBytes(StandardCharsets.UTF_8),
InsecureSecretKeyAccess.get());

SpannerException exception =
assertThrows(SpannerException.class, () -> client.login("alice", password));
assertTrue(exception.getCause() instanceof GeneralSecurityException);
assertTrue(exception.getCause().getMessage().contains("evaluatedMessage"));
} finally {
channel.shutdownNow();
server.shutdownNow();
channel.awaitTermination(5, TimeUnit.SECONDS);
server.awaitTermination(5, TimeUnit.SECONDS);
}
}

/** Creates minimal Argon2id parameters so the OPAQUE test executes quickly. */
private static HashParameters createFastArgon2HashParameters() {
return HashParameters.newBuilder()
.setArgon2IdParameters(
HashParameters.Argon2IdParameters.newBuilder()
.setIterationCount(1)
.setMemoryUsage(8)
.setParallelism(1)
.setHashSize(32)
.build())
.build();
}

/**
* Builds a fake {@code LoginService} that negotiates OPAQUE, responds to the initial request with
* {@code evaluated_message = {0x00}} and forged envelope/MAC material, and would issue an access
* token if the client did not reject the point at infinity.
*/
private static LoginServiceGrpc.LoginServiceImplBase createRoguePointAtInfinityServer(
HashParameters hashParams) {
return new LoginServiceGrpc.LoginServiceImplBase() {
@Override
public StreamObserver<LoginRequest> login(StreamObserver<LoginResponse> responseObserver) {
return new StreamObserver<LoginRequest>() {
@Override
public void onNext(LoginRequest request) {
try {
if (request.hasHandshakeRequest()) {
responseObserver.onNext(buildHandshakeResponse(hashParams));
} else if (request.hasOpaqueRequest()
&& request.getOpaqueRequest().hasInitialRequest()) {
responseObserver.onNext(
buildForgedInitialOpaqueResponse(
request.getUsername(),
request.getOpaqueRequest().getInitialRequest(),
hashParams));
} else if (request.hasOpaqueRequest()
&& request.getOpaqueRequest().hasFinalRequest()) {
responseObserver.onNext(
LoginResponse.newBuilder()
.setAccessToken(AccessToken.newBuilder().build())
.build());
responseObserver.onCompleted();
}
} catch (Exception e) {
responseObserver.onError(e);
}
}

@Override
public void onError(Throwable t) {}

@Override
public void onCompleted() {}
};
}
};
}

/** Builds the OPAQUE handshake response advertising the test Argon2id parameters. */
private static LoginResponse buildHandshakeResponse(HashParameters hashParams) {
return LoginResponse.newBuilder()
.setHandshakeResponse(
PasswordAuthenticationHandshakeResponse.newBuilder()
.setPasswordAuthenticationProtocol(
PasswordAuthenticationProtocol.PASSWORD_AUTHENTICATION_PROTOCOL_OPAQUE)
.setHashParameters(hashParams)
.build())
.build();
}

/**
* Builds a forged initial OPAQUE response using {@code evaluated_message = {0x00}} (point at
* infinity). Without point validation, {@code OpaqueUtil.finalize} would return {@code {0x00}},
* allowing a rogue server without the password to derive the same envelope and AKE keys.
*/
private static LoginResponse buildForgedInitialOpaqueResponse(
String username, InitialOpaqueLoginRequest initReq, HashParameters hashParams)
throws GeneralSecurityException {
byte[] infinity = new byte[] {0x00};

// Derive password-independent OPRF output keys assuming finalize(blind, {0x00}) == {0x00}.
byte[] stretched = OpaqueUtil.stretch(infinity, hashParams);
byte[] randomizedPassword = OpaqueUtil.extract(OpaqueUtil.concat(infinity, stretched));
byte[] maskingKey =
OpaqueUtil.expand(
randomizedPassword, OpaqueUtil.MASKING_KEY_INFO.getBytes(StandardCharsets.UTF_8), 32);

byte[] maskingNonce = new byte[32];
Arrays.fill(maskingNonce, (byte) 0x11);
byte[] pad =
OpaqueUtil.expand(
maskingKey,
OpaqueUtil.concat(
maskingNonce, "CredentialResponsePad".getBytes(StandardCharsets.UTF_8)),
LoginClient.EXPECTED_ENVELOPE_SIZE);

// Forge an envelope containing the attacker's public key and a matching auth tag.
byte[][] serverKeyPair =
OpaqueUtil.generateKeyPair("rogue-server".getBytes(StandardCharsets.UTF_8));
byte[] envelopeNonce = new byte[32];
Arrays.fill(envelopeNonce, (byte) 0x22);
byte[] authKey =
OpaqueUtil.expand(
randomizedPassword,
OpaqueUtil.concat(
envelopeNonce, OpaqueUtil.AUTH_KEY_INFO.getBytes(StandardCharsets.UTF_8)),
32);
byte[] authTag =
OpaqueUtil.mac(
authKey,
OpaqueUtil.concat(
envelopeNonce, serverKeyPair[1], username.getBytes(StandardCharsets.UTF_8)));
byte[] maskedResponse =
OpaqueUtil.xorBytes(OpaqueUtil.concat(serverKeyPair[1], envelopeNonce, authTag), pad);

// Derive the client's static public key from the known randomizedPassword to forge AKE DH3.
byte[] clientSeed =
OpaqueUtil.expand(
randomizedPassword,
OpaqueUtil.concat(
envelopeNonce, OpaqueUtil.PRIVATE_KEY_INFO.getBytes(StandardCharsets.UTF_8)),
32);
byte[][] clientKeyPair =
OpaqueUtil.generateKeyPair(
OpaqueUtil.concat(
clientSeed, OpaqueUtil.DIFFIE_HELLMAN_KEY_INFO.getBytes(StandardCharsets.UTF_8)));

byte[][] serverKeysharePair =
OpaqueUtil.generateKeyPair("rogue-keyshare".getBytes(StandardCharsets.UTF_8));
byte[] serverNonce = new byte[32];
Arrays.fill(serverNonce, (byte) 0x33);

byte[] serverMac =
computeForgedServerMac(
username,
initReq,
infinity,
serverNonce,
serverKeyPair,
serverKeysharePair,
clientKeyPair[1]);

return LoginResponse.newBuilder()
.setOpaqueResponse(
OpaqueLoginResponse.newBuilder()
.setInitialResponse(
InitialOpaqueLoginResponse.newBuilder()
.setEvaluatedMessage(ByteString.copyFrom(infinity))
.setMaskingNonce(ByteString.copyFrom(maskingNonce))
.setMaskedResponse(ByteString.copyFrom(maskedResponse))
.setServerNonce(ByteString.copyFrom(serverNonce))
.setServerPublicKeyshare(ByteString.copyFrom(serverKeysharePair[1]))
.setServerMac(ByteString.copyFrom(serverMac))
.build())
.build())
.build();
}

/** Computes the OPAQUE 3DH handshake secret and server MAC for the forged initial response. */
private static byte[] computeForgedServerMac(
String username,
InitialOpaqueLoginRequest initReq,
byte[] evaluatedMessage,
byte[] serverNonce,
byte[][] serverKeyPair,
byte[][] serverKeysharePair,
byte[] clientPublicKey)
throws GeneralSecurityException {
byte[] clientPublicKeyshare = initReq.getClientPublicKeyshare().toByteArray();
byte[] dh1 = OpaqueUtil.diffieHellman(serverKeysharePair[0], clientPublicKeyshare);
byte[] dh2 = OpaqueUtil.diffieHellman(serverKeyPair[0], clientPublicKeyshare);
byte[] dh3 = OpaqueUtil.diffieHellman(serverKeysharePair[0], clientPublicKey);

byte[] preamble =
OpaqueUtil.concat(
"OPAQUEv1-".getBytes(StandardCharsets.UTF_8),
username.getBytes(StandardCharsets.UTF_8),
initReq.getClientNonce().toByteArray(),
clientPublicKeyshare,
serverKeyPair[1],
evaluatedMessage,
serverNonce,
serverKeysharePair[1]);
byte[] prk = OpaqueUtil.extract(OpaqueUtil.concat(dh1, dh2, dh3));
byte[] preambleHash = OpaqueUtil.sha256(preamble);
byte[] handshakeSecret =
OpaqueUtil.expand(
prk,
OpaqueUtil.concat(
"OPAQUE-HandshakeSecret".getBytes(StandardCharsets.UTF_8), preambleHash),
32);
byte[] km2 =
OpaqueUtil.expand(handshakeSecret, "OPAQUE-ServerMAC".getBytes(StandardCharsets.UTF_8), 32);
return OpaqueUtil.mac(km2, preambleHash);
}
}
Loading
Loading