下面列出了怎么用java.security.AccessControlContext的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Executes the given command on one of the channel group's pooled threads.
*/
@Override
public final void execute(Runnable task) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// when a security manager is installed then the user's task
// must be run with the current calling context
final AccessControlContext acc = AccessController.getContext();
final Runnable delegate = task;
task = new Runnable() {
@Override
public void run() {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
delegate.run();
return null;
}
}, acc);
}
};
}
executeOnPooledThread(task);
}
private static void checkMBeanTrustPermission(final Class<?> theClass)
throws SecurityException {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
Permission perm = new MBeanTrustPermission("register");
PrivilegedAction<ProtectionDomain> act =
new PrivilegedAction<ProtectionDomain>() {
public ProtectionDomain run() {
return theClass.getProtectionDomain();
}
};
ProtectionDomain pd = AccessController.doPrivileged(act);
AccessControlContext acc =
new AccessControlContext(new ProtectionDomain[] { pd });
sm.checkPermission(perm, acc);
}
}
public static void main(String[]args) throws Exception {
final DomainCombiner dc = new DomainCombiner() {
@Override
public ProtectionDomain[] combine(ProtectionDomain[] currentDomains, ProtectionDomain[] assignedDomains) {
return currentDomains; // basically a no-op
}
};
// Get an instance of the saved ACC
AccessControlContext saved = AccessController.getContext();
// Simulate the stack ACC with a DomainCombiner attached
AccessControlContext stack = new AccessControlContext(AccessController.getContext(), dc);
// Now try to run JavaSecurityAccess.doIntersectionPrivilege() and assert
// whether the DomainCombiner from the stack ACC is preserved
boolean ret = SharedSecrets.getJavaSecurityAccess().doIntersectionPrivilege(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
return dc == AccessController.getContext().getDomainCombiner();
}
}, stack, saved);
if (!ret) {
System.exit(1);
}
}
Object invoke() throws Exception {
AccessControlContext acc = this.acc;
if ((acc == null) && (System.getSecurityManager() != null)) {
throw new SecurityException("AccessControlContext is not set");
}
try {
return AccessController.doPrivileged(
new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
return invokeInternal();
}
},
acc
);
}
catch (PrivilegedActionException exception) {
throw exception.getException();
}
}
public static void main(String[]args) throws Exception {
final DomainCombiner dc = new DomainCombiner() {
@Override
public ProtectionDomain[] combine(ProtectionDomain[] currentDomains, ProtectionDomain[] assignedDomains) {
return currentDomains; // basically a no-op
}
};
// Get an instance of the saved ACC
AccessControlContext saved = AccessController.getContext();
// Simulate the stack ACC with a DomainCombiner attached
AccessControlContext stack = new AccessControlContext(AccessController.getContext(), dc);
// Now try to run JavaSecurityAccess.doIntersectionPrivilege() and assert
// whether the DomainCombiner from the stack ACC is preserved
boolean ret = SharedSecrets.getJavaSecurityAccess().doIntersectionPrivilege(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
return dc == AccessController.getContext().getDomainCombiner();
}
}, stack, saved);
if (!ret) {
System.exit(1);
}
}
@Override
@SuppressWarnings({"unchecked", "CloneDeclaresCloneNotSupported"})
public Object clone() {
// Note that only references to the configurations are copied.
try {
SSLConfiguration config = (SSLConfiguration)super.clone();
if (handshakeListeners != null) {
config.handshakeListeners =
(HashMap<HandshakeCompletedListener, AccessControlContext>)
handshakeListeners.clone();
}
return config;
} catch (CloneNotSupportedException cnse) {
// unlikely
}
return null; // unlikely
}
/**
* create a context that can read any directories (recursively)
* mentioned in the class path. In the case of a jar, it has to
* be the directory containing the jar, not just the jar, as jar
* files might refer to other jar files.
*/
private static AccessControlContext getContext(File[] cp)
throws MalformedURLException
{
PathPermissions perms =
new PathPermissions(cp);
ProtectionDomain domain =
new ProtectionDomain(new CodeSource(perms.getCodeBase(),
(java.security.cert.Certificate[]) null),
perms);
AccessControlContext acc =
new AccessControlContext(new ProtectionDomain[] { domain });
return acc;
}
/**
* Verify that the given AccessControlContext has permission to
* accept this connection.
*/
void checkAcceptPermission(SecurityManager sm,
AccessControlContext acc)
{
/*
* Note: no need to synchronize on cache-related fields, since this
* method only gets called from the ConnectionHandler's thread.
*/
if (sm != cacheSecurityManager) {
okContext = null;
authCache = new WeakHashMap<AccessControlContext,
Reference<AccessControlContext>>();
cacheSecurityManager = sm;
}
if (acc.equals(okContext) || authCache.containsKey(acc)) {
return;
}
InetAddress addr = socket.getInetAddress();
String host = (addr != null) ? addr.getHostAddress() : "*";
sm.checkAccept(host, socket.getPort());
authCache.put(acc, new SoftReference<AccessControlContext>(acc));
okContext = acc;
}
void nativeQueueSurfaceDataRunnable(AppContext appContext,
final Component c, final Runnable r)
{
synchronized(this) {
if (runnableList == null) {
runnableList = new LinkedList<Runnable>();
}
runnableList.add(new Runnable() {
public void run() {
AccessControlContext stack = AccessController.getContext();
AccessControlContext acc =
AWTAccessor.getComponentAccessor().getAccessControlContext(c);
javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Void>() {
public Void run() {
r.run();
return null;
}
}, stack, acc);
}
});
}
scheduleProcessingRunnable(appContext);
}
/**
* Retrieves the ServiceCreds for the specified server principal from
* the Subject in the specified AccessControlContext. If not found, and if
* useSubjectCredsOnly is false, then obtain from a LoginContext.
*
* NOTE: This method is also used by JSSE Kerberos Cipher Suites
*/
public static ServiceCreds getServiceCreds(GSSCaller caller,
String serverPrincipal, AccessControlContext acc)
throws LoginException {
Subject accSubj = Subject.getSubject(acc);
ServiceCreds sc = null;
if (accSubj != null) {
sc = ServiceCreds.getInstance(accSubj, serverPrincipal);
}
if (sc == null && !GSSUtil.useSubjectCredsOnly(caller)) {
Subject subject = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID);
sc = ServiceCreds.getInstance(subject, serverPrincipal);
}
return sc;
}
public static void main(String[]args) throws Exception {
final DomainCombiner dc = new DomainCombiner() {
@Override
public ProtectionDomain[] combine(ProtectionDomain[] currentDomains, ProtectionDomain[] assignedDomains) {
return currentDomains; // basically a no-op
}
};
// Get an instance of the saved ACC
AccessControlContext saved = AccessController.getContext();
// Simulate the stack ACC with a DomainCombiner attached
AccessControlContext stack = new AccessControlContext(AccessController.getContext(), dc);
// Now try to run JavaSecurityAccess.doIntersectionPrivilege() and assert
// whether the DomainCombiner from the stack ACC is preserved
boolean ret = SharedSecrets.getJavaSecurityAccess().doIntersectionPrivilege(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
return dc == AccessController.getContext().getDomainCombiner();
}
}, stack, saved);
if (!ret) {
System.exit(1);
}
}
/**
* Executes the given command on one of the channel group's pooled threads.
*/
@Override
public final void execute(Runnable task) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// when a security manager is installed then the user's task
// must be run with the current calling context
final AccessControlContext acc = AccessController.getContext();
final Runnable delegate = task;
task = new Runnable() {
@Override
public void run() {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
delegate.run();
return null;
}
}, acc);
}
};
}
executeOnPooledThread(task);
}
/**
* Add the given bean to the list of disposable beans in this factory,
* registering its DisposableBean interface and/or the given destroy method
* to be called on factory shutdown (if applicable). Only applies to singletons.
* @param beanName the name of the bean
* @param bean the bean instance
* @param mbd the bean definition for the bean
* @see RootBeanDefinition#isSingleton
* @see RootBeanDefinition#getDependsOn
* @see #registerDisposableBean
* @see #registerDependentBean
*/
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
if (mbd.isSingleton()) {
// Register a DisposableBean implementation that performs all destruction
// work for the given bean: DestructionAwareBeanPostProcessors,
// DisposableBean interface, custom destroy method.
registerDisposableBean(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
else {
// A bean with a custom scope...
Scope scope = this.scopes.get(mbd.getScope());
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope '" + mbd.getScope() + "'");
}
scope.registerDestructionCallback(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
}
}
public static void main(String[] args) throws Exception {
ProtectionDomain domain = new ProtectionDomain(null, null);
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
// this initialize ProxyLazyValues
UIManager.getLookAndFeel();
return null;
}
}, new AccessControlContext(new ProtectionDomain[]{domain}));
weakRef = new WeakReference<ProtectionDomain>(domain);
domain = null;
Util.generateOOME();
if (weakRef.get() != null) {
throw new RuntimeException("Memory leak found!");
}
System.out.println("Test passed");
}
public static void main(String[]args) throws Exception {
final DomainCombiner dc = new DomainCombiner() {
@Override
public ProtectionDomain[] combine(ProtectionDomain[] currentDomains, ProtectionDomain[] assignedDomains) {
return currentDomains; // basically a no-op
}
};
// Get an instance of the saved ACC
AccessControlContext saved = AccessController.getContext();
// Simulate the stack ACC with a DomainCombiner attached
AccessControlContext stack = new AccessControlContext(AccessController.getContext(), dc);
// Now try to run JavaSecurityAccess.doIntersectionPrivilege() and assert
// whether the DomainCombiner from the stack ACC is preserved
boolean ret = SharedSecrets.getJavaSecurityAccess().doIntersectionPrivilege(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
return dc == AccessController.getContext().getDomainCombiner();
}
}, stack, saved);
if (!ret) {
System.exit(1);
}
}
private ClassLoader getClassLoader(final ObjectName name) {
if(clr == null){
return null;
}
// Restrict to getClassLoader permission only
Permissions permissions = new Permissions();
permissions.add(new MBeanPermission("*", null, name, "getClassLoader"));
ProtectionDomain protectionDomain = new ProtectionDomain(null, permissions);
ProtectionDomain[] domains = {protectionDomain};
AccessControlContext ctx = new AccessControlContext(domains);
ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return clr.getClassLoader(name);
}
}, ctx);
return loader;
}
/**
* Get the AccessControlContext of the domain combiner created with
* the supplied subject, i.e. an AccessControlContext with the domain
* combiner created with the supplied subject and where the caller's
* context has been removed.
*/
public static AccessControlContext
getDomainCombinerContext(Subject subject) {
return new AccessControlContext(
new AccessControlContext(new ProtectionDomain[0]),
new JMXSubjectDomainCombiner(subject));
}
/**
* Creates a new instance of URLClassLoader for the specified
* URLs and parent class loader. If a security manager is
* installed, the {@code loadClass} method of the URLClassLoader
* returned by this method will invoke the
* {@code SecurityManager.checkPackageAccess} method before
* loading the class.
*
* @param urls the URLs to search for classes and resources
* @param parent the parent class loader for delegation
* @exception NullPointerException if {@code urls} is {@code null}.
* @return the resulting class loader
*/
public static URLClassLoader newInstance(final URL[] urls,
final ClassLoader parent) {
// Save the caller's context
final AccessControlContext acc = AccessController.getContext();
// Need a privileged block to create the class loader
URLClassLoader ucl = AccessController.doPrivileged(
new PrivilegedAction<URLClassLoader>() {
public URLClassLoader run() {
return new FactoryURLClassLoader(urls, parent, acc);
}
});
return ucl;
}
public void testDoPrivilegedWithCombiner() {
final Permission permission = new RuntimePermission("do stuff");
final DomainCombiner union = new DomainCombiner() {
@Override
public ProtectionDomain[] combine(ProtectionDomain[] a, ProtectionDomain[] b) {
throw new AssertionFailedError("Expected combiner to be unused");
}
};
ProtectionDomain protectionDomain = new ProtectionDomain(null, new Permissions());
AccessControlContext accessControlContext = new AccessControlContext(
new AccessControlContext(new ProtectionDomain[] { protectionDomain }), union);
final AtomicInteger actionCount = new AtomicInteger();
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
assertEquals(null, AccessController.getContext().getDomainCombiner());
AccessController.getContext().checkPermission(permission);
// Calling doPrivileged again would have exercised the combiner
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
actionCount.incrementAndGet();
assertEquals(null, AccessController.getContext().getDomainCombiner());
AccessController.getContext().checkPermission(permission);
return null;
}
});
return null;
}
}, accessControlContext);
assertEquals(1, actionCount.get());
}
public ClientKeyExchange createServerExchange(
ProtocolVersion protocolVersion, ProtocolVersion clientVersion,
SecureRandom rand, byte[] encodedTicket, byte[] encrypted,
AccessControlContext acc, Object serviceCreds) throws IOException {
return new ExchangerImpl(protocolVersion, clientVersion, rand,
encodedTicket, encrypted, acc, serviceCreds);
}
public void init() {
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
if (subject == null) {
return;
}
setNameFromPrincipal(subject.getPrincipals());
}
JarLoader(URL url, URLStreamHandler jarHandler,
HashMap<String, Loader> loaderMap,
AccessControlContext acc)
throws IOException
{
super(new URL("jar", "", -1, url + "!/", jarHandler));
csu = url;
handler = jarHandler;
lmap = loaderMap;
this.acc = acc;
ensureOpen();
}
public KerberosClientKeyExchange(ProtocolVersion protocolVersion,
ProtocolVersion clientVersion, SecureRandom rand,
HandshakeInStream input, AccessControlContext acc,
Object serverKeys) throws IOException {
if (impl != null) {
init(protocolVersion, clientVersion, rand, input, acc, serverKeys);
} else {
throw new IllegalStateException("Kerberos is unavailable");
}
}
public static void main(String[] args) throws Exception {
/*
* If we delay setting the security manager until after the service
* configuration file has been installed, then this test still
* functions properly, but the -Djava.security.debug output is
* lacking, so to ease debugging, we'll set it early-- at the cost
* of having to specify the policy even when running standalone.
*/
TestLibrary.suggestSecurityManager(null);
ServiceConfiguration.installServiceConfigurationFile();
/*
* Execute use of RMIClassLoader within an AccessControlContext
* that has a protection domain with no permissions, to make sure
* that RMIClassLoader can still properly initialize itself.
*/
CodeSource codesource = new CodeSource(null, (Certificate[]) null);
Permissions perms = null;
ProtectionDomain pd = new ProtectionDomain(codesource, perms);
AccessControlContext acc =
new AccessControlContext(new ProtectionDomain[] { pd });
java.security.AccessController.doPrivileged(
new java.security.PrivilegedExceptionAction() {
public Object run() throws Exception {
TestProvider.exerciseTestProvider(
TestProvider2.loadClassReturn,
TestProvider2.loadProxyClassReturn,
TestProvider2.getClassLoaderReturn,
TestProvider2.getClassAnnotationReturn,
TestProvider2.invocations);
return null;
}
}, acc);
}
private static boolean update(ImageObserver iw, AccessControlContext acc,
Image img, int info,
int x, int y, int w, int h) {
if (acc != null || System.getSecurityManager() != null) {
return AccessController.doPrivileged(
(PrivilegedAction<Boolean>) () -> {
return iw.imageUpdate(img, info, x, y, w, h);
}, acc);
}
return false;
}
/**
* Dispatches an event. The manner in which the event is
* dispatched depends upon the type of the event and the
* type of the event's source object:
*
* <table border=1 summary="Event types, source types, and dispatch methods">
* <tr>
* <th>Event Type</th>
* <th>Source Type</th>
* <th>Dispatched To</th>
* </tr>
* <tr>
* <td>ActiveEvent</td>
* <td>Any</td>
* <td>event.dispatch()</td>
* </tr>
* <tr>
* <td>Other</td>
* <td>Component</td>
* <td>source.dispatchEvent(AWTEvent)</td>
* </tr>
* <tr>
* <td>Other</td>
* <td>MenuComponent</td>
* <td>source.dispatchEvent(AWTEvent)</td>
* </tr>
* <tr>
* <td>Other</td>
* <td>Other</td>
* <td>No action (ignored)</td>
* </tr>
* </table>
* <p>
* @param event an instance of <code>java.awt.AWTEvent</code>,
* or a subclass of it
* @throws NullPointerException if <code>event</code> is <code>null</code>
* @since 1.2
*/
protected void dispatchEvent(final AWTEvent event) {
final Object src = event.getSource();
final PrivilegedAction<Void> action = new PrivilegedAction<Void>() {
public Void run() {
// In case fwDispatcher is installed and we're already on the
// dispatch thread (e.g. performing DefaultKeyboardFocusManager.sendMessage),
// dispatch the event straight away.
if (fwDispatcher == null || isDispatchThreadImpl()) {
dispatchEventImpl(event, src);
} else {
fwDispatcher.scheduleDispatch(new Runnable() {
@Override
public void run() {
if (dispatchThread.filterAndCheckEvent(event)) {
dispatchEventImpl(event, src);
}
}
});
}
return null;
}
};
final AccessControlContext stack = AccessController.getContext();
final AccessControlContext srcAcc = getAccessControlContextFrom(src);
final AccessControlContext eventAcc = event.getAccessControlContext();
if (srcAcc == null) {
javaSecurityAccess.doIntersectionPrivilege(action, stack, eventAcc);
} else {
javaSecurityAccess.doIntersectionPrivilege(
new PrivilegedAction<Void>() {
public Void run() {
javaSecurityAccess.doIntersectionPrivilege(action, eventAcc);
return null;
}
}, stack, srcAcc);
}
}
public KerberosClientKeyExchange(ProtocolVersion protocolVersion,
ProtocolVersion clientVersion, SecureRandom rand,
HandshakeInStream input, AccessControlContext acc,
Object serverKeys) throws IOException {
if (impl != null) {
init(protocolVersion, clientVersion, rand, input, acc, serverKeys);
} else {
throw new IllegalStateException("Kerberos is unavailable");
}
}
private Class<?> loadClass(final String className)
throws ClassNotFoundException {
AccessControlContext stack = AccessController.getContext();
final ClassNotFoundException[] caughtException = new ClassNotFoundException[1];
Class c = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Class<?>>() {
@Override
public Class<?> run() {
try {
ReflectUtil.checkPackageAccess(className);
return Class.forName(className);
} catch (ClassNotFoundException e) {
final ClassLoaderRepository clr =
getClassLoaderRepository();
try {
if (clr == null) throw new ClassNotFoundException(className);
return clr.loadClass(className);
} catch (ClassNotFoundException ex) {
caughtException[0] = ex;
}
}
return null;
}
}, stack, acc);
if (caughtException[0] != null) {
throw caughtException[0];
}
return c;
}
/**
* Check that the principal contained in the Subject is of
* type JMXPrincipal and refers to the principalName identity.
*/
private void checkSubject(String op) {
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
Set principals = subject.getPrincipals();
Principal principal = (Principal) principals.iterator().next();
if (!(principal instanceof JMXPrincipal))
throw new SecurityException(op+": Authenticated subject contains " +
"invalid principal type = " +
principal.getClass().getName());
String identity = principal.getName();
if (!identity.equals(principalName))
throw new SecurityException(op+": Authenticated subject contains " +
"invalid principal name = " + identity);
}
public void init(String serverName,
AccessControlContext acc, ProtocolVersion protocolVersion,
SecureRandom rand) throws IOException {
if (impl != null) {
impl.init(serverName, acc, protocolVersion, rand);
}
}