Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Date;
import java.util.Objects;
Expand Down Expand Up @@ -132,7 +134,29 @@ public boolean equals(Object obj) {

private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
input.defaultReadObject();
appIdentityService = newInstance(appIdentityServiceClassName);
try {
// Load the class without initializing it (second argument: false) to prevent
// static initializers from running, which could potentially be used for
// malicious purposes. Use the class loader of AppIdentityService (third
// argument) to ensure the class is loaded from the same context as the library,
// preventing class loading manipulation.
Class<?> clazz =
Class.forName(
appIdentityServiceClassName, false, AppIdentityService.class.getClassLoader());
if (!AppIdentityService.class.isAssignableFrom(clazz)) {
throw new IOException(
String.format(
"The class, %s, is not assignable from %s.",
appIdentityServiceClassName, AppIdentityService.class.getName()));
}
Constructor<?> constructor = clazz.getConstructor();
appIdentityService = (AppIdentityService) constructor.newInstance();
} catch (InstantiationException
| IllegalAccessException
| NoSuchMethodException
| InvocationTargetException e) {
throw new IOException(e);
}
}

public static Builder newBuilder() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/*
* Copyright 2026, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package com.google.auth.appengine;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.util.Collections;
import org.junit.jupiter.api.Test;

class AppEngineDeserializationSecurityTest {

/** A class that does not implement HttpTransportFactory. */
static class ArbitraryClass {}

@Test
void testArbitraryClassInstantiationPrevented() throws Exception {
// 1. Create valid credentials
AppEngineCredentials credentials =
AppEngineCredentials.newBuilder().setScopes(Collections.singleton("scope")).build();

// 2. Use reflection to set appIdentityServiceClassName to ArbitraryClass
// as the setter must be of AppIdentityService
Field classNameField =
AppEngineCredentials.class.getDeclaredField("appIdentityServiceClassName");
classNameField.setAccessible(true);
classNameField.set(credentials, ArbitraryClass.class.getName());

// 3. Serialize
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(credentials);
oos.close();

// 4. Deserialize
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);

// 5. Assert that IOException is thrown (validation failure)
assertThrows(IOException.class, ois::readObject);
}

@Test
void testValidServiceDeserialization() throws Exception {
// 1. Create valid credentials with MockAppIdentityService
MockAppIdentityService mockService = new MockAppIdentityService();
AppEngineCredentials credentials =
AppEngineCredentials.newBuilder()
.setScopes(Collections.singleton("scope"))
.setAppIdentityService(mockService)
.build();

// 2. Serialize
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(credentials);
oos.close();

// 3. Deserialize
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);

AppEngineCredentials deserialized = (AppEngineCredentials) ois.readObject();

// 4. Verify deserialization success and field type
assertNotNull(deserialized);
Field serviceField = AppEngineCredentials.class.getDeclaredField("appIdentityService");
serviceField.setAccessible(true);
Object service = serviceField.get(deserialized);
assertEquals(MockAppIdentityService.class, service.getClass());
}

@Test
void testNonExistentClassDeserialization() throws Exception {
// 1. Create valid credentials
AppEngineCredentials credentials =
AppEngineCredentials.newBuilder().setScopes(Collections.singleton("scope")).build();

// 2. Use reflection to set appIdentityServiceClassName to non-existent class
Field classNameField =
AppEngineCredentials.class.getDeclaredField("appIdentityServiceClassName");
classNameField.setAccessible(true);
classNameField.set(credentials, "com.google.nonexistent.Class");

// 3. Serialize
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(credentials);
oos.close();

// 4. Deserialize
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);

