Java Code Examples for org.wildfly.security.manager.WildFlySecurityManager#setCurrentContextClassLoaderPrivileged()

The following examples show how to use org.wildfly.security.manager.WildFlySecurityManager#setCurrentContextClassLoaderPrivileged() . 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: PluggableMBeanServerImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private ClassLoader pushClassLoader(final ObjectName name) throws InstanceNotFoundException {
    ClassLoader mbeanCl;
    try {
        mbeanCl = doPrivileged(new PrivilegedExceptionAction<ClassLoader>() {
            public ClassLoader run() throws InstanceNotFoundException {
                return delegate.getClassLoaderFor(name);
            }
        });
    } catch (PrivilegedActionException e) {
        try {
            throw e.getCause();
        } catch (RuntimeException r) {
            throw r;
        } catch (InstanceNotFoundException ie) {
            throw ie;
        } catch (Error error) {
            throw error;
        } catch (Throwable throwable) {
            throw new UndeclaredThrowableException(throwable);
        }
    }
    return WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(mbeanCl);
}
 
Example 2
Source File: PluggableMBeanServerImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private ClassLoader pushClassLoaderByName(final ObjectName loaderName) throws InstanceNotFoundException {
    ClassLoader mbeanCl;
    try {
        mbeanCl = doPrivileged(new PrivilegedExceptionAction<ClassLoader>() {
            public ClassLoader run() throws Exception {
                return delegate.getClassLoader(loaderName);
            }
        });
    } catch (PrivilegedActionException e) {
        try {
            throw e.getCause();
        } catch (RuntimeException r) {
            throw r;
        } catch (InstanceNotFoundException ie) {
            throw ie;
        } catch (Error error) {
            throw error;
        } catch (Throwable throwable) {
            throw new UndeclaredThrowableException(throwable);
        }
    }
    return WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(mbeanCl);
}
 
Example 3
Source File: PluggableMBeanServerTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testNotificationTccl() throws Exception {
    ObjectName objName = createName("test.domain:bean=test-tccl");
    server.registerMBean(new TestBean(objName), objName);
    ClassLoader oldTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
    ClassLoader newOutTccl = new URLClassLoader(new URL[]{}, oldTccl); // creating a new class loader here
    WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(newOutTccl);
    try {
        final AtomicBoolean differ = new AtomicBoolean(false);
        NotificationFilterSupport filter = new NotificationFilterSupport();
        filter.enableType("testtccl");
        server.addNotificationListener(objName, new NotificationListener() {
            @Override
            public void handleNotification(Notification notification, Object handback) {
                Assert.assertEquals("callback", handback.toString());
                ClassLoader newInTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
                Assert.assertNotEquals(newInTccl, newOutTccl);
                differ.set(true);
            }
        }, filter, "callback");
        server.invoke(objName, "proceed", null, null);
        Assert.assertTrue(differ.get());
    } finally {
        WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
    }
}
 
Example 4
Source File: LdapSubjectSupplementalService.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void supplementSubject(Subject subject) throws IOException {
    final ClassLoader old = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(LdapSubjectSupplemental.class);
    try {
        Set<RealmUser> users = subject.getPrincipals(RealmUser.class);
        Set<Principal> principals = subject.getPrincipals();

        Set<RealmGroup> set = new HashSet<>();
        Set<String> result = new HashSet<>();
        for (RealmUser user : users) {
            String name = user.getName();
            result.add(name);
        }
        for (String s : ldapGroupSearcher.loadGroups(result)) {
            RealmGroup realmGroup = new RealmGroup(realmName, s);
            set.add(realmGroup);
        }
        principals.addAll(set);
    } finally {
        WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(old);
    }

}
 
Example 5
Source File: UserLdapCallbackHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public Function<Principal, Principal> getPrincipalMapper() {
    return p -> {
        final ClassLoader old = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(UserLdapCallbackHandler.class);
        LdapConnectionHandler ldapConnectionHandler = createLdapConnectionHandler();
        try {
            try {
                SearchResult<LdapEntry> searchResult = userSearcherSupplier.get().search(ldapConnectionHandler, p.getName());

                return p instanceof RealmUser ? new MappedPrincipal(((RealmUser) p).getRealm(), searchResult.getResult().getSimpleName(), p.getName())
                        : new MappedPrincipal(searchResult.getResult().getSimpleName(), p.getName());
            } catch (IllegalStateException | IOException | NamingException e) {
                SECURITY_LOGGER.trace("Unable to map principal.", e);
                return p;
            }
        } finally {
            safeClose(ldapConnectionHandler);
            WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(old);
        }
    };
}
 
Example 6
Source File: LdapConnectionManagerService.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private DirContext getConnection(final Hashtable<String, String> properties, final SSLContext sslContext) throws NamingException {
    ClassLoader old = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(LdapConnectionManagerService.class);
    try {
        if (sslContext != null) {
            ThreadLocalSSLSocketFactory.setSSLSocketFactory(sslContext.getSocketFactory());
            properties.put("java.naming.ldap.factory.socket", ThreadLocalSSLSocketFactory.class.getName());
        }
        if (SECURITY_LOGGER.isTraceEnabled()) {
            Hashtable<String, String> logProperties;
            if (properties.containsKey(Context.SECURITY_CREDENTIALS)) {
                logProperties = new Hashtable<String, String>(properties);
                logProperties.put(Context.SECURITY_CREDENTIALS, "***");
            } else {
                logProperties = properties;
            }
            SECURITY_LOGGER.tracef("Connecting to LDAP with properties (%s)", logProperties.toString());
        }

        return new InitialDirContext(properties);
    } finally {
        if (sslContext != null) {
            ThreadLocalSSLSocketFactory.removeSSLSocketFactory();
        }
        WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(old);
    }
}
 
