Search in sources :

Example 91 with PrivilegedActionException

use of java.security.PrivilegedActionException in project OpenAM by OpenRock.

the class WindowsDesktopSSO method process.

/**
     * Processes the authentication request.
     *
     * @param callbacks
     * @param state
     * @return  -1 as succeeded; 0 as failed.
     * @exception AuthLoginException upon any failure.
     */
public int process(Callback[] callbacks, int state) throws AuthLoginException {
    int result = ISAuthConstants.LOGIN_IGNORE;
    // Check to see if the Rest Auth Endpoint has signified that IWA has failed.
    HttpServletRequest request = getHttpServletRequest();
    if (request != null && hasWDSSOFailed(request)) {
        return ISAuthConstants.LOGIN_IGNORE;
    }
    if (!getConfigParams()) {
        initWindowsDesktopSSOAuth(options);
    }
    // retrieve the spnego token
    byte[] spnegoToken = getSPNEGOTokenFromHTTPRequest(request);
    if (spnegoToken == null) {
        spnegoToken = getSPNEGOTokenFromCallback(callbacks);
    }
    if (spnegoToken == null) {
        debug.error("spnego token is not valid.");
        throw new AuthLoginException(amAuthWindowsDesktopSSO, "token", null);
    }
    if (debug.messageEnabled()) {
        debug.message("SPNEGO token: \n" + DerValue.printByteArray(spnegoToken, 0, spnegoToken.length));
    }
    // parse the spnego token and extract the kerberos mech token from it
    final byte[] kerberosToken = parseToken(spnegoToken);
    if (kerberosToken == null) {
        debug.error("kerberos token is not valid.");
        throw new AuthLoginException(amAuthWindowsDesktopSSO, "token", null);
    }
    if (debug.messageEnabled()) {
        debug.message("Kerberos token retrieved from SPNEGO token: \n" + DerValue.printByteArray(kerberosToken, 0, kerberosToken.length));
    }
    // authenticate the user with the kerberos token
    try {
        authenticateToken(kerberosToken, trustedKerberosRealms);
        if (debug.messageEnabled()) {
            debug.message("WindowsDesktopSSO kerberos authentication passed succesfully.");
        }
        result = ISAuthConstants.LOGIN_SUCCEED;
    } catch (PrivilegedActionException pe) {
        Exception e = extractException(pe);
        if (e instanceof GSSException) {
            int major = ((GSSException) e).getMajor();
            if (major == GSSException.CREDENTIALS_EXPIRED) {
                debug.message("Credential expired. Re-establish credential...");
                serviceLogin();
                try {
                    authenticateToken(kerberosToken, trustedKerberosRealms);
                    if (debug.messageEnabled()) {
                        debug.message("Authentication succeeded with new cred.");
                        result = ISAuthConstants.LOGIN_SUCCEED;
                    }
                } catch (Exception ee) {
                    debug.error("Authentication failed with new cred.Stack Trace", ee);
                    throw new AuthLoginException(amAuthWindowsDesktopSSO, "auth", null, ee);
                }
            } else {
                debug.error("Authentication failed with PrivilegedActionException wrapped GSSException. Stack Trace", e);
                throw new AuthLoginException(amAuthWindowsDesktopSSO, "auth", null, e);
            }
        }
    } catch (GSSException e1) {
        int major = e1.getMajor();
        if (major == GSSException.CREDENTIALS_EXPIRED) {
            debug.message("Credential expired. Re-establish credential...");
            serviceLogin();
            try {
                authenticateToken(kerberosToken, trustedKerberosRealms);
                if (debug.messageEnabled()) {
                    debug.message("Authentication succeeded with new cred.");
                    result = ISAuthConstants.LOGIN_SUCCEED;
                }
            } catch (Exception ee) {
                debug.error("Authentication failed with new cred. Stack Trace", ee);
                throw new AuthLoginException(amAuthWindowsDesktopSSO, "auth", null, ee);
            }
        } else {
            debug.error("Authentication failed with GSSException. Stack Trace", e1);
            throw new AuthLoginException(amAuthWindowsDesktopSSO, "auth", null, e1);
        }
    } catch (AuthLoginException e2) {
        debug.error("Authentication failed with AuthLoginException. Stack Trace", e2);
        throw e2;
    } catch (Exception e3) {
        debug.error("Authentication failed with generic exception. Stack Trace", e3);
        throw new AuthLoginException(amAuthWindowsDesktopSSO, "auth", null, e3);
    }
    return result;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) GSSException(org.ietf.jgss.GSSException) PrivilegedActionException(java.security.PrivilegedActionException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) IdRepoException(com.sun.identity.idm.IdRepoException) PrivilegedActionException(java.security.PrivilegedActionException) GSSException(org.ietf.jgss.GSSException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SSOException(com.iplanet.sso.SSOException)

Example 92 with PrivilegedActionException

use of java.security.PrivilegedActionException in project wildfly by wildfly.

the class MockRuntimeVaultReader method createVault.

public void createVault(final String fqn, final Map<String, Object> options) throws VaultReaderException {
    Map<String, Object> vaultOptions = new HashMap<String, Object>(options);
    SecurityVault vault = null;
    try {
        vault = AccessController.doPrivileged(new PrivilegedExceptionAction<SecurityVault>() {

            @Override
            public SecurityVault run() throws Exception {
                if (fqn == null || fqn.isEmpty()) {
                    return SecurityVaultFactory.get();
                } else {
                    return SecurityVaultFactory.get(fqn);
                }
            }
        });
    } catch (PrivilegedActionException e) {
        Throwable t = e.getCause();
        if (t instanceof SecurityVaultException) {
            throw SecurityLogger.ROOT_LOGGER.vaultReaderException(t);
        }
        if (t instanceof RuntimeException) {
            throw SecurityLogger.ROOT_LOGGER.runtimeException(t);
        }
        throw SecurityLogger.ROOT_LOGGER.runtimeException(t);
    }
    try {
        vault.init(vaultOptions);
    } catch (SecurityVaultException e) {
        e.printStackTrace();
        throw SecurityLogger.ROOT_LOGGER.vaultReaderException(e);
    }
    this.vault = vault;
}
Also used : HashMap(java.util.HashMap) PrivilegedActionException(java.security.PrivilegedActionException) SecurityVaultException(org.jboss.security.vault.SecurityVaultException) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) SecurityVault(org.jboss.security.vault.SecurityVault)

