diff --git a/libs/core/src/main/java/org/elasticsearch/core/internal/provider/EmbeddedImplClassLoader.java b/libs/core/src/main/java/org/elasticsearch/core/internal/provider/EmbeddedImplClassLoader.java index 751c5146b484a..5e5c82af4807e 100644 --- a/libs/core/src/main/java/org/elasticsearch/core/internal/provider/EmbeddedImplClassLoader.java +++ b/libs/core/src/main/java/org/elasticsearch/core/internal/provider/EmbeddedImplClassLoader.java @@ -23,10 +23,8 @@ import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; -import java.security.AccessController; import java.security.CodeSigner; import java.security.CodeSource; -import java.security.PrivilegedAction; import java.security.SecureClassLoader; import java.util.ArrayList; import java.util.Collections; @@ -96,8 +94,7 @@ record JarMeta(String prefix, boolean isMultiRelease, Set packages, Map< private final ClassLoader parent; static EmbeddedImplClassLoader getInstance(ClassLoader parent, String providerName) { - PrivilegedAction pa = () -> new EmbeddedImplClassLoader(parent, getProviderPrefixes(parent, providerName)); - return AccessController.doPrivileged(pa); + return new EmbeddedImplClassLoader(parent, getProviderPrefixes(parent, providerName)); } private EmbeddedImplClassLoader(ClassLoader parent, Map prefixToCodeBase) { @@ -120,14 +117,12 @@ private EmbeddedImplClassLoader(ClassLoader parent, Map pre record Resource(InputStream inputStream, CodeSource codeSource) {} /** Searches for the named resource. Iterates over all prefixes. */ - private Resource privilegedGetResourceOrNull(JarMeta jarMeta, String pkg, String filepath) { - return AccessController.doPrivileged((PrivilegedAction) () -> { - InputStream is = findResourceInLoaderPkgOrNull(jarMeta, pkg, filepath, parent::getResourceAsStream); - if (is != null) { - return new Resource(is, prefixToCodeBase.get(jarMeta.prefix())); - } - return null; - }); + private Resource getResourceOrNull(JarMeta jarMeta, String pkg, String filepath) { + InputStream is = findResourceInLoaderPkgOrNull(jarMeta, pkg, filepath, parent::getResourceAsStream); + if (is != null) { + return new Resource(is, prefixToCodeBase.get(jarMeta.prefix())); + } + return null; } @Override @@ -148,7 +143,7 @@ public Class findClass(String name) throws ClassNotFoundException { String pkg = toPackageName(filepath); JarMeta jarMeta = packageToJarMeta.get(pkg); if (jarMeta != null) { - Resource res = privilegedGetResourceOrNull(jarMeta, pkg, filepath); + Resource res = getResourceOrNull(jarMeta, pkg, filepath); if (res != null) { try (InputStream in = res.inputStream()) { byte[] bytes = in.readAllBytes(); diff --git a/libs/core/src/main/java/org/elasticsearch/core/internal/provider/ProviderLocator.java b/libs/core/src/main/java/org/elasticsearch/core/internal/provider/ProviderLocator.java index 902c61402c058..e3b36463d80ea 100644 --- a/libs/core/src/main/java/org/elasticsearch/core/internal/provider/ProviderLocator.java +++ b/libs/core/src/main/java/org/elasticsearch/core/internal/provider/ProviderLocator.java @@ -15,9 +15,6 @@ import java.io.UncheckedIOException; import java.lang.module.Configuration; import java.lang.module.ModuleFinder; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.Locale; import java.util.Objects; import java.util.ServiceConfigurationError; @@ -97,10 +94,9 @@ public ProviderLocator(String providerName, Class providerType, String provid @Override public T get() { try { - PrivilegedExceptionAction pa = this::load; - return AccessController.doPrivileged(pa); - } catch (PrivilegedActionException e) { - throw new UncheckedIOException((IOException) e.getCause()); + return load(); + } catch (IOException e) { + throw new UncheckedIOException(e); } } diff --git a/qa/evil-tests/src/test/java/org/elasticsearch/common/logging/EvilLoggerTests.java b/qa/evil-tests/src/test/java/org/elasticsearch/common/logging/EvilLoggerTests.java index 992bebe57e561..2bc983e77283d 100644 --- a/qa/evil-tests/src/test/java/org/elasticsearch/common/logging/EvilLoggerTests.java +++ b/qa/evil-tests/src/test/java/org/elasticsearch/common/logging/EvilLoggerTests.java @@ -174,7 +174,7 @@ public void testConcurrentDeprecationLogger() throws IOException, BrokenBarrierE assertLogLine( deprecationEvents.get(i), DeprecationLogger.CRITICAL, - "org.elasticsearch.common.logging.DeprecationLogger.lambda\\$doPrivilegedLog\\$0", + "org.elasticsearch.common.logging.DeprecationLogger.logDeprecation", ".*This is a maybe logged deprecation message" + i + ".*" ); } @@ -207,7 +207,7 @@ public void testDeprecatedSettings() throws IOException { assertLogLine( deprecationEvents.get(0), DeprecationLogger.CRITICAL, - "org.elasticsearch.common.logging.DeprecationLogger.lambda\\$doPrivilegedLog\\$0", + "org.elasticsearch.common.logging.DeprecationLogger.logDeprecation", ".*\\[deprecated.foo\\] setting was deprecated in Elasticsearch and will be removed in a future release..*" ); } diff --git a/server/src/main/java/org/elasticsearch/bootstrap/ElasticsearchUncaughtExceptionHandler.java b/server/src/main/java/org/elasticsearch/bootstrap/ElasticsearchUncaughtExceptionHandler.java index b2c1bcb1d544a..20ba8a9dd5e8c 100644 --- a/server/src/main/java/org/elasticsearch/bootstrap/ElasticsearchUncaughtExceptionHandler.java +++ b/server/src/main/java/org/elasticsearch/bootstrap/ElasticsearchUncaughtExceptionHandler.java @@ -14,8 +14,6 @@ import org.elasticsearch.core.SuppressForbidden; import java.io.IOError; -import java.security.AccessController; -import java.security.PrivilegedAction; class ElasticsearchUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { private static final Logger logger = LogManager.getLogger(ElasticsearchUncaughtExceptionHandler.class); @@ -53,41 +51,17 @@ static boolean isFatalUncaught(Throwable e) { void onFatalUncaught(final String threadName, final Throwable t) { final String message = "fatal error in thread [" + threadName + "], exiting"; - logErrorMessage(t, message); + logger.error(message, t); } void onNonFatalUncaught(final String threadName, final Throwable t) { final String message = "uncaught exception in thread [" + threadName + "]"; - logErrorMessage(t, message); - } - - private static void logErrorMessage(Throwable t, String message) { - AccessController.doPrivileged((PrivilegedAction) () -> { - logger.error(message, t); - return null; - }); + logger.error(message, t); } + @SuppressForbidden(reason = "intentionally halting") void halt(int status) { - AccessController.doPrivileged(new PrivilegedHaltAction(status)); + // we halt to prevent shutdown hooks from running + Runtime.getRuntime().halt(status); } - - static class PrivilegedHaltAction implements PrivilegedAction { - - private final int status; - - private PrivilegedHaltAction(final int status) { - this.status = status; - } - - @SuppressForbidden(reason = "halt") - @Override - public Void run() { - // we halt to prevent shutdown hooks from running - Runtime.getRuntime().halt(status); - return null; - } - - } - } diff --git a/server/src/main/java/org/elasticsearch/common/blobstore/fs/FsBlobStore.java b/server/src/main/java/org/elasticsearch/common/blobstore/fs/FsBlobStore.java index 9a368483d46c0..938aa1ddbc9fc 100644 --- a/server/src/main/java/org/elasticsearch/common/blobstore/fs/FsBlobStore.java +++ b/server/src/main/java/org/elasticsearch/common/blobstore/fs/FsBlobStore.java @@ -18,8 +18,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Iterator; import java.util.List; @@ -57,14 +55,11 @@ public int bufferSizeInBytes() { public BlobContainer blobContainer(BlobPath path) { Path f = buildPath(path); if (readOnly == false) { - AccessController.doPrivileged((PrivilegedAction) () -> { - try { - Files.createDirectories(f); - } catch (IOException ex) { - throw new ElasticsearchException("failed to create blob container", ex); - } - return null; - }); + try { + Files.createDirectories(f); + } catch (IOException ex) { + throw new ElasticsearchException("failed to create blob container", ex); + } } return new FsBlobContainer(this, path, f); } diff --git a/server/src/main/java/org/elasticsearch/common/logging/DeprecationLogger.java b/server/src/main/java/org/elasticsearch/common/logging/DeprecationLogger.java index ef5b318a8b426..8f778f8c05209 100644 --- a/server/src/main/java/org/elasticsearch/common/logging/DeprecationLogger.java +++ b/server/src/main/java/org/elasticsearch/common/logging/DeprecationLogger.java @@ -15,8 +15,6 @@ import org.elasticsearch.common.regex.Regex; import org.elasticsearch.common.settings.Settings; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Collections; import java.util.List; @@ -119,18 +117,11 @@ private DeprecationLogger logDeprecation(Level level, DeprecationCategory catego String opaqueId = HeaderWarning.getXOpaqueId(); String productOrigin = HeaderWarning.getProductOrigin(); ESLogMessage deprecationMessage = DeprecatedMessage.of(category, key, opaqueId, productOrigin, msg, params); - doPrivilegedLog(level, deprecationMessage); + logger.log(level, deprecationMessage); } return this; } - private void doPrivilegedLog(Level level, ESLogMessage deprecationMessage) { - AccessController.doPrivileged((PrivilegedAction) () -> { - logger.log(level, deprecationMessage); - return null; - }); - } - /** * Used for handling previous version RestApiCompatible logic. * Logs a message at the {@link DeprecationLogger#CRITICAL} level diff --git a/server/src/main/java/org/elasticsearch/common/util/concurrent/EsExecutors.java b/server/src/main/java/org/elasticsearch/common/util/concurrent/EsExecutors.java index 28849a825bf25..4fd5225a29167 100644 --- a/server/src/main/java/org/elasticsearch/common/util/concurrent/EsExecutors.java +++ b/server/src/main/java/org/elasticsearch/common/util/concurrent/EsExecutors.java @@ -17,8 +17,6 @@ import org.elasticsearch.core.SuppressForbidden; import org.elasticsearch.node.Node; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.List; import java.util.Optional; import java.util.concurrent.AbstractExecutorService; @@ -393,11 +391,9 @@ static class EsThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { - return AccessController.doPrivileged((PrivilegedAction) () -> { - Thread t = new EsThread(group, r, namePrefix + "[T#" + threadNumber.getAndIncrement() + "]", 0, isSystem); - t.setDaemon(true); - return t; - }); + Thread t = new EsThread(group, r, namePrefix + "[T#" + threadNumber.getAndIncrement() + "]", 0, isSystem); + t.setDaemon(true); + return t; } } diff --git a/server/src/main/java/org/elasticsearch/index/codec/vectors/reflect/AssertingKnnVectorsReaderReflect.java b/server/src/main/java/org/elasticsearch/index/codec/vectors/reflect/AssertingKnnVectorsReaderReflect.java index bf47564c11b3a..b22fa88fb49b4 100644 --- a/server/src/main/java/org/elasticsearch/index/codec/vectors/reflect/AssertingKnnVectorsReaderReflect.java +++ b/server/src/main/java/org/elasticsearch/index/codec/vectors/reflect/AssertingKnnVectorsReaderReflect.java @@ -14,8 +14,6 @@ import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; -import java.security.AccessController; -import java.security.PrivilegedAction; /** * Reflective access to unwrap non-accessible delegate in AssertingKnnVectorsReader. @@ -52,25 +50,13 @@ private static MethodHandle getDelegateFieldHandle() { if (cls == null) { return MethodHandles.throwException(KnnVectorsReader.class, AssertionError.class); } - var lookup = privilegedPrivateLookupIn(cls, MethodHandles.lookup()); + var lookup = MethodHandles.privateLookupIn(cls, MethodHandles.lookup()); return lookup.findGetter(cls, "delegate", KnnVectorsReader.class); } catch (ReflectiveOperationException e) { throw new AssertionError(e); } } - @SuppressWarnings("removal") - static MethodHandles.Lookup privilegedPrivateLookupIn(Class cls, MethodHandles.Lookup lookup) throws IllegalAccessException { - PrivilegedAction pa = () -> { - try { - return MethodHandles.privateLookupIn(cls, lookup); - } catch (IllegalAccessException e) { - throw new AssertionError("should not happen, check opens", e); - } - }; - return AccessController.doPrivileged(pa); - } - static void handleThrowable(Throwable t) { if (t instanceof Error error) { throw error; diff --git a/server/src/main/java/org/elasticsearch/index/codec/vectors/reflect/OffHeapReflectionUtils.java b/server/src/main/java/org/elasticsearch/index/codec/vectors/reflect/OffHeapReflectionUtils.java index 599a205508385..49950bb4df4e9 100644 --- a/server/src/main/java/org/elasticsearch/index/codec/vectors/reflect/OffHeapReflectionUtils.java +++ b/server/src/main/java/org/elasticsearch/index/codec/vectors/reflect/OffHeapReflectionUtils.java @@ -26,8 +26,6 @@ import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.VarHandle; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Map; import static java.lang.invoke.MethodType.methodType; @@ -91,62 +89,62 @@ private OffHeapReflectionUtils() {} try { // Lucene99ScalarQuantizedVectorsReader var cls = Class.forName("org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsReader$FieldEntry"); - var lookup = privilegedPrivateLookupIn(L99_SQ_VR_CLS, MethodHandles.lookup()); + var lookup = MethodHandles.privateLookupIn(L99_SQ_VR_CLS, MethodHandles.lookup()); var mt = methodType(cls, String.class); GET_FIELD_ENTRY_HNDL_SQ = lookup.findVirtual(L99_SQ_VR_CLS, "getFieldEntry", mt); GET_VECTOR_DATA_LENGTH_HANDLE_SQ = lookup.findVirtual(cls, "vectorDataLength", methodType(long.class)); RAW_VECTORS_READER_HNDL_SQ = lookup.findVarHandle(L99_SQ_VR_CLS, "rawVectorsReader", FlatVectorsReader.class); // Lucene99FlatVectorsReader cls = Class.forName("org.apache.lucene.codecs.lucene99.Lucene99FlatVectorsReader$FieldEntry"); - lookup = privilegedPrivateLookupIn(L99_FLT_VR_CLS, MethodHandles.lookup()); + lookup = MethodHandles.privateLookupIn(L99_FLT_VR_CLS, MethodHandles.lookup()); mt = methodType(cls, String.class, VectorEncoding.class); GET_FIELD_ENTRY_HANDLE_L99FLT = lookup.findVirtual(L99_FLT_VR_CLS, "getFieldEntry", mt); VECTOR_DATA_LENGTH_HANDLE_L99FLT = lookup.findVirtual(cls, "vectorDataLength", methodType(long.class)); // DirectIOLucene99FlatVectorsReader cls = Class.forName("org.elasticsearch.index.codec.vectors.es818.DirectIOLucene99FlatVectorsReader$FieldEntry"); - lookup = privilegedPrivateLookupIn(DIOL99_FLT_VR_CLS, MethodHandles.lookup()); + lookup = MethodHandles.privateLookupIn(DIOL99_FLT_VR_CLS, MethodHandles.lookup()); mt = methodType(cls, String.class, VectorEncoding.class); GET_FIELD_ENTRY_HANDLE_DIOL99FLT = lookup.findVirtual(DIOL99_FLT_VR_CLS, "getFieldEntry", mt); VECTOR_DATA_LENGTH_HANDLE_DIOL99FLT = lookup.findVirtual(cls, "vectorDataLength", methodType(long.class)); // Lucene99HnswVectorsReader cls = Class.forName("org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsReader$FieldEntry"); - lookup = privilegedPrivateLookupIn(L99_HNSW_VR_CLS, MethodHandles.lookup()); + lookup = MethodHandles.privateLookupIn(L99_HNSW_VR_CLS, MethodHandles.lookup()); mt = methodType(cls, String.class, VectorEncoding.class); GET_FIELD_ENTRY_HANDLE_L99HNSW = lookup.findVirtual(L99_HNSW_VR_CLS, "getFieldEntry", mt); GET_VECTOR_INDEX_LENGTH_HANDLE_L99HNSW = lookup.findVirtual(cls, "vectorIndexLength", methodType(long.class)); - lookup = privilegedPrivateLookupIn(L99_HNSW_VR_CLS, MethodHandles.lookup()); + lookup = MethodHandles.privateLookupIn(L99_HNSW_VR_CLS, MethodHandles.lookup()); FLAT_VECTORS_READER_HNDL_L99HNSW = lookup.findVarHandle(L99_HNSW_VR_CLS, "flatVectorsReader", FlatVectorsReader.class); // Lucene90HnswVectorsReader cls = Class.forName("org.apache.lucene.backward_codecs.lucene90.Lucene90HnswVectorsReader$FieldEntry"); - lookup = privilegedPrivateLookupIn(L90_HNSW_VR_CLS, MethodHandles.lookup()); + lookup = MethodHandles.privateLookupIn(L90_HNSW_VR_CLS, MethodHandles.lookup()); mt = methodType(cls, String.class); GET_FIELD_ENTRY_HANDLE_L90HNSW = lookup.findVirtual(L90_HNSW_VR_CLS, "getFieldEntry", mt); GET_VECTOR_INDEX_LENGTH_HANDLE_L90HNSW = lookup.findVirtual(cls, "indexDataLength", methodType(long.class)); GET_VECTOR_DATA_LENGTH_HANDLE_L90HNSW = lookup.findVirtual(cls, "vectorDataLength", methodType(long.class)); // Lucene91HnswVectorsReader cls = Class.forName("org.apache.lucene.backward_codecs.lucene91.Lucene91HnswVectorsReader$FieldEntry"); - lookup = privilegedPrivateLookupIn(L91_HNSW_VR_CLS, MethodHandles.lookup()); + lookup = MethodHandles.privateLookupIn(L91_HNSW_VR_CLS, MethodHandles.lookup()); mt = methodType(cls, String.class); GET_FIELD_ENTRY_HANDLE_L91HNSW = lookup.findVirtual(L91_HNSW_VR_CLS, "getFieldEntry", mt); GET_VECTOR_INDEX_LENGTH_HANDLE_L91HNSW = lookup.findVirtual(cls, "vectorIndexLength", methodType(long.class)); GET_VECTOR_DATA_LENGTH_HANDLE_L91HNSW = lookup.findVirtual(cls, "vectorDataLength", methodType(long.class)); // Lucene92HnswVectorsReader cls = Class.forName("org.apache.lucene.backward_codecs.lucene92.Lucene92HnswVectorsReader$FieldEntry"); - lookup = privilegedPrivateLookupIn(L92_HNSW_VR_CLS, MethodHandles.lookup()); + lookup = MethodHandles.privateLookupIn(L92_HNSW_VR_CLS, MethodHandles.lookup()); mt = methodType(cls, String.class); GET_FIELD_ENTRY_HANDLE_L92HNSW = lookup.findVirtual(L92_HNSW_VR_CLS, "getFieldEntry", mt); GET_VECTOR_INDEX_LENGTH_HANDLE_L92HNSW = lookup.findVirtual(cls, "vectorIndexLength", methodType(long.class)); GET_VECTOR_DATA_LENGTH_HANDLE_L92HNSW = lookup.findVirtual(cls, "vectorDataLength", methodType(long.class)); // Lucene94HnswVectorsReader cls = Class.forName("org.apache.lucene.backward_codecs.lucene94.Lucene94HnswVectorsReader$FieldEntry"); - lookup = privilegedPrivateLookupIn(L94_HNSW_VR_CLS, MethodHandles.lookup()); + lookup = MethodHandles.privateLookupIn(L94_HNSW_VR_CLS, MethodHandles.lookup()); mt = methodType(cls, String.class, VectorEncoding.class); GET_FIELD_ENTRY_HANDLE_L94HNSW = lookup.findVirtual(L94_HNSW_VR_CLS, "getFieldEntry", mt); GET_VECTOR_INDEX_LENGTH_HANDLE_L94HNSW = lookup.findVirtual(cls, "vectorIndexLength", methodType(long.class)); GET_VECTOR_DATA_LENGTH_HANDLE_L94HNSW = lookup.findVirtual(cls, "vectorDataLength", methodType(long.class)); // Lucene95HnswVectorsReader cls = Class.forName("org.apache.lucene.backward_codecs.lucene95.Lucene95HnswVectorsReader$FieldEntry"); - lookup = privilegedPrivateLookupIn(L95_HNSW_VR_CLS, MethodHandles.lookup()); + lookup = MethodHandles.privateLookupIn(L95_HNSW_VR_CLS, MethodHandles.lookup()); mt = methodType(cls, String.class, VectorEncoding.class); GET_FIELD_ENTRY_HANDLE_L95HNSW = lookup.findVirtual(L95_HNSW_VR_CLS, "getFieldEntry", mt); GET_VECTOR_INDEX_LENGTH_HANDLE_L95HNSW = lookup.findVirtual(cls, "vectorIndexLength", methodType(long.class)); @@ -278,18 +276,6 @@ static Map getOffHeapByteSizeL95HNSW(Lucene95HnswVectorsReader rea throw new AssertionError("should not reach here"); } - @SuppressWarnings("removal") - private static MethodHandles.Lookup privilegedPrivateLookupIn(Class cls, MethodHandles.Lookup lookup) { - PrivilegedAction pa = () -> { - try { - return MethodHandles.privateLookupIn(cls, lookup); - } catch (IllegalAccessException e) { - throw new AssertionError("should not happen, check opens", e); - } - }; - return AccessController.doPrivileged(pa); - } - private static void handleThrowable(Throwable t) { if (t instanceof Error error) { throw error; diff --git a/server/src/main/java/org/elasticsearch/plugins/ExtendedPluginsClassLoader.java b/server/src/main/java/org/elasticsearch/plugins/ExtendedPluginsClassLoader.java index d9bf0d653bb62..7a78b9fbe7500 100644 --- a/server/src/main/java/org/elasticsearch/plugins/ExtendedPluginsClassLoader.java +++ b/server/src/main/java/org/elasticsearch/plugins/ExtendedPluginsClassLoader.java @@ -9,8 +9,6 @@ package org.elasticsearch.plugins; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Collections; import java.util.List; @@ -43,8 +41,6 @@ protected Class findClass(String name) throws ClassNotFoundException { * Return a new classloader across the parent and extended loaders. */ public static ExtendedPluginsClassLoader create(ClassLoader parent, List extendedLoaders) { - return AccessController.doPrivileged( - (PrivilegedAction) () -> new ExtendedPluginsClassLoader(parent, extendedLoaders) - ); + return new ExtendedPluginsClassLoader(parent, extendedLoaders); } } diff --git a/server/src/main/java/org/elasticsearch/plugins/PluginsLoader.java b/server/src/main/java/org/elasticsearch/plugins/PluginsLoader.java index ac920d73fc666..c30cc28d2f6fa 100644 --- a/server/src/main/java/org/elasticsearch/plugins/PluginsLoader.java +++ b/server/src/main/java/org/elasticsearch/plugins/PluginsLoader.java @@ -27,8 +27,6 @@ import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Path; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -423,7 +421,7 @@ static LayerAndLoader createModuleLayer( finder, Set.of(moduleName) ); - var controller = privilegedDefineModulesWithOneLoader(configuration, parentLayersOrBoot(parentLayers), parentLoader); + var controller = ModuleLayer.defineModulesWithOneLoader(configuration, parentLayersOrBoot(parentLayers), parentLoader); var pluginModule = controller.layer().findModule(moduleName).get(); ensureEntryPointAccessible(controller, pluginModule, className); // export/open upstream modules to this plugin module @@ -432,7 +430,7 @@ static LayerAndLoader createModuleLayer( addPluginExportsServices(qualifiedExports, controller); enableNativeAccess(moduleName, modulesWithNativeAccess, controller); logger.debug(() -> "Loading bundle: created module layer and loader for module " + moduleName); - return new LayerAndLoader(controller.layer(), privilegedFindLoader(controller.layer(), moduleName)); + return new LayerAndLoader(controller.layer(), controller.layer().findLoader(moduleName)); } /** Determines the module name of the SPI module, given its URL. */ @@ -490,18 +488,6 @@ private static void ensureEntryPointAccessible(Controller controller, Module plu } } - @SuppressWarnings("removal") - static Controller privilegedDefineModulesWithOneLoader(Configuration cf, List parentLayers, ClassLoader parentLoader) { - return AccessController.doPrivileged( - (PrivilegedAction) () -> ModuleLayer.defineModulesWithOneLoader(cf, parentLayers, parentLoader) - ); - } - - @SuppressWarnings("removal") - static ClassLoader privilegedFindLoader(ModuleLayer layer, String name) { - return AccessController.doPrivileged((PrivilegedAction) () -> layer.findLoader(name)); - } - private static List parentLayersOrBoot(List parentLayers) { if (parentLayers == null || parentLayers.isEmpty()) { return List.of(ModuleLayer.boot()); diff --git a/server/src/main/java/org/elasticsearch/plugins/PluginsService.java b/server/src/main/java/org/elasticsearch/plugins/PluginsService.java index 6ef3cd17ba2e9..78a8650a5e920 100644 --- a/server/src/main/java/org/elasticsearch/plugins/PluginsService.java +++ b/server/src/main/java/org/elasticsearch/plugins/PluginsService.java @@ -32,8 +32,6 @@ import java.io.IOException; import java.lang.reflect.Constructor; import java.nio.file.Path; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -395,7 +393,7 @@ private void loadBundle(PluginLayer pluginLayer, Map loade // Set context class loader to plugin's class loader so that plugins // that have dependencies with their own SPI endpoints have a chance to load // and initialize them appropriately. - privilegedSetContextClassLoader(pluginLayer.pluginClassLoader()); + Thread.currentThread().setContextClassLoader(pluginLayer.pluginClassLoader()); Plugin plugin; if (pluginBundle.pluginDescriptor().isStable()) { @@ -428,7 +426,7 @@ We need to pass a name though so that we can show that a plugin was loaded (via } loadedPlugins.put(name, new LoadedPlugin(pluginBundle.plugin, plugin, pluginLayer.pluginClassLoader())); } finally { - privilegedSetContextClassLoader(cl); + Thread.currentThread().setContextClassLoader(cl); } } @@ -537,12 +535,4 @@ private static String signatureMessage(final Class clazz) { public final Stream filterPlugins(Class type) { return plugins().stream().filter(x -> type.isAssignableFrom(x.instance().getClass())).map(p -> ((T) p.instance())); } - - @SuppressWarnings("removal") - private static void privilegedSetContextClassLoader(ClassLoader loader) { - AccessController.doPrivileged((PrivilegedAction) () -> { - Thread.currentThread().setContextClassLoader(loader); - return null; - }); - } } diff --git a/server/src/main/java/org/elasticsearch/plugins/UberModuleClassLoader.java b/server/src/main/java/org/elasticsearch/plugins/UberModuleClassLoader.java index 5e63f2e0b9aa9..c47fac279f7e1 100644 --- a/server/src/main/java/org/elasticsearch/plugins/UberModuleClassLoader.java +++ b/server/src/main/java/org/elasticsearch/plugins/UberModuleClassLoader.java @@ -23,10 +23,8 @@ import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Path; -import java.security.AccessController; import java.security.CodeSigner; import java.security.CodeSource; -import java.security.PrivilegedAction; import java.security.SecureClassLoader; import java.util.Enumeration; import java.util.List; @@ -119,7 +117,7 @@ static UberModuleClassLoader getInstance( Set packageNames = finder.find(moduleName).map(ModuleReference::descriptor).map(ModuleDescriptor::packages).orElseThrow(); - PrivilegedAction pa = () -> new UberModuleClassLoader( + return new UberModuleClassLoader( parent, moduleName, jarUrls.toArray(new URL[0]), @@ -128,7 +126,6 @@ static UberModuleClassLoader getInstance( packageNames, modulesWithNativeAccess ); - return AccessController.doPrivileged(pa); } private static boolean isPackageInLayers(String packageName, ModuleLayer moduleLayer) { @@ -312,17 +309,12 @@ static Path urlToPathUnchecked(URL url) { } @Override - @SuppressWarnings("removal") public void close() throws Exception { - PrivilegedAction pa = () -> { - try { - internalLoader.close(); - } catch (IOException e) { - throw new IllegalStateException("Could not close internal URLClassLoader"); - } - return null; - }; - AccessController.doPrivileged(pa); + try { + internalLoader.close(); + } catch (IOException e) { + throw new IllegalStateException("Could not close internal URLClassLoader"); + } } // visible for testing diff --git a/server/src/main/java/org/elasticsearch/readiness/ReadinessService.java b/server/src/main/java/org/elasticsearch/readiness/ReadinessService.java index 1a169699d4131..165bcebb80a5d 100644 --- a/server/src/main/java/org/elasticsearch/readiness/ReadinessService.java +++ b/server/src/main/java/org/elasticsearch/readiness/ReadinessService.java @@ -32,8 +32,6 @@ import java.net.InetSocketAddress; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Collection; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; @@ -122,25 +120,20 @@ ServerSocketChannel setupSocket() { int portNumber = PORT.get(settings); assert portNumber >= 0; - var socketAddress = AccessController.doPrivileged((PrivilegedAction) () -> { - try { - return socketAddress(InetAddress.getByName("0"), portNumber); - } catch (IOException e) { - throw new IllegalArgumentException("Failed to resolve readiness host address", e); - } - }); + InetSocketAddress socketAddress; + try { + socketAddress = socketAddress(InetAddress.getByName("0"), portNumber); + } catch (IOException e) { + throw new IllegalArgumentException("Failed to resolve readiness host address", e); + } try { serverChannel = socketChannelFactory.get(); - - AccessController.doPrivileged((PrivilegedAction) () -> { - try { - serverChannel.bind(socketAddress); - } catch (IOException e) { - throw new BindTransportException("Failed to bind to " + NetworkAddress.format(socketAddress), e); - } - return null; - }); + try { + serverChannel.bind(socketAddress); + } catch (IOException e) { + throw new BindTransportException("Failed to bind to " + NetworkAddress.format(socketAddress), e); + } // First time bounding the socket, we notify any listeners if (boundSocket.get() == null) { @@ -180,14 +173,11 @@ synchronized void startListener() { assert serverChannel != null; try { while (serverChannel.isOpen()) { - AccessController.doPrivileged((PrivilegedAction) () -> { - try (SocketChannel channel = serverChannel.accept()) {} catch (IOException e) { - logger.debug("encountered exception while responding to readiness check request", e); - } catch (Exception other) { - logger.warn("encountered unknown exception while responding to readiness check request", other); - } - return null; - }); + try (SocketChannel channel = serverChannel.accept()) {} catch (IOException e) { + logger.debug("encountered exception while responding to readiness check request", e); + } catch (Exception other) { + logger.warn("encountered unknown exception while responding to readiness check request", other); + } } } finally { listenerThreadLatch.countDown(); diff --git a/server/src/main/java/org/elasticsearch/search/lookup/LeafDocLookup.java b/server/src/main/java/org/elasticsearch/search/lookup/LeafDocLookup.java index 4eaf5c4bb077f..00fc07043baf5 100644 --- a/server/src/main/java/org/elasticsearch/search/lookup/LeafDocLookup.java +++ b/server/src/main/java/org/elasticsearch/search/lookup/LeafDocLookup.java @@ -19,8 +19,6 @@ import org.elasticsearch.script.field.Field; import java.io.IOException; -import java.security.AccessController; -import java.security.PrivilegedAction; import java.util.Collection; import java.util.Map; import java.util.Set; @@ -42,23 +40,18 @@ Field factories require a privileged action to advance to docids (files could be */ class FieldFactoryWrapper { final DocValuesScriptFieldFactory factory; - private final PrivilegedAction advancer; FieldFactoryWrapper(DocValuesScriptFieldFactory factory) { this.factory = factory; - this.advancer = () -> { - try { - factory.setNextDocId(docId); - } catch (IOException ioe) { - throw ExceptionsHelper.convertToElastic(ioe); - } - return null; - }; } // advances the factory to the current docid for the enclosing LeafDocLookup void advanceToDoc() { - AccessController.doPrivileged(this.advancer); + try { + factory.setNextDocId(docId); + } catch (IOException ioe) { + throw ExceptionsHelper.convertToElastic(ioe); + } } } @@ -101,30 +94,26 @@ private FieldFactoryWrapper getFactoryForField(String fieldName) { throw new IllegalArgumentException("No field found for [" + fieldName + "] in mapping"); } - // Load the field data on behalf of the script. Otherwise, it would require - // additional permissions to deal with pagedbytes/ramusagestimator/etc. - return AccessController.doPrivileged((PrivilegedAction) () -> { - IndexFieldData indexFieldData = fieldDataLookup.apply(fieldType, SCRIPT); + IndexFieldData indexFieldData = fieldDataLookup.apply(fieldType, SCRIPT); - FieldFactoryWrapper docFactory = null; + FieldFactoryWrapper docFactory = null; - if (docFactoryCache.isEmpty() == false) { - docFactory = docFactoryCache.get(fieldName); - } + if (docFactoryCache.isEmpty() == false) { + docFactory = docFactoryCache.get(fieldName); + } - // if this field has already been accessed via the doc-access API and the field-access API - // uses doc values then we share to avoid double-loading - FieldFactoryWrapper fieldFactory; - if (docFactory != null && indexFieldData instanceof SourceValueFetcherIndexFieldData == false) { - fieldFactory = docFactory; - } else { - fieldFactory = new FieldFactoryWrapper(indexFieldData.load(reader).getScriptFieldFactory(fieldName)); - } + // if this field has already been accessed via the doc-access API and the field-access API + // uses doc values then we share to avoid double-loading + FieldFactoryWrapper fieldFactory; + if (docFactory != null && indexFieldData instanceof SourceValueFetcherIndexFieldData == false) { + fieldFactory = docFactory; + } else { + fieldFactory = new FieldFactoryWrapper(indexFieldData.load(reader).getScriptFieldFactory(fieldName)); + } - fieldFactoryCache.put(fieldName, fieldFactory); + fieldFactoryCache.put(fieldName, fieldFactory); - return fieldFactory; - }); + return fieldFactory; } public Field getScriptField(String fieldName) { @@ -146,35 +135,31 @@ private FieldFactoryWrapper getFactoryForDoc(String fieldName) { throw new IllegalArgumentException("No field found for [" + fieldName + "] in mapping"); } - // Load the field data on behalf of the script. Otherwise, it would require - // additional permissions to deal with pagedbytes/ramusagestimator/etc. - return AccessController.doPrivileged((PrivilegedAction) () -> { - FieldFactoryWrapper docFactory = null; - FieldFactoryWrapper fieldFactory = null; + FieldFactoryWrapper docFactory = null; + FieldFactoryWrapper fieldFactory = null; - if (fieldFactoryCache.isEmpty() == false) { - fieldFactory = fieldFactoryCache.get(fieldName); - } + if (fieldFactoryCache.isEmpty() == false) { + fieldFactory = fieldFactoryCache.get(fieldName); + } - if (fieldFactory != null) { - IndexFieldData fieldIndexFieldData = fieldDataLookup.apply(fieldType, SCRIPT); + if (fieldFactory != null) { + IndexFieldData fieldIndexFieldData = fieldDataLookup.apply(fieldType, SCRIPT); - // if this field has already been accessed via the field-access API and the field-access API - // uses doc values then we share to avoid double-loading - if (fieldIndexFieldData instanceof SourceValueFetcherIndexFieldData == false) { - docFactory = fieldFactory; - } + // if this field has already been accessed via the field-access API and the field-access API + // uses doc values then we share to avoid double-loading + if (fieldIndexFieldData instanceof SourceValueFetcherIndexFieldData == false) { + docFactory = fieldFactory; } + } - if (docFactory == null) { - IndexFieldData indexFieldData = fieldDataLookup.apply(fieldType, SEARCH); - docFactory = new FieldFactoryWrapper(indexFieldData.load(reader).getScriptFieldFactory(fieldName)); - } + if (docFactory == null) { + IndexFieldData indexFieldData = fieldDataLookup.apply(fieldType, SEARCH); + docFactory = new FieldFactoryWrapper(indexFieldData.load(reader).getScriptFieldFactory(fieldName)); + } - docFactoryCache.put(fieldName, docFactory); + docFactoryCache.put(fieldName, docFactory); - return docFactory; - }); + return docFactory; } @Override diff --git a/server/src/test/java/org/elasticsearch/common/logging/DeprecationLoggerTests.java b/server/src/test/java/org/elasticsearch/common/logging/DeprecationLoggerTests.java index 52439f4b59447..d891b0bb41198 100644 --- a/server/src/test/java/org/elasticsearch/common/logging/DeprecationLoggerTests.java +++ b/server/src/test/java/org/elasticsearch/common/logging/DeprecationLoggerTests.java @@ -17,11 +17,6 @@ import org.elasticsearch.test.ESTestCase; import org.mockito.Mockito; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.Permissions; -import java.security.PrivilegedAction; -import java.security.ProtectionDomain; import java.util.concurrent.atomic.AtomicBoolean; import static org.hamcrest.Matchers.equalTo; @@ -75,13 +70,7 @@ public void testLogPermissions() { DeprecationLogger deprecationLogger = DeprecationLogger.getLogger("name"); - AccessControlContext noPermissionsAcc = new AccessControlContext( - new ProtectionDomain[] { new ProtectionDomain(null, new Permissions()) } - ); - AccessController.doPrivileged((PrivilegedAction) () -> { - deprecationLogger.warn(DeprecationCategory.API, "key", "foo", "bar"); - return null; - }, noPermissionsAcc); + deprecationLogger.warn(DeprecationCategory.API, "key", "foo", "bar"); assertThat("supplier called", supplierCalled.get(), is(true)); } finally { LogManager.setFactory(originalFactory); diff --git a/server/src/test/java/org/elasticsearch/search/lookup/LeafDocLookupTests.java b/server/src/test/java/org/elasticsearch/search/lookup/LeafDocLookupTests.java index 6ddffbef37f7d..895206b551250 100644 --- a/server/src/test/java/org/elasticsearch/search/lookup/LeafDocLookupTests.java +++ b/server/src/test/java/org/elasticsearch/search/lookup/LeafDocLookupTests.java @@ -24,10 +24,6 @@ import org.junit.Before; import java.io.IOException; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.ProtectionDomain; import java.util.Map; import java.util.function.BiFunction; import java.util.function.Consumer; @@ -427,12 +423,7 @@ public void testParallelCache() { public void testLookupPrivilegesAdvanceDoc() { nextDocCallback = i -> SpecialPermission.check(); - // mimic the untrusted codebase, which gets no permissions - var restrictedContext = new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, null) }); - AccessController.doPrivileged((PrivilegedAction) () -> { - ScriptDocValues fetchedDocValues = docLookup.get("field"); - assertEquals(docValues, fetchedDocValues); - return null; - }, restrictedContext); + ScriptDocValues fetchedDocValues = docLookup.get("field"); + assertEquals(docValues, fetchedDocValues); } } diff --git a/server/src/test/java/org/elasticsearch/transport/TransportHandshakerRawMessageTests.java b/server/src/test/java/org/elasticsearch/transport/TransportHandshakerRawMessageTests.java index 89e929d7029f6..58ca2cbab9530 100644 --- a/server/src/test/java/org/elasticsearch/transport/TransportHandshakerRawMessageTests.java +++ b/server/src/test/java/org/elasticsearch/transport/TransportHandshakerRawMessageTests.java @@ -27,8 +27,6 @@ import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.StandardCharsets; -import java.security.AccessController; -import java.security.PrivilegedExceptionAction; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.greaterThan; @@ -193,8 +191,6 @@ public void testOutboundHandshake() throws Exception { private Socket openTransportConnection() throws Exception { final var transportAddress = randomFrom(getInstanceFromNode(TransportService.class).boundAddress().boundAddresses()).address(); - return AccessController.doPrivileged( - (PrivilegedExceptionAction) (() -> new Socket(transportAddress.getAddress(), transportAddress.getPort())) - ); + return new Socket(transportAddress.getAddress(), transportAddress.getPort()); } }