com.atlassian.bamboo.specs.maven.sandbox.BambooSpecsSecurityManager Maven / Gradle / Ivy
package com.atlassian.bamboo.specs.maven.sandbox;
import java.security.AccessControlException;
import java.security.Permission;
import java.security.ProtectionDomain;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import static com.atlassian.bamboo.specs.maven.sandbox.PrivilegedThreads.getThreadPermissionChecker;
/**
* A security manager that treats one thread in a JVM as a high-privilege, unrestricted thread.
* All other threads will have the same restrictions as applets (no network/file access etc.)
*/
public class BambooSpecsSecurityManager extends SecurityManager {
private static final String DEBUG_MODE = System.getProperty("specs.security.manager.debug");
private final Set threadsBeingChecked = ConcurrentHashMap.newKeySet();
@Override
public void checkPermission(final Permission perm) {
if (!threadsBeingChecked.add(Thread.currentThread())) {
//we're already checking this thread
return;
}
try {
final Collection context = AccessControlContextHackcessor.getContext(getClass());
if (context.isEmpty()) {
//the stack contained only privileged code
log("Allowing privileged call: " + perm);
return;
}
try {
getThreadPermissionChecker().checkPermission(perm);
} catch (final AccessControlException e) {
log("Access denied: " + perm);
throw e;
}
} finally {
threadsBeingChecked.remove(Thread.currentThread());
}
}
@Override
public void checkPermission(final Permission perm, final Object context) {
getThreadPermissionChecker().checkPermission(perm, context);
}
@Override
public void checkAccess(final Thread t) {
super.checkAccess(t);
throw new AccessControlException("Access to threads is not permitted");
}
/**
* Set the permission checkers used by the {@link BambooSpecsSecurityManager}.
* @param specializedVerifiers map that associates threads to their specialized verifiers. The current thread will always be a high privilege thread and does not need to be added.
* @param defaultVerifier the checker used by default if no customised checker is found
*/
public static void setPermissionCheckers(final Map specializedVerifiers, final ThreadPermissionVerifier defaultVerifier) {
final Map specializedVerifiersAndCurrentThread = new HashMap<>(specializedVerifiers);
specializedVerifiersAndCurrentThread.put(Thread.currentThread(), HighPrivilegeThreadPermissionVerifier.INSTANCE);
PrivilegedThreads.setThreadPermissionCheckers(specializedVerifiersAndCurrentThread, defaultVerifier);
}
/**
* Clear the permission checkers used by the {@link BambooSpecsSecurityManager}.
*/
public static void clearPermissionCheckers() {
PrivilegedThreads.resetThreadPermissionCheckers();
}
static void log(final String s) {
if (DEBUG_MODE != null) {
System.out.println(s);
}
}
}