java.security.AccessControlContext Java Examples

The following examples show how to use java.security.AccessControlContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SSLConfiguration.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
@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
}
 
Example #2
Source File: bug6795356.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
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");
    }
 
Example #3
Source File: PreserveCombinerTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example #4
Source File: AsynchronousChannelGroupImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #5
Source File: MBeanInstantiator.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: PreserveCombinerTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example #7
Source File: DefaultMBeanServerInterceptor.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example #8
Source File: AbstractBeanFactory.java    From blog_demos with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
		}
	}
}
 
Example #9
Source File: AsynchronousChannelGroupImpl.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #10
Source File: Krb5Util.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #11
Source File: RepaintManager.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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);
}
 
Example #12
Source File: TCPTransport.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #13
Source File: PreserveCombinerTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example #14
Source File: Statement.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #15
Source File: Launcher.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #16
Source File: PreserveCombinerTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example #17
Source File: RequiredModelMBean.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #18
Source File: ForkJoinWorkerThread.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Version for InnocuousForkJoinWorkerThread
 */
ForkJoinWorkerThread(ForkJoinPool pool, ThreadGroup threadGroup,
                     AccessControlContext acc) {
    super(threadGroup, null, "aForkJoinWorkerThread");
    U.putOrderedObject(this, INHERITEDACCESSCONTROLCONTEXT, acc);
    eraseThreadLocals(); // clear before registering
    this.pool = pool;
    this.workQueue = pool.registerWorker(this);
}
 
Example #19
Source File: Krb5AcceptCredential.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
static Krb5AcceptCredential getInstance(final GSSCaller caller, Krb5NameElement name)
    throws GSSException {

    final String serverPrinc = (name == null? null:
        name.getKrb5PrincipalName().getName());
    final AccessControlContext acc = AccessController.getContext();

    ServiceCreds creds = null;
    try {
        creds = AccessController.doPrivileged(
                    new PrivilegedExceptionAction<ServiceCreds>() {
            public ServiceCreds run() throws Exception {
                return Krb5Util.getServiceCreds(
                    caller == GSSCaller.CALLER_UNKNOWN ? GSSCaller.CALLER_ACCEPT: caller,
                    serverPrinc, acc);
            }});
    } catch (PrivilegedActionException e) {
        GSSException ge =
            new GSSException(GSSException.NO_CRED, -1,
                "Attempt to obtain new ACCEPT credentials failed!");
        ge.initCause(e.getException());
        throw ge;
    }

    if (creds == null)
        throw new GSSException(GSSException.NO_CRED, -1,
                               "Failed to find any Kerberos credentails");

    if (name == null) {
        String fullName = creds.getName();
        if (fullName != null) {
            name = Krb5NameElement.getInstance(fullName,
                                   Krb5MechFactory.NT_GSS_KRB5_PRINCIPAL);
        }
    }

    return new Krb5AcceptCredential(name, creds);
}
 
Example #20
Source File: TCPTransport.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verify that the current access control context has permission to
 * accept the connection being dispatched by the current thread.
 */
protected void checkAcceptPermission(AccessControlContext acc) {
    SecurityManager sm = System.getSecurityManager();
    if (sm == null) {
        return;
    }
    ConnectionHandler h = threadConnectionHandler.get();
    if (h == null) {
        throw new Error(
            "checkAcceptPermission not in ConnectionHandler thread");
    }
    h.checkAcceptPermission(sm, acc);
}
 
Example #21
Source File: JMXSubjectDomainCombiner.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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));
}
 
Example #22
Source File: AbstractConfiguredObject.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
protected final AccessControlContext getSystemTaskControllerContext(String taskName, Principal principal)
{
    final Subject subject = getSystemTaskSubject(taskName, principal);
    return AccessController.doPrivileged
            (new PrivilegedAction<AccessControlContext>()
            {
                @Override
                public AccessControlContext run()
                {
                    return new AccessControlContext
                            (AccessController.getContext(),
                             new SubjectDomainCombiner(subject));
                }
            }, null);
}
 
Example #23
Source File: URLClassLoader.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
URLClassLoader(URL[] urls, ClassLoader parent,
               AccessControlContext acc) {
    super(parent);
    // this is to make the stack depth consistent with 1.1
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        security.checkCreateClassLoader();
    }
    ucp = new URLClassPath(urls);
    this.acc = acc;
}
 
Example #24
Source File: URLClassLoader.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
URLClassLoader(URL[] urls, AccessControlContext acc) {
    super();
    // this is to make the stack depth consistent with 1.1
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        security.checkCreateClassLoader();
    }
    this.acc = acc;
    ucp = new URLClassPath(urls, acc);
}
 
Example #25
Source File: EventQueue.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static AccessControlContext getAccessControlContextFrom(Object src) {
    return src instanceof Component ?
        ((Component)src).getAccessControlContext() :
        src instanceof MenuComponent ?
            ((MenuComponent)src).getAccessControlContext() :
            src instanceof TrayIcon ?
                ((TrayIcon)src).getAccessControlContext() :
                null;
}
 
Example #26
Source File: ForkJoinWorkerThread.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Version for InnocuousForkJoinWorkerThread
 */
ForkJoinWorkerThread(ForkJoinPool pool, ThreadGroup threadGroup,
                     AccessControlContext acc) {
    super(threadGroup, null, "aForkJoinWorkerThread");
    U.putOrderedObject(this, INHERITEDACCESSCONTROLCONTEXT, acc);
    eraseThreadLocals(); // clear before registering
    this.pool = pool;
    this.workQueue = pool.registerWorker(this);
}
 
Example #27
Source File: URLClassLoader.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new instance of URLClassLoader for the specified
 * URLs and default 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} before
 * loading the class.
 *
 * @param urls the URLs to search for classes and resources
 * @exception  NullPointerException if {@code urls} is {@code null}.
 * @return the resulting class loader
 */
public static URLClassLoader newInstance(final URL[] urls) {
    // 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, acc);
            }
        });
    return ucl;
}
 
Example #28
Source File: NestedActions.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object run() {
    Utils.readFile(filename);

    AccessControlContext acc = AccessController.getContext();
    Subject subject = Subject.getSubject(acc);
    ReadPropertyAction readProperty = new ReadPropertyAction();
    if (anotherSubject != null) {
        return Subject.doAs(anotherSubject, readProperty);
    } else {
        return Subject.doAs(subject, readProperty);
    }
}
 
Example #29
Source File: KerberosClientKeyExchange.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void init(String serverName,
    AccessControlContext acc, ProtocolVersion protocolVersion,
    SecureRandom rand) throws IOException {

    if (impl != null) {
        impl.init(serverName, acc, protocolVersion, rand);
    }
}
 
Example #30
Source File: JMXSubjectDomainCombiner.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * 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));
}