Java Code Examples for javax.security.auth.Subject#doAsPrivileged()

The following examples show how to use javax.security.auth.Subject#doAsPrivileged() . 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: DefaultListableBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testInitSecurityAwarePrototypeBean() {
	final DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	RootBeanDefinition bd = new RootBeanDefinition(TestSecuredBean.class);
	bd.setScope(ConfigurableBeanFactory.SCOPE_PROTOTYPE);
	bd.setInitMethodName("init");
	lbf.registerBeanDefinition("test", bd);
	final Subject subject = new Subject();
	subject.getPrincipals().add(new TestPrincipal("user1"));

	TestSecuredBean bean = (TestSecuredBean) Subject.doAsPrivileged(subject,
			new PrivilegedAction() {
				@Override
				public Object run() {
					return lbf.getBean("test");
				}
			}, null);
	assertNotNull(bean);
	assertEquals("user1", bean.getUserName());
}
 
Example 2
Source File: ROConnection.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @see javax.management.MBeanServerConnection#getMBeanCount()
 */
public Integer getMBeanCount() throws IOException {
    if (this.subject == null) {
        return this.mbs.getMBeanCount();
    }
    try {
        return (Integer) Subject.doAsPrivileged(this.subject, new PrivilegedExceptionAction<Integer>() {
            public final Integer run() throws Exception {
                return mbs.getMBeanCount();
            }
        }, this.context);
    } catch (final PrivilegedActionException pe) {
        final Exception e = JMXProviderUtils.extractException(pe);
        if (e instanceof IOException)
            throw (IOException) e;
        throw JMXProviderUtils.newIOException("Got unexpected server exception: " + e, e);
    }
}
 
Example 3
Source File: Client.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
private boolean checkSuperUserPermission(final Permission... superUserPermissions) {
    for (Permission superUserPermission : superUserPermissions) {
        try {
            Subject.doAsPrivileged(subject, (PrivilegedAction<Object>) () -> {
                SecurityManager sm = System.getSecurityManager();
                if (sm != null) {
                    sm.checkPermission(superUserPermission);
                }
                return null;
            }, null);
            return true;
        } catch (SecurityException ex1) {
            // ignore exception
        }
    }
    return false;
}
 
Example 4
Source File: ROConnection.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @see javax.management.MBeanServerConnection#getMBeanInfo(javax.management.ObjectName)
 */
public MBeanInfo getMBeanInfo(final ObjectName name)
        throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException {
    if (this.subject == null) {
        return this.mbs.getMBeanInfo(name);
    }
    try {
        return (MBeanInfo) Subject.doAsPrivileged(this.subject, new PrivilegedExceptionAction<MBeanInfo>() {
            public final MBeanInfo run() throws Exception {
                return mbs.getMBeanInfo(name);
            }
        }, this.context);
    } catch (final PrivilegedActionException pe) {
        final Exception e = JMXProviderUtils.extractException(pe);
        if (e instanceof InstanceNotFoundException)
            throw (InstanceNotFoundException) e;
        if (e instanceof IntrospectionException)
            throw (IntrospectionException) e;
        if (e instanceof ReflectionException)
            throw (ReflectionException) e;
        if (e instanceof IOException)
            throw (IOException) e;
        throw JMXProviderUtils.newIOException("Got unexpected server exception: " + e, e);
    }
}
 
Example 5
Source File: Client.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Checks that client has the specified permission.
 *
 * @return true if it has, throw {@link SecurityException} otherwise with specified error message
 */
public boolean checkPermission(final Permission permission, String errorMessage,
        final Permission... superUserPermissions) {
    try {
        Subject.doAsPrivileged(subject, (PrivilegedAction<Object>) () -> {
            SecurityManager sm = System.getSecurityManager();
            if (sm != null) {
                sm.checkPermission(permission);
            }
            return null;
        }, null);
    } catch (SecurityException ex) {
        // if the client is not allowed to perform the operation, we check if it has one of the provided super-user permissions
        if (!checkSuperUserPermission(superUserPermissions)) {
            throw new SecurityException(errorMessage, ex);
        }
    }

    return true;
}
 
Example 6
Source File: ROConnection.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @see javax.management.MBeanServerConnection#queryMBeans(javax.management.ObjectName, javax.management.QueryExp)
 */