Example 93 with PrivilegedActionException

use of java.security.PrivilegedActionException in project wildfly by wildfly.

the class PicketLinkTestBase method makeCallWithKerberosAuthn.

/**
     * Returns response body for the given URL request as a String. It also checks if the returned HTTP status code is the
     * expected one. If the server returns {@link HttpServletResponse#SC_UNAUTHORIZED} and an username is provided, then the
     * given user is authenticated against Kerberos and a new request is executed under the new subject.
     *
     * @param uri                URI to which the request should be made
     * @param user               Username
     * @param pass               Password
     * @param expectedStatusCode expected status code returned from the requested server
     * @return HTTP response body
     * @throws IOException
     * @throws URISyntaxException
     * @throws PrivilegedActionException
     * @throws LoginException
     */
public static String makeCallWithKerberosAuthn(URI uri, final HttpClient httpClient, final String user, final String pass, final int expectedStatusCode) throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
    uri = Utils.replaceHost(uri, Utils.getDefaultHost(true));
    LOGGER.trace("Requesting URI: " + uri);
    final HttpGet httpGet = new HttpGet(uri);
    final HttpResponse response = httpClient.execute(httpGet);
    int statusCode = response.getStatusLine().getStatusCode();
    if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
        assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
        return EntityUtils.toString(response.getEntity());
    }
    final HttpEntity entity = response.getEntity();
    final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
    assertTrue("WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
    final Set<String> authnHeaderValues = new HashSet<String>();
    for (final Header header : authnHeaders) {
        authnHeaderValues.add(header.getValue());
    }
    assertTrue("WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
    }
    if (entity != null) {
        EntityUtils.consume(entity);
    }
    // Use our custom configuration to avoid reliance on external config
    final Krb5LoginConfiguration krb5configuration = new Krb5LoginConfiguration(Utils.getLoginConfiguration());
    Configuration.setConfiguration(krb5configuration);
    // 1. Authenticate to Kerberos.
    final LoginContext lc = Utils.loginWithKerberos(krb5configuration, user, pass);
    // 2. Perform the work as authenticated Subject.
    final String responseBody = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<String>() {

        public String run() throws Exception {
            final HttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode);
            return EntityUtils.toString(response.getEntity());
        }
    });
    lc.logout();
    krb5configuration.resetConfiguration();
    return responseBody;
}
Also used : HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) Krb5LoginConfiguration(org.jboss.as.test.integration.security.common.Krb5LoginConfiguration) LoginException(javax.security.auth.login.LoginException) ClientProtocolException(org.apache.http.client.ClientProtocolException) URISyntaxException(java.net.URISyntaxException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) LoginContext(javax.security.auth.login.LoginContext) Header(org.apache.http.Header) HashSet(java.util.HashSet)

Example 94 with PrivilegedActionException

use of java.security.PrivilegedActionException in project wildfly by wildfly.

the class JaccInterceptor method processInvocation.

