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 @@ -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,31 @@ 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 (preventing gadget chain attacks). Use the class loader
// of HttpTransportFactory to ensure the class is loaded from the same context as the library
// to try to prevent any class loading manipulation.
Class<?> clazz =
Class.forName(
appIdentityServiceClassName, false, AppIdentityService.class.getClassLoader());

// Check that the class is an instance of `AppIdentityService` to prevent loading of
// arbitrary classes.
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,136 @@
/*
* 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 {
AppEngineCredentials credentials =
AppEngineCredentials.newBuilder().setScopes(Collections.singleton("scope")).build();

// 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());

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(credentials);

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

assertThrows(IOException.class, ois::readObject);

bos.close();
oos.close();
bis.close();
ois.close();
}

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

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

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

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

assertNotNull(deserialized);
Field serviceField = AppEngineCredentials.class.getDeclaredField("appIdentityService");
serviceField.setAccessible(true);
Object service = serviceField.get(deserialized);
assertEquals(MockAppIdentityService.class, service.getClass());

bos.close();
oos.close();
bis.close();
ois.close();
}

@Test
void testNonExistentClassDeserialization() throws Exception {
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");

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

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

assertThrows(ClassNotFoundException.class, ois::readObject);

bos.close();
oos.close();
bis.close();
ois.close();
}
}
61 changes: 57 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,61 @@ 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 transport or ServiceLoader-provided
// transport. This avoids unsafe reflection for the most common use cases. This check runs first
// to replicate the logic in each Credential's constructor.
HttpTransportFactory currentFactory =
getFromServiceLoader(HttpTransportFactory.class, OAuth2Utils.HTTP_TRANSPORT_FACTORY);
// If this doesn't match, then it may be a custom implementation of HttpTransportFactory
if (className.equals(currentFactory.getClass().getName())) {
return currentFactory;
}

// Fallback to reflection to initialize the transport if the requested class is not from
// ServiceLoader or the default value. This handles cases where a custom factory was used.
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 (preventing gadget chain attacks). Use the class loader
// of HttpTransportFactory to ensure the class is loaded from the same context as the library
// to try to prevent any class loading manipulation.
Class<?> clazz = Class.forName(className, false, HttpTransportFactory.class.getClassLoader());

// Check that the class is an instance of `HttpTransportFactory` to prevent loading of
// arbitrary classes.
if (!HttpTransportFactory.class.isAssignableFrom(clazz)) {
throw new IOException(
String.format(
"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
Loading
Loading