8344235: Revisit SecurityManager usage in java.logging after JEP 486 and JEP 491 integration

Reviewed-by: jpai
This commit is contained in:
Daniel Fuchs 2024-11-21 11:54:28 +00:00
parent 18df6fd5ba
commit a62279ca0a
17 changed files with 202 additions and 903 deletions

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -25,9 +25,6 @@
package jdk.internal.logger;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@ -131,15 +128,8 @@ public final class BootstrapLogger implements Logger, PlatformLogger.Bridge,
@Override
public Thread newThread(Runnable r) {
ExecutorService owner = getExecutor();
@SuppressWarnings("removal")
Thread thread = AccessController.doPrivileged(new PrivilegedAction<Thread>() {
@Override
public Thread run() {
Thread t = InnocuousThread.newThread(new BootstrapMessageLoggerTask(owner, r));
t.setName("BootstrapMessageLoggerTask-"+t.getName());
return t;
}
}, null, new RuntimePermission("enableContextClassLoaderOverride"));
Thread thread = InnocuousThread.newThread(new BootstrapMessageLoggerTask(owner, r));
thread.setName("BootstrapMessageLoggerTask-" + thread.getName());
thread.setDaemon(true);
return thread;
}
@ -269,8 +259,6 @@ public final class BootstrapLogger implements Logger, PlatformLogger.Bridge,
// the parameters etc... we need to store the context of the
// caller who logged the message - so that we can reuse it when
// we finally log the message.
@SuppressWarnings("removal")
final AccessControlContext acc;
// The next event in the queue
LogEvent next;
@ -279,7 +267,6 @@ public final class BootstrapLogger implements Logger, PlatformLogger.Bridge,
private LogEvent(BootstrapLogger bootstrap, Level level,
ResourceBundle bundle, String msg,
Throwable thrown, Object[] params) {
this.acc = AccessController.getContext();
this.timeMillis = System.currentTimeMillis();
this.nanoAdjustment = VM.getNanoTimeAdjustment(timeMillis);
this.level = level;
@ -298,7 +285,6 @@ public final class BootstrapLogger implements Logger, PlatformLogger.Bridge,
private LogEvent(BootstrapLogger bootstrap, Level level,
Supplier<String> msgSupplier,
Throwable thrown, Object[] params) {
this.acc = AccessController.getContext();
this.timeMillis = System.currentTimeMillis();
this.nanoAdjustment = VM.getNanoTimeAdjustment(timeMillis);
this.level = level;
@ -319,7 +305,6 @@ public final class BootstrapLogger implements Logger, PlatformLogger.Bridge,
String sourceClass, String sourceMethod,
ResourceBundle bundle, String msg,
Throwable thrown, Object[] params) {
this.acc = AccessController.getContext();
this.timeMillis = System.currentTimeMillis();
this.nanoAdjustment = VM.getNanoTimeAdjustment(timeMillis);
this.level = null;
@ -340,7 +325,6 @@ public final class BootstrapLogger implements Logger, PlatformLogger.Bridge,
String sourceClass, String sourceMethod,
Supplier<String> msgSupplier,
Throwable thrown, Object[] params) {
this.acc = AccessController.getContext();
this.timeMillis = System.currentTimeMillis();
this.nanoAdjustment = VM.getNanoTimeAdjustment(timeMillis);
this.level = null;
@ -444,20 +428,12 @@ public final class BootstrapLogger implements Logger, PlatformLogger.Bridge,
Objects.requireNonNull(level),
Objects.requireNonNull(msgSupplier), null, null);
}
@SuppressWarnings("removal")
static void log(LogEvent log, Logger logger) {
final SecurityManager sm = System.getSecurityManager();
// not sure we can actually use lambda here. We may need to create
// an anonymous class. Although if we reach here, then it means
// the VM is booted.
if (sm == null || log.acc == null) {
BootstrapExecutors.submit(() -> log.log(logger));
} else {
BootstrapExecutors.submit(() ->
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
log.log(logger); return null;
}, log.acc));
}
BootstrapExecutors.submit(() -> log.log(logger));
}
// non default methods from PlatformLogger.Bridge interface
@ -510,20 +486,9 @@ public final class BootstrapLogger implements Logger, PlatformLogger.Bridge,
Objects.requireNonNull(level), sourceClass,
sourceMethod, msgSupplier, thrown, null);
}
@SuppressWarnings("removal")
static void log(LogEvent log, PlatformLogger.Bridge logger) {
final SecurityManager sm = System.getSecurityManager();
if (sm == null || log.acc == null) {
BootstrapExecutors.submit(() -> log.log(logger));
} else {
// not sure we can actually use lambda here. We may need to create
// an anonymous class. Although if we reach here, then it means
// the VM is booted.
BootstrapExecutors.submit(() ->
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
log.log(logger); return null;
}, log.acc));
}
BootstrapExecutors.submit(() -> log.log(logger));
}
static void log(LogEvent event) {
@ -897,37 +862,32 @@ public final class BootstrapLogger implements Logger, PlatformLogger.Bridge,
// We do not want this field to get initialized if VM.isBooted() is false.
@SuppressWarnings("removal")
private static final class DetectBackend {
static final LoggingBackend detectedBackend;
static {
detectedBackend = AccessController.doPrivileged(new PrivilegedAction<LoggingBackend>() {
@Override
public LoggingBackend run() {
final Iterator<LoggerFinder> iterator =
ServiceLoader.load(LoggerFinder.class, ClassLoader.getSystemClassLoader())
.iterator();
if (iterator.hasNext()) {
return LoggingBackend.CUSTOM; // Custom Logger Provider is registered
}
// No custom logger provider: we will be using the default
// backend.
final Iterator<DefaultLoggerFinder> iterator2 =
ServiceLoader.loadInstalled(DefaultLoggerFinder.class)
.iterator();
if (iterator2.hasNext()) {
// LoggingProviderImpl is registered. The default
// implementation is java.util.logging
String cname = System.getProperty("java.util.logging.config.class");
String fname = System.getProperty("java.util.logging.config.file");
return (cname != null || fname != null)
? LoggingBackend.JUL_WITH_CONFIG
: LoggingBackend.JUL_DEFAULT;
} else {
// SimpleConsoleLogger is used
return LoggingBackend.NONE;
}
}
});
static final LoggingBackend detectedBackend = detectBackend();
static LoggingBackend detectBackend() {
final Iterator<LoggerFinder> iterator =
ServiceLoader.load(LoggerFinder.class, ClassLoader.getSystemClassLoader())
.iterator();
if (iterator.hasNext()) {
return LoggingBackend.CUSTOM; // Custom Logger Provider is registered
}
// No custom logger provider: we will be using the default
// backend.
final Iterator<DefaultLoggerFinder> iterator2 =
ServiceLoader.loadInstalled(DefaultLoggerFinder.class)
.iterator();
if (iterator2.hasNext()) {
// LoggingProviderImpl is registered. The default
// implementation is java.util.logging
String cname = System.getProperty("java.util.logging.config.class");
String fname = System.getProperty("java.util.logging.config.file");
return (cname != null || fname != null)
? LoggingBackend.JUL_WITH_CONFIG
: LoggingBackend.JUL_DEFAULT;
} else {
// SimpleConsoleLogger is used
return LoggingBackend.NONE;
}
}
}

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -36,8 +36,6 @@ import java.util.Objects;
import java.lang.System.LoggerFinder;
import java.lang.System.Logger;
import java.lang.ref.ReferenceQueue;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collection;
import java.util.ResourceBundle;
@ -70,7 +68,7 @@ import java.util.ResourceBundle;
* that provides the necessary configuration.
*
* @apiNote Programmers are not expected to call this class directly.
* Instead they should rely on the static methods defined by {@link
* Instead, they should rely on the static methods defined by {@link
* java.lang.System java.lang.System} or {@link sun.util.logging.PlatformLogger
* sun.util.logging.PlatformLogger}.
*
@ -81,30 +79,12 @@ import java.util.ResourceBundle;
*/
public class DefaultLoggerFinder extends LoggerFinder {
static final RuntimePermission LOGGERFINDER_PERMISSION =
new RuntimePermission("loggerFinder");
/**
* Creates a new instance of DefaultLoggerFinder.
* @throws SecurityException if the calling code does not have the
* {@code RuntimePermission("loggerFinder")}
*/
protected DefaultLoggerFinder() {
this(checkPermission());
}
private DefaultLoggerFinder(Void unused) {
// nothing to do.
}
private static Void checkPermission() {
@SuppressWarnings("removal")
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(LOGGERFINDER_PERMISSION);
}
return null;
}
// SharedLoggers is a default cache of loggers used when JUL is not
// present - in that case we use instances of SimpleConsoleLogger which
@ -139,23 +119,14 @@ public class DefaultLoggerFinder extends LoggerFinder {
static final SharedLoggers application = new SharedLoggers();
}
@SuppressWarnings("removal")
public static boolean isSystem(Module m) {
return AccessController.doPrivileged(new PrivilegedAction<>() {
@Override
public Boolean run() {
// returns true if moduleCL is the platform class loader
// or one of its ancestors.
return VM.isSystemDomainLoader(m.getClassLoader());
}
});
return VM.isSystemDomainLoader(m.getClassLoader());
}
@Override
public final Logger getLogger(String name, Module module) {
Objects.requireNonNull(name, "name");
Objects.requireNonNull(module, "module");
checkPermission();
return demandLoggerFor(name, module);
}
@ -176,11 +147,8 @@ public class DefaultLoggerFinder extends LoggerFinder {
* @param name The name of the logger.
* @param module The module on behalf of which the logger is created.
* @return A {@link Logger logger} suitable for the application usage.
* @throws SecurityException if the calling code does not have the
* {@code RuntimePermission("loggerFinder")}.
*/
protected Logger demandLoggerFor(String name, Module module) {
checkPermission();
if (isSystem(module)) {
return SharedLoggers.system.get(SimpleConsoleLogger::makeSimpleLogger, name);
} else {

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -25,8 +25,6 @@
package jdk.internal.logger;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.function.BiFunction;
import java.lang.System.LoggerFinder;
import java.lang.System.Logger;
@ -44,9 +42,6 @@ import sun.util.logging.PlatformLogger;
*/
public final class LazyLoggers {
static final RuntimePermission LOGGERFINDER_PERMISSION =
new RuntimePermission("loggerFinder");
private LazyLoggers() {
throw new InternalError();
}
@ -341,7 +336,6 @@ public final class LazyLoggers {
// Do not expose this outside of this package.
private static volatile LoggerFinder provider;
@SuppressWarnings("removal")
private static LoggerFinder accessLoggerFinder() {
LoggerFinder prov = provider;
if (prov == null) {
@ -350,10 +344,7 @@ public final class LazyLoggers {
// the result.
// This is just an optimization to avoid the cost of calling
// doPrivileged every time.
final SecurityManager sm = System.getSecurityManager();
prov = sm == null ? LoggerFinder.getLoggerFinder() :
AccessController.doPrivileged(
(PrivilegedAction<LoggerFinder>)LoggerFinder::getLoggerFinder);
prov = LoggerFinder.getLoggerFinder();
if (prov instanceof TemporaryLoggerFinder) return prov;
provider = prov;
}
@ -403,17 +394,9 @@ public final class LazyLoggers {
* @param module module on behalf of which the logger is created
* @return The logger returned by the LoggerFinder.
*/
@SuppressWarnings("removal")
static Logger getLoggerFromFinder(String name, Module module) {
final SecurityManager sm = System.getSecurityManager();
if (sm == null) {
return accessLoggerFinder().getLogger(name, module);
} else {
return AccessController.doPrivileged((PrivilegedAction<Logger>)
() -> {return accessLoggerFinder().getLogger(name, module);},
null, LOGGERFINDER_PERMISSION);
}
}
return accessLoggerFinder().getLogger(name, module);
}
/**
* Returns a (possibly lazy) Logger for the caller.

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -24,12 +24,8 @@
*/
package jdk.internal.logger;
import java.io.FilePermission;
import java.lang.System.Logger;
import java.lang.System.LoggerFinder;
import java.security.AccessController;
import java.security.Permission;
import java.security.PrivilegedAction;
import java.util.Iterator;
import java.util.Locale;
import java.util.ServiceConfigurationError;
@ -37,9 +33,6 @@ import java.util.ServiceLoader;
import java.util.function.BooleanSupplier;
import jdk.internal.vm.annotation.Stable;
import sun.security.util.SecurityConstants;
import sun.security.action.GetBooleanAction;
import sun.security.action.GetPropertyAction;
/**
* Helper class used to load the {@link java.lang.System.LoggerFinder}.
@ -47,13 +40,6 @@ import sun.security.action.GetPropertyAction;
public final class LoggerFinderLoader {
private static volatile System.LoggerFinder service;
private static final Object lock = new int[0];
static final Permission CLASSLOADER_PERMISSION =
SecurityConstants.GET_CLASSLOADER_PERMISSION;
static final Permission READ_PERMISSION =
new FilePermission("<<ALL FILES>>",
SecurityConstants.FILE_READ_ACTION);
public static final RuntimePermission LOGGERFINDER_PERMISSION =
new RuntimePermission("loggerFinder");
// This is used to control how the LoggerFinderLoader handles
// errors when instantiating the LoggerFinder provider.
@ -63,7 +49,7 @@ public final class LoggerFinderLoader {
// DEBUG => Do not fail, use plain default (simple logger) implementation,
// prints warning and exception stack trace on console.
// QUIET => Do not fail and stay silent.
private static enum ErrorPolicy { ERROR, WARNING, DEBUG, QUIET };
private static enum ErrorPolicy { ERROR, WARNING, DEBUG, QUIET }
// This class is static and cannot be instantiated.
private LoggerFinderLoader() {
@ -107,8 +93,7 @@ public final class LoggerFinderLoader {
// Get configuration error policy
private static ErrorPolicy configurationErrorPolicy() {
String errorPolicy =
GetPropertyAction.privilegedGetProperty("jdk.logger.finder.error");
String errorPolicy = System.getProperty("jdk.logger.finder.error");
if (errorPolicy == null || errorPolicy.isEmpty()) {
return ErrorPolicy.WARNING;
}
@ -122,25 +107,12 @@ public final class LoggerFinderLoader {
// Whether multiple provider should be considered as an error.
// This is further submitted to the configuration error policy.
private static boolean ensureSingletonProvider() {
return GetBooleanAction.privilegedGetProperty
("jdk.logger.finder.singleton");
return Boolean.getBoolean("jdk.logger.finder.singleton");
}
@SuppressWarnings("removal")
private static Iterator<System.LoggerFinder> findLoggerFinderProviders() {
final Iterator<System.LoggerFinder> iterator;
if (System.getSecurityManager() == null) {
iterator = ServiceLoader.load(System.LoggerFinder.class,
return ServiceLoader.load(System.LoggerFinder.class,
ClassLoader.getSystemClassLoader()).iterator();
} else {
final PrivilegedAction<Iterator<System.LoggerFinder>> pa =
() -> ServiceLoader.load(System.LoggerFinder.class,
ClassLoader.getSystemClassLoader()).iterator();
iterator = AccessController.doPrivileged(pa, null,
LOGGERFINDER_PERMISSION, CLASSLOADER_PERMISSION,
READ_PERMISSION);
}
return iterator;
}
public static final class TemporaryLoggerFinder extends LoggerFinder {
@ -219,25 +191,10 @@ public final class LoggerFinderLoader {
return result;
}
@SuppressWarnings("removal")
private static System.LoggerFinder loadDefaultImplementation() {
final SecurityManager sm = System.getSecurityManager();
final Iterator<DefaultLoggerFinder> iterator;
if (sm == null) {
iterator = ServiceLoader.loadInstalled(DefaultLoggerFinder.class).iterator();
} else {
// We use limited do privileged here - the minimum set of
// permissions required to 'see' the META-INF/services resources
// seems to be CLASSLOADER_PERMISSION and READ_PERMISSION.
// Note that do privileged is required because
// otherwise the SecurityManager will prevent the ServiceLoader
// from seeing the installed provider.
PrivilegedAction<Iterator<DefaultLoggerFinder>> pa = () ->
ServiceLoader.loadInstalled(DefaultLoggerFinder.class).iterator();
iterator = AccessController.doPrivileged(pa, null,
LOGGERFINDER_PERMISSION, CLASSLOADER_PERMISSION,
READ_PERMISSION);
}
final Iterator<DefaultLoggerFinder> iterator =
ServiceLoader.loadInstalled(DefaultLoggerFinder.class).iterator();
DefaultLoggerFinder result = null;
try {
// Iterator iterates with the access control context stored
@ -256,11 +213,6 @@ public final class LoggerFinderLoader {
}
public static System.LoggerFinder getLoggerFinder() {
@SuppressWarnings("removal")
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(LOGGERFINDER_PERMISSION);
}
return service();
}

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -29,8 +29,6 @@ import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.StackWalker.StackFrame;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.time.ZonedDateTime;
import java.util.Optional;
import java.util.MissingResourceException;
@ -39,7 +37,6 @@ import java.util.function.Function;
import java.lang.System.Logger;
import java.util.function.Predicate;
import java.util.function.Supplier;
import sun.security.action.GetPropertyAction;
import sun.util.logging.PlatformLogger;
import sun.util.logging.PlatformLogger.ConfigurableBridge.LoggerConfiguration;
@ -56,8 +53,7 @@ public class SimpleConsoleLogger extends LoggerConfiguration
PlatformLogger.toPlatformLevel(DEFAULT_LEVEL);
static Level getDefaultLevel() {
String levelName = GetPropertyAction
.privilegedGetProperty("jdk.system.logger.level", "INFO");
String levelName = System.getProperty("jdk.system.logger.level", "INFO");
try {
return Level.valueOf(levelName);
} catch (IllegalArgumentException iae) {
@ -202,18 +198,9 @@ public class SimpleConsoleLogger extends LoggerConfiguration
/*
* CallerFinder is a stateful predicate.
*/
@SuppressWarnings("removal")
static final class CallerFinder implements Predicate<StackWalker.StackFrame> {
private static final StackWalker WALKER;
static {
final PrivilegedAction<StackWalker> action = new PrivilegedAction<>() {
@Override
public StackWalker run() {
return StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
}
};
WALKER = AccessController.doPrivileged(action);
}
private static final StackWalker WALKER =
StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
/**
* Returns StackFrame of the caller's frame.
@ -439,8 +426,7 @@ public class SimpleConsoleLogger extends LoggerConfiguration
// Make it easier to wrap Logger...
private static final String[] skips;
static {
String additionalPkgs =
GetPropertyAction.privilegedGetProperty("jdk.logger.packages");
String additionalPkgs = System.getProperty("jdk.logger.packages");
skips = additionalPkgs == null ? new String[0] : additionalPkgs.split(",");
}
@ -499,7 +485,7 @@ public class SimpleConsoleLogger extends LoggerConfiguration
// jdk/test/java/lang/invoke/lambda/LogGeneratedClassesTest.java
// to fail - because that test has a testcase which somehow references
// PlatformLogger and counts the number of generated lambda classes.
String format = GetPropertyAction.privilegedGetProperty(key);
String format = System.getProperty(key);
if (format == null && defaultPropertyGetter != null) {
format = defaultPropertyGetter.apply(key);