// 5. Assert ClassNotFoundException
assertThrows(ClassNotFoundException.class, ois::readObject);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -673,6 +673,9 @@ public boolean equals(Object obj) {

private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
input.defaultReadObject();
// Use Oauth2Credential's newInstance() to try to safely instantiate the transport factory,
// with best-effort prevention against RCE attacks by validating the class name and loading
// behavior.
transportFactory = newInstance(transportFactoryClassName);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,9 @@ static ExternalAccountAuthorizedUserCredentials fromJson(

private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
input.defaultReadObject();
// Use Oauth2Credential's newInstance() to try to safely instantiate the transport factory,
// with best-effort prevention against RCE attacks by validating the class name and loading
// behavior.
transportFactory = newInstance(transportFactoryClassName);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,9 @@ public CredentialSource getCredentialSource() {
private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
// Properly deserialize the transient transportFactory.
input.defaultReadObject();
// Use Oauth2Credential's newInstance() to try to safely instantiate the transport factory,
// with best-effort prevention against RCE attacks by validating the class name and loading
// behavior.
transportFactory = newInstance(transportFactoryClassName);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,9 @@ public Builder toBuilder() {
private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
// properly deserialize the transient transportFactory.
input.defaultReadObject();
// Use Oauth2Credential's newInstance() to try to safely instantiate the transport factory,
// with best-effort prevention against RCE attacks by validating the class name and loading
// behavior.
transportFactory = newInstance(transportFactoryClassName);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -911,6 +911,9 @@ public ImpersonatedCredentials build() {

private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
input.defaultReadObject();
// Use Oauth2Credential's newInstance() to try to safely instantiate the transport factory,
// with best-effort prevention against RCE attacks by validating the class name and loading
// behavior.
transportFactory = newInstance(transportFactoryClassName);
}
}
60 changes: 56 additions & 4 deletions oauth2_http/java/com/google/auth/oauth2/OAuth2Credentials.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import com.google.auth.Credentials;
import com.google.auth.RequestMetadataCallback;
import com.google.auth.http.AuthHttpConstants;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
Expand All @@ -51,6 +52,8 @@
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.time.Duration;
import java.util.ArrayList;
Expand Down Expand Up @@ -475,11 +478,60 @@ private void readObject(ObjectInputStream input) throws IOException, ClassNotFou
refreshTask = null;
}

@SuppressWarnings("unchecked")
protected static <T> T newInstance(String className) throws IOException, ClassNotFoundException {
/**
* Best-effort safe mechanism to attempt to instantiate an {@link HttpTransportFactory} from a
* class name.
*
* <p>This method attempts to avoid Arbitrary Code Execution (ACE) vulnerabilities by:
*
* <ol>
* <li>Checking if the class name matches the default or ServiceLoader-provided factory, and
* returning that instance if so.
* <li>If not, loading the class using reflection without running static initializers.
* <li>Verifying that the loaded class is assignable to {@link HttpTransportFactory}.
* <li>Only after verification, instantiating the class using its default constructor.
* </ol>
*
* @param className The fully qualified name of the class to instantiate.
* @return An instance of {@link HttpTransportFactory}.
* @throws IOException If the class cannot be loaded, is the wrong type, or cannot be
* instantiated.
* @throws ClassNotFoundException If the class cannot be found.
*/
protected static HttpTransportFactory newInstance(String className)
throws IOException, ClassNotFoundException {
// Check if the requested class matches the default or ServiceLoader-provided
// factory. This avoids unsafe reflection for the most common use cases.
// This check runs first to replicate the logic in Credential constructor.
HttpTransportFactory currentFactory =
getFromServiceLoader(HttpTransportFactory.class, OAuth2Utils.HTTP_TRANSPORT_FACTORY);
// It is possible that there is a custom implementation of HttpTransportFactory
if (className.equals(currentFactory.getClass().getName())) {
return currentFactory;
}

// Fallback to reflection if the requested class differs from the ServiceLoader
// default. This handles cases where a custom factory was used during
// serialization but is not the currently active ServiceLoader provider.
try {
return (T) Class.forName(className).newInstance();
} catch (InstantiationException | IllegalAccessException e) {
// Load the class without initializing it (second argument: false) to prevent
// static initializers from running, which could potentially be used for
// malicious purposes. Use the class loader of HttpTransportFactory (third argument)
// to ensure the class is loaded from the same context as the library, preventing
// class loading manipulation.
Class<?> clazz = Class.forName(className, false, HttpTransportFactory.class.getClassLoader());
if (!HttpTransportFactory.class.isAssignableFrom(clazz)) {
throw new IOException(
String.format(
"The class, %s, is not assignable from %s.",
className, HttpTransportFactory.class.getName()));
}
Constructor<?> constructor = clazz.getDeclaredConstructor();
return (HttpTransportFactory) constructor.newInstance();
} catch (InstantiationException
| IllegalAccessException
| NoSuchMethodException
| InvocationTargetException e) {
throw new IOException(e);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1126,6 +1126,9 @@ private Map<String, List<String>> getRequestMetadataWithSelfSignedJwt(URI uri)
private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
// properly deserialize the transient transportFactory
input.defaultReadObject();
// Use Oauth2Credential's newInstance() to try to safely instantiate the transport factory,
// with best-effort prevention against RCE attacks by validating the class name and loading
// behavior.
transportFactory = newInstance(transportFactoryClassName);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,9 @@ public boolean equals(Object obj) {

private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
input.defaultReadObject();
// Use Oauth2Credential's newInstance() to try to safely instantiate the transport factory,
// with best-effort prevention against RCE attacks by validating the class name and loading
// behavior.
transportFactory = newInstance(transportFactoryClassName);
}

Expand Down
Loading
Loading