@SuppressWarnings("unchecked")
public Set<ObjectInstance> queryMBeans(final ObjectName name, final QueryExp query) throws IOException {
    if (this.context == null) {
        return this.mbs.queryMBeans(name, query);
    }
    try {
        return (Set<ObjectInstance>) Subject.doAsPrivileged(this.subject,
                                                            new PrivilegedExceptionAction<Set<ObjectInstance>>() {
                                                                public final Set<ObjectInstance> run()
                                                                        throws Exception {
                                                                    return mbs.queryMBeans(name, query);
                                                                }
                                                            },
                                                            this.context);
    } catch (final PrivilegedActionException pe) {
        final Exception e = JMXProviderUtils.extractException(pe);
        if (e instanceof IOException)
            throw (IOException) e;
        throw JMXProviderUtils.newIOException("Got unexpected server exception: " + e, e);
    }
}
 
Example 7
Source File: ROConnection.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @see javax.management.MBeanServerConnection#setAttributes(javax.management.ObjectName, javax.management.AttributeList)
 */
public AttributeList setAttributes(final ObjectName name, final AttributeList attributes)
        throws InstanceNotFoundException, ReflectionException, IOException {
    if (this.subject == null) {
        return this.mbs.setAttributes(name, attributes);
    }
    try {
        return (AttributeList) Subject.doAsPrivileged(this.subject, new PrivilegedExceptionAction<AttributeList>() {
            public final AttributeList run() throws Exception {
                return mbs.setAttributes(name, attributes);
            }
        }, this.context);
    } catch (final PrivilegedActionException pe) {
        final Exception e = JMXProviderUtils.extractException(pe);
        if (e instanceof InstanceNotFoundException)
            throw (InstanceNotFoundException) e;
        if (e instanceof ReflectionException)
            throw (ReflectionException) e;
        if (e instanceof IOException)
            throw (IOException) e;
        throw JMXProviderUtils.newIOException("Got unexpected server exception: " + e, e);
    }
}
 
Example 8
Source File: SecurityUtil.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Checks that a Subject has a Permission under the SecurityManager.
 * To perform this check the following policy grant is required
 * <ul>
 * <li> to run the encapsulated test:
 *      permission javax.security.auth.AuthPermission "doAsPrivileged";
 * </ul>
 * or an AccessControlException will be raised detailing the cause.
 * <p>
 *
 * @param subject the subject representing the SystemPrincipal(s)
 * @param perm the permission to be checked
 * @throws AccessControlException if permissions are missing
 */
static public void checkSubjectHasPermission(final Subject subject,
                                             final Permission perm) {
    // the checks
    final PrivilegedAction runCheck
        = new PrivilegedAction() {
                public Object run() {
                    AccessController.checkPermission(perm);
                    return null;
                }
            };
    final PrivilegedAction runCheckAsPrivilegedUser
        = new PrivilegedAction() {
                public Object run() {
                    // run check only using the the subject
                    // (by using null as the AccessControlContext)
                    final AccessControlContext acc = null;
                    Subject.doAsPrivileged(subject, runCheck, acc);
                    return null;
                }
            };

    // run check as privileged action for narrow codebase permissions
    AccessController.doPrivileged(runCheckAsPrivilegedUser);
}
 
Example 9
Source File: SelfExpansion.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 {
    Subject s = new Subject();
    s.getPrincipals().add
            (new javax.security.auth.x500.X500Principal("CN=test"));
    s.getPrivateCredentials().add(new String("test"));
    try {
        Subject.doAsPrivileged(s, new PrivilegedAction() {
            public Object run() {
                java.util.Iterator i = Subject.getSubject
                            (AccessController.getContext
                            ()).getPrivateCredentials().iterator();
                return i.next();
            }
        }, null);
        System.out.println("Test succeeded");
    } catch (Exception e) {
        System.out.println("Test failed");
        e.printStackTrace();
        throw e;
    }
}
 
Example 10
Source File: Test.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    System.setSecurityManager(new SecurityManager());
    try {
        Subject.doAsPrivileged(get("CN=joe"), new PrivilegedAction() {
            public Object run() {
                return Subject.doAs(null, new PrivilegedAction() {
                    public Object run() {
                    return System.getProperty("foobar");
                    }
                });
            }
        }, null);
    throw new RuntimeException
             ("Access control exception should have occcured");
    } catch (java.security.AccessControlException e) {
            // Expected exception occured
    }
}
 