@Override
public Object processInvocation(InterceptorContext context) throws Exception {
    Component component = context.getPrivateData(Component.class);
    final SecurityDomain securityDomain = context.getPrivateData(SecurityDomain.class);
    Assert.checkNotNullParam("securityDomain", securityDomain);
    final SecurityIdentity currentIdentity = securityDomain.getCurrentSecurityIdentity();
    if (component instanceof EJBComponent == false) {
        throw EjbLogger.ROOT_LOGGER.unexpectedComponent(component, EJBComponent.class);
    }
    Method invokedMethod = context.getMethod();
    ComponentView componentView = context.getPrivateData(ComponentView.class);
    String viewClassOfInvokedMethod = componentView.getViewClass().getName();
    // shouldn't really happen if the interceptor was setup correctly. But let's be safe and do a check
    if (!viewClassName.equals(viewClassOfInvokedMethod) || !viewMethod.equals(invokedMethod)) {
        throw EjbLogger.ROOT_LOGGER.failProcessInvocation(getClass().getName(), invokedMethod, viewClassOfInvokedMethod, viewMethod, viewClassName);
    }
    EJBComponent ejbComponent = (EJBComponent) component;
    if (WildFlySecurityManager.isChecking()) {
        try {
            AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
                hasPermission(ejbComponent, componentView, invokedMethod, currentIdentity);
                return null;
            });
        } catch (PrivilegedActionException e) {
            throw e.getException();
        }
    } else {
        hasPermission(ejbComponent, componentView, invokedMethod, currentIdentity);
    }
    // successful authorization, let the invocation proceed
    return context.proceed();
}
Also used : SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) ComponentView(org.jboss.as.ee.component.ComponentView) PrivilegedActionException(java.security.PrivilegedActionException) Method(java.lang.reflect.Method) EJBComponent(org.jboss.as.ejb3.component.EJBComponent) Component(org.jboss.as.ee.component.Component) EJBComponent(org.jboss.as.ejb3.component.EJBComponent) SecurityDomain(org.wildfly.security.auth.server.SecurityDomain)

Example 95 with PrivilegedActionException

use of java.security.PrivilegedActionException in project wildfly by wildfly.

the class RunAsPrincipalInterceptor method processInvocation.

public Object processInvocation(final InterceptorContext context) throws Exception {
    final Component component = context.getPrivateData(Component.class);
    if (component instanceof EJBComponent == false) {
        throw EjbLogger.ROOT_LOGGER.unexpectedComponent(component, EJBComponent.class);
    }
    final EJBComponent ejbComponent = (EJBComponent) component;
    // Set the incomingRunAsIdentity before switching users
    final SecurityDomain securityDomain = context.getPrivateData(SecurityDomain.class);
    Assert.checkNotNullParam("securityDomain", securityDomain);
    final SecurityIdentity currentIdentity = securityDomain.getCurrentSecurityIdentity();
    final SecurityIdentity oldIncomingRunAsIdentity = ejbComponent.getIncomingRunAsIdentity();
    SecurityIdentity newIdentity;
    try {
        // run as a user with the given name or if the caller has sufficient permission
        if (runAsPrincipal.equals(ANONYMOUS_PRINCIPAL)) {
            try {
                newIdentity = currentIdentity.createRunAsAnonymous();
            } catch (AuthorizationFailureException ex) {
                newIdentity = currentIdentity.createRunAsAnonymous(false);
            }
        } else {
            try {
                newIdentity = currentIdentity.createRunAsIdentity(runAsPrincipal);
            } catch (AuthorizationFailureException ex) {
                newIdentity = currentIdentity.createRunAsIdentity(runAsPrincipal, false);
            }
        }
        ejbComponent.setIncomingRunAsIdentity(currentIdentity);
        return newIdentity.runAs(context);
    } catch (PrivilegedActionException e) {
        Throwable cause = e.getCause();
        if (cause != null) {
            if (cause instanceof Exception) {
                throw (Exception) cause;
            } else {
                throw new RuntimeException(e);
            }
        } else {
            throw e;
        }
    } finally {
        ejbComponent.setIncomingRunAsIdentity(oldIncomingRunAsIdentity);
    }
}
Also used : SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) AuthorizationFailureException(org.wildfly.security.authz.AuthorizationFailureException) PrivilegedActionException(java.security.PrivilegedActionException) EJBComponent(org.jboss.as.ejb3.component.EJBComponent) Component(org.jboss.as.ee.component.Component) EJBComponent(org.jboss.as.ejb3.component.EJBComponent) PrivilegedActionException(java.security.PrivilegedActionException) AuthorizationFailureException(org.wildfly.security.authz.AuthorizationFailureException) SecurityDomain(org.wildfly.security.auth.server.SecurityDomain)

Aggregations

PrivilegedActionException (java.security.PrivilegedActionException)135 IOException (java.io.IOException)58 PrivilegedExceptionAction (java.security.PrivilegedExceptionAction)56 Subject (javax.security.auth.Subject)23 LoginContext (javax.security.auth.login.LoginContext)14 LoginException (javax.security.auth.login.LoginException)12 InvocationTargetException (java.lang.reflect.InvocationTargetException)11 Method (java.lang.reflect.Method)11 URISyntaxException (java.net.URISyntaxException)11 HashSet (java.util.HashSet)11 ServletException (javax.servlet.ServletException)11 AccessControlContext (java.security.AccessControlContext)10 Principal (java.security.Principal)9 GSSException (org.ietf.jgss.GSSException)9 Field (java.lang.reflect.Field)8 SolrServerException (org.apache.solr.client.solrj.SolrServerException)7 GSSManager (org.ietf.jgss.GSSManager)7 MalformedURLException (java.net.MalformedURLException)6 ArrayList (java.util.ArrayList)6 YardException (org.apache.stanbol.entityhub.servicesapi.yard.YardException)6