Example 7
Source File: DeferredExtensionContext.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private XMLStreamException loadModule(final String moduleName, final XMLMapper xmlMapper) throws XMLStreamException {
    // Register element handlers for this extension
    try {
        final Module module = moduleLoader.loadModule(ModuleIdentifier.fromString(moduleName));
        boolean initialized = false;
        for (final Extension extension : module.loadService(Extension.class)) {
            ClassLoader oldTccl = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(extension.getClass());
            try {
                extensionRegistry.initializeParsers(extension, moduleName, xmlMapper);
            } finally {
                WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
            }
            if (!initialized) {
                initialized = true;
            }
        }
        if (!initialized) {
            throw ControllerLogger.ROOT_LOGGER.notFound("META-INF/services/", Extension.class.getName(), module.getName());
        }
        return null;
    } catch (final ModuleLoadException e) {
        throw ControllerLogger.ROOT_LOGGER.failedToLoadModule(e);
    }
}
 
Example 8
Source File: KeytabService.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public SubjectIdentity createSubjectIdentity(final boolean isClient) throws LoginException {
    final Subject theSubject = new Subject();

    final LoginContext lc = new LoginContext("KDC", theSubject, NO_CALLBACK_HANDLER, isClient ? clientConfiguration : serverConfiguration);

    final ClassLoader old = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(KeytabService.class);
    try {
        lc.login();
    } finally {
        WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(old);
    }

    return new SubjectIdentity() {

        volatile boolean available = true;

        @Override
        public Subject getSubject() {
            assertAvailable();
            return theSubject;
        }

        @Override
        public void logout() {
            assertAvailable();
            try {
                lc.logout();
            } catch (LoginException e) {
                SECURITY_LOGGER.trace("Unable to logout.", e);
            }
        }

        private void assertAvailable() {
            if (available == false) {
                throw SECURITY_LOGGER.subjectIdentityLoggedOut();
            }
        }

    };
}
 
Example 9
Source File: LdapSubjectSupplementalService.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private synchronized Set<String> getGroups() throws RealmUnavailableException {
    if (groups == null) {
        final ClassLoader old = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(LdapSubjectSupplemental.class);
        try {
            groups = ldapGroupSearcher.loadGroups(Collections.singleton(principal.getName()));
        } catch (IOException e) {
            throw new RealmUnavailableException(e);
        } finally {
            WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(old);
        }
    }

    return groups;
}
 
Example 10
Source File: AbstractOperationContext.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void invokeResultHandler() {
    ClassLoader oldTccl = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(handler.getClass());
    try {
        resultHandler.handleResult(resultAction, AbstractOperationContext.this, operation);
    } finally {
        WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
    }
}
 
Example 11
Source File: ModelControllerClientFactoryImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private <T, U, V, R> R executeInModelControllerCl(TriFunction<T, U, V, R> function, T t, U u, V v) {
    final ClassLoader tccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
    try {
        WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(modelController.getClass().getClassLoader());
        return function.apply(t,u,v);
    } finally {
        WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(tccl);
    }
}
 
Example 12
Source File: PluggableMBeanServerImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void resetClassLoader(ClassLoader cl) {
    WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(cl);
}
 
Example 13
Source File: UserLdapCallbackHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static boolean verifyPassword(LdapConnectionHandler ldapConnectionHandler, SearchResult<LdapEntry> searchResult, String username, String password, Map<String, Object> sharedState) {
    LdapEntry ldapEntry = searchResult.getResult();

    // 3 - Connect as user once their DN is identified
    final PasswordCredential cachedCredential = searchResult.getAttachment(PASSWORD_KEY);
    if (cachedCredential != null) {
        if (cachedCredential.verify(password)) {
            SECURITY_LOGGER.tracef("Password verified for user '%s' (using cached password)", username);

            sharedState.put(LdapEntry.class.getName(), ldapEntry);
            if (username.equals(ldapEntry.getSimpleName()) == false) {
                sharedState.put(SecurityRealmService.LOADED_USERNAME_KEY, ldapEntry.getSimpleName());
            }
            return true;
        } else {
            SECURITY_LOGGER.tracef("Password verification failed for user (using cached password) '%s'", username);
            return false;
        }
    } else {
        final ClassLoader old = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(UserLdapCallbackHandler.class);
        try {
            LdapConnectionHandler verificationHandler = ldapConnectionHandler;
            URI referralUri = ldapEntry.getReferralUri();
            if (referralUri != null) {
                verificationHandler = verificationHandler.findForReferral(referralUri);
            }

            if (verificationHandler != null) {
                verificationHandler.verifyIdentity(ldapEntry.getDistinguishedName(), password);
                SECURITY_LOGGER.tracef("Password verified for user '%s' (using connection attempt)", username);

                searchResult.attach(PASSWORD_KEY, new PasswordCredential(password));
                sharedState.put(LdapEntry.class.getName(), ldapEntry);
                if (username.equals(ldapEntry.getSimpleName()) == false) {
                    sharedState.put(SecurityRealmService.LOADED_USERNAME_KEY, ldapEntry.getSimpleName());
                }
                return true;
            } else {
                SECURITY_LOGGER.tracef(
                        "Password verification failed for user '%s', no connection for referral '%s'", username,
                        referralUri.toString());
                return false;
            }
        } catch (Exception e) {
            SECURITY_LOGGER.tracef("Password verification failed for user (using connection attempt) '%s'",
                    username);
            return false;
        } finally {
            WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(old);
        }
    }
}