Example 11
Source File: CallbacksSecurityTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testInitSecurityAwarePrototypeBean() {
	final DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	BeanDefinitionBuilder bdb = BeanDefinitionBuilder
			.genericBeanDefinition(NonPrivilegedBean.class).setScope(
					ConfigurableBeanFactory.SCOPE_PROTOTYPE)
			.setInitMethodName("init").setDestroyMethodName("destroy")
			.addConstructorArgValue("user1");
	lbf.registerBeanDefinition("test", bdb.getBeanDefinition());
	final Subject subject = new Subject();
	subject.getPrincipals().add(new TestPrincipal("user1"));

	NonPrivilegedBean bean = Subject.doAsPrivileged(
			subject, new PrivilegedAction<NonPrivilegedBean>() {
				@Override
				public NonPrivilegedBean run() {
					return lbf.getBean("test", NonPrivilegedBean.class);
				}
			}, null);
	assertNotNull(bean);
}
 
Example 12
Source File: ROConnection.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @see javax.management.MBeanServerConnection#getAttributes(javax.management.ObjectName, java.lang.String[])
 */
public AttributeList getAttributes(final ObjectName name, final String[] attributes)
        throws InstanceNotFoundException, ReflectionException, IOException {
    if (this.subject == null) {
        return this.mbs.getAttributes(name, attributes);
    }
    try {
        return (AttributeList) Subject.doAsPrivileged(this.subject, new PrivilegedExceptionAction<AttributeList>() {
            public final AttributeList run() throws Exception {
                return mbs.getAttributes(name, attributes);
            }
        }, this.context);
    } catch (final PrivilegedActionException pe) {
        final Exception e = JMXProviderUtils.extractException(pe);
        if (e instanceof InstanceNotFoundException)
            throw (InstanceNotFoundException) e;
        if (e instanceof ReflectionException)
            throw (ReflectionException) e;
        if (e instanceof IOException)
            throw (IOException) e;
        throw JMXProviderUtils.newIOException("Got unexpected server exception: " + e, e);
    }
}
 
Example 13
Source File: DefaultListableBeanFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testInitSecurityAwarePrototypeBean() {
	final DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	RootBeanDefinition bd = new RootBeanDefinition(TestSecuredBean.class);
	bd.setScope(ConfigurableBeanFactory.SCOPE_PROTOTYPE);
	bd.setInitMethodName("init");
	lbf.registerBeanDefinition("test", bd);
	final Subject subject = new Subject();
	subject.getPrincipals().add(new TestPrincipal("user1"));

	TestSecuredBean bean = (TestSecuredBean) Subject.doAsPrivileged(subject,
			new PrivilegedAction() {
				@Override
				public Object run() {
					return lbf.getBean("test");
				}
			}, null);
	assertNotNull(bean);
	assertEquals("user1", bean.getUserName());
}
 
Example 14
Source File: SystemPrivilegesPermissionTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
public Object run() {
    final boolean readOnly = true;
    final Set principals = new HashSet();
    final Set publicCredentials = new HashSet();
    final Set privateCredentials = new HashSet();
    // add the given principal
    principals.add(principal);
    // also add a principal with the "normalized" name for testing
    // authorization ids
    final String normalized = getAuthorizationId(principal.getName());
    principals.add(new SystemPrincipal(normalized));
    final Subject subject = new Subject(readOnly,
            principals,
            publicCredentials,
            privateCredentials);

    // check subject's permission with a fresh AccessControlContext,
    // not the thread's current one (Subject.doAs(subject, action))
    // println("    run doAsPrivileged() as " + principal + "...");
    // The alternative approach to use Subject.doAs(subject, action)
    // instead of Subject.doAsPrivileged(subject, action, null) has
    // issues: there are subtile differences between these methods
    // regarding the checking of the caller's protection domain.  To
    // make doAs() work, the shutdown/createDatabase permissions must
    // be granted to the codebase (class RunAsPrivilegedUserAction).
    // This, however, defeats the purpose since everyone now's granted
    // permission.  In contrast, doAsPrivileged() with a null ACC
    // seems to effectively ignore the caller's protection domain, so
    // the check now only depends on the principal's permissions.
    Subject.doAsPrivileged(subject, action, null);
    //Subject.doAs(subject, action);
    return null;
}
 
Example 15
Source File: WildcardPrincipalName.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override public Void run() {
    Set<Principal> principals = new HashSet<>();
    Set<Object> publicCredentials = new HashSet<>();
    Set<Object> privateCredentials = new HashSet<>();

    principals.add(principal);
    Subject subject = new Subject(true,
                                  principals,
                                  publicCredentials,
                                  privateCredentials);

    Subject.doAsPrivileged(subject, action, null);
    return null;
}
 
Example 16
Source File: WildcardPrincipalName.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override public Void run() {
    Set<Principal> principals = new HashSet<>();
    Set<Object> publicCredentials = new HashSet<>();
    Set<Object> privateCredentials = new HashSet<>();

    principals.add(principal);
    Subject subject = new Subject(true,
                                  principals,
                                  publicCredentials,
                                  privateCredentials);

    Subject.doAsPrivileged(subject, action, null);
    return null;
}
 
Example 17
Source File: GetLocalHostWithSM.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

            // try setting the local hostname
            InetAddress localHost = InetAddress.getLocalHost();
            if (localHost.isLoopbackAddress()) {
                System.err.println("Local host name is resolved into a loopback address. Quit now!");
                return;
            }
            System.setProperty("host.name", localHost.
                                            getHostName());
            String policyFileName = System.getProperty("test.src", ".") +
                          "/" + "policy.file";
            System.setProperty("java.security.policy", policyFileName);
            System.setSecurityManager(new SecurityManager());

            InetAddress localHost1 = null;
            InetAddress localHost2 = null;

            localHost1 = InetAddress.getLocalHost();

            Subject mySubject = new Subject();
            MyPrincipal userPrincipal = new MyPrincipal("test");
            mySubject.getPrincipals().add(userPrincipal);
            localHost2 = (InetAddress)Subject.doAsPrivileged(mySubject,
                                new MyAction(), null);

            if (localHost1.equals(localHost2)) {
                System.out.println("localHost1 = " + localHost1);
                throw new RuntimeException("InetAddress.getLocalHost() test " +
                                           " fails. localHost2 should be " +
                                           " the real address instead of " +
                                           " the loopback address."+localHost2);
            }
        }
 
Example 18
Source File: WildcardPrincipalName.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override public Void run() {
    Set<Principal> principals = new HashSet<>();
    Set<Object> publicCredentials = new HashSet<>();
    Set<Object> privateCredentials = new HashSet<>();

    principals.add(principal);
    Subject subject = new Subject(true,
                                  principals,
                                  publicCredentials,
                                  privateCredentials);

    Subject.doAsPrivileged(subject, action, null);
    return null;
}
 
Example 19
Source File: GetLocalHostWithSM.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

            // try setting the local hostname
            InetAddress localHost = InetAddress.getLocalHost();
            if (localHost.isLoopbackAddress()) {
                System.err.println("Local host name is resolved into a loopback address. Quit now!");
                return;
            }
            System.setProperty("host.name", localHost.
                                            getHostName());
            String policyFileName = System.getProperty("test.src", ".") +
                          "/" + "policy.file";
            System.setProperty("java.security.policy", policyFileName);
            System.setSecurityManager(new SecurityManager());

            InetAddress localHost1 = null;
            InetAddress localHost2 = null;

            localHost1 = InetAddress.getLocalHost();

            Subject mySubject = new Subject();
            MyPrincipal userPrincipal = new MyPrincipal("test");
            mySubject.getPrincipals().add(userPrincipal);
            localHost2 = (InetAddress)Subject.doAsPrivileged(mySubject,
                                new MyAction(), null);

            if (localHost1.equals(localHost2)) {
                System.out.println("localHost1 = " + localHost1);
                throw new RuntimeException("InetAddress.getLocalHost() test " +
                                           " fails. localHost2 should be " +
                                           " the real address instead of " +
                                           " the loopback address."+localHost2);
            }
        }
 
Example 20
Source File: SystemPrivilegesPermissionTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public Object run() {
    final boolean readOnly = true;
    final Set principals = new HashSet();
    final Set publicCredentials = new HashSet();
    final Set privateCredentials = new HashSet();
    // add the given principal
    principals.add(principal);
    // also add a principal with the "normalized" name for testing
    // authorization ids
    final String normalized = getAuthorizationId(principal.getName());
    principals.add(new SystemPrincipal(normalized));
    final Subject subject = new Subject(readOnly,
                                        principals,
                                        publicCredentials,
                                        privateCredentials);

    // check subject's permission with a fresh AccessControlContext,
    // not the thread's current one (Subject.doAs(subject, action))
    // println("    run doAsPrivileged() as " + principal + "...");
    // The alternative approach to use Subject.doAs(subject, action)
    // instead of Subject.doAsPrivileged(subject, action, null) has
    // issues: there are subtile differences between these methods
    // regarding the checking of the caller's protection domain.  To
    // make doAs() work, the shutdown/createDatabase permissions must
    // be granted to the codebase (class RunAsPrivilegedUserAction).
    // This, however, defeats the purpose since everyone now's granted
    // permission.  In contrast, doAsPrivileged() with a null ACC
    // seems to effectively ignore the caller's protection domain, so
    // the check now only depends on the principal's permissions.
    Subject.doAsPrivileged(subject, action, null);
    //Subject.doAs(subject, action);
    return null;
}