Search in sources :

Example 1 with ServerAuthContext

use of javax.security.auth.message.config.ServerAuthContext in project jetty.project by eclipse.

the class JaspiAuthenticator method secureResponse.

public boolean secureResponse(JaspiMessageInfo messageInfo, Authentication validatedUser) throws ServerAuthException {
    try {
        String authContextId = _authConfig.getAuthContextID(messageInfo);
        ServerAuthContext authContext = _authConfig.getAuthContext(authContextId, _serviceSubject, _authProperties);
        // TODO
        // authContext.cleanSubject(messageInfo,validatedUser.getUserIdentity().getSubject());
        AuthStatus status = authContext.secureResponse(messageInfo, _serviceSubject);
        return (AuthStatus.SEND_SUCCESS.equals(status));
    } catch (AuthException e) {
        throw new ServerAuthException(e);
    }
}
Also used : AuthStatus(javax.security.auth.message.AuthStatus) AuthException(javax.security.auth.message.AuthException) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) ServerAuthContext(javax.security.auth.message.config.ServerAuthContext)

Example 2 with ServerAuthContext

use of javax.security.auth.message.config.ServerAuthContext in project jetty.project by eclipse.

the class JaspiAuthenticator method validateRequest.

public Authentication validateRequest(JaspiMessageInfo messageInfo) throws ServerAuthException {
    try {
        String authContextId = _authConfig.getAuthContextID(messageInfo);
        ServerAuthContext authContext = _authConfig.getAuthContext(authContextId, _serviceSubject, _authProperties);
        Subject clientSubject = new Subject();
        AuthStatus authStatus = authContext.validateRequest(messageInfo, clientSubject, _serviceSubject);
        if (authStatus == AuthStatus.SEND_CONTINUE)
            return Authentication.SEND_CONTINUE;
        if (authStatus == AuthStatus.SEND_FAILURE)
            return Authentication.SEND_FAILURE;
        if (authStatus == AuthStatus.SUCCESS) {
            Set<UserIdentity> ids = clientSubject.getPrivateCredentials(UserIdentity.class);
            UserIdentity userIdentity;
            if (ids.size() > 0) {
                userIdentity = ids.iterator().next();
            } else {
                CallerPrincipalCallback principalCallback = _callbackHandler.getThreadCallerPrincipalCallback();
                if (principalCallback == null) {
                    return Authentication.UNAUTHENTICATED;
                }
                Principal principal = principalCallback.getPrincipal();
                if (principal == null) {
                    String principalName = principalCallback.getName();
                    Set<Principal> principals = principalCallback.getSubject().getPrincipals();
                    for (Principal p : principals) {
                        if (p.getName().equals(principalName)) {
                            principal = p;
                            break;
                        }
                    }
                    if (principal == null) {
                        return Authentication.UNAUTHENTICATED;
                    }
                }
                GroupPrincipalCallback groupPrincipalCallback = _callbackHandler.getThreadGroupPrincipalCallback();
                String[] groups = groupPrincipalCallback == null ? null : groupPrincipalCallback.getGroups();
                userIdentity = _identityService.newUserIdentity(clientSubject, principal, groups);
            }
            HttpSession session = ((HttpServletRequest) messageInfo.getRequestMessage()).getSession(false);
            Authentication cached = (session == null ? null : (SessionAuthentication) session.getAttribute(SessionAuthentication.__J_AUTHENTICATED));
            if (cached != null)
                return cached;
            return new UserAuthentication(getAuthMethod(), userIdentity);
        }
        if (authStatus == AuthStatus.SEND_SUCCESS) {
            // we are processing a message in a secureResponse dialog.
            return Authentication.SEND_SUCCESS;
        }
        if (authStatus == AuthStatus.FAILURE) {
            HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return Authentication.SEND_FAILURE;
        }
        // should not happen
        throw new IllegalStateException("No AuthStatus returned");
    } catch (IOException | AuthException e) {
        throw new ServerAuthException(e);
    }
}
Also used : HttpSession(javax.servlet.http.HttpSession) UserIdentity(org.eclipse.jetty.server.UserIdentity) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthException(javax.security.auth.message.AuthException) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) SessionAuthentication(org.eclipse.jetty.security.authentication.SessionAuthentication) IOException(java.io.IOException) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) UserAuthentication(org.eclipse.jetty.security.UserAuthentication) Subject(javax.security.auth.Subject) ServerAuthContext(javax.security.auth.message.config.ServerAuthContext) HttpServletRequest(javax.servlet.http.HttpServletRequest) CallerPrincipalCallback(javax.security.auth.message.callback.CallerPrincipalCallback) GroupPrincipalCallback(javax.security.auth.message.callback.GroupPrincipalCallback) AuthStatus(javax.security.auth.message.AuthStatus) DeferredAuthentication(org.eclipse.jetty.security.authentication.DeferredAuthentication) SessionAuthentication(org.eclipse.jetty.security.authentication.SessionAuthentication) UserAuthentication(org.eclipse.jetty.security.UserAuthentication) Authentication(org.eclipse.jetty.server.Authentication) Principal(java.security.Principal)

Example 3 with ServerAuthContext

use of javax.security.auth.message.config.ServerAuthContext in project Payara by payara.

the class RealmAdapter method invokePostAuthenticateDelegate.

/**
 * Post authentication for given request and response.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param context The Context to which client of this class is attached.
 * @exception IOException if an input/output error occurs
 */
@Override
public boolean invokePostAuthenticateDelegate(HttpRequest request, HttpResponse response, Context context) throws IOException {
    boolean result = false;
    ServerAuthContext serverAuthContext = null;
    try {
        if (httpServletHelper != null) {
            HttpServletRequest req = (HttpServletRequest) request.getRequest();
            MessageInfo messageInfo = (MessageInfo) req.getAttribute(MESSAGE_INFO);
            if (messageInfo != null) {
                // JSR 196 is enabled for this application
                serverAuthContext = (ServerAuthContext) messageInfo.getMap().get(SERVER_AUTH_CONTEXT);
                if (serverAuthContext != null) {
                    try {
                        context.fireContainerEvent(BEFORE_POST_AUTHENTICATION, null);
                        result = SUCCESS.equals(serverAuthContext.secureResponse(messageInfo, null));
                    } finally {
                        context.fireContainerEvent(AFTER_POST_AUTHENTICATION, null);
                    }
                }
            }
        }
    } catch (AuthException ex) {
        throw new IOException(ex);
    } finally {
        if (httpServletHelper != null && serverAuthContext != null) {
            if (request instanceof HttpRequestWrapper) {
                request.removeNote(WRAPPED_REQUEST);
            }
            if (response instanceof HttpResponseWrapper) {
                request.removeNote(WRAPPED_RESPONSE);
            }
        }
    }
    return result;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthException(javax.security.auth.message.AuthException) IOException(java.io.IOException) ServerAuthContext(javax.security.auth.message.config.ServerAuthContext) MessageInfo(javax.security.auth.message.MessageInfo)

Example 4 with ServerAuthContext

use of javax.security.auth.message.config.ServerAuthContext in project Payara by payara.

the class RealmAdapter method validate.

private boolean validate(HttpRequest request, HttpResponse response, LoginConfig config, Authenticator authenticator, boolean calledFromAuthenticate) throws IOException {
    HttpServletRequest servletRequest = (HttpServletRequest) request.getRequest();
    HttpServletResponse servletResponse = (HttpServletResponse) response.getResponse();
    Subject subject = new Subject();
    MessageInfo messageInfo = new HttpMessageInfo(servletRequest, servletResponse);
    boolean isValidateSuccess = false;
    boolean isMandatory = true;
    try {
        isMandatory = !getWebSecurityManager(true).permitAll(servletRequest);
        // Issue - 9578 - produce user challenge if call originates from HttpServletRequest.authenticate
        if (isMandatory || calledFromAuthenticate) {
            setMandatory(messageInfo);
        }
        ServerAuthContext authContext = getServerAuthContext(messageInfo);
        // Call the JASPIC ServerAuthContext which should eventually call the ServerAuthModule (SAM)
        // Notice a null is passed in as the service subject
        // Additionally notice we only care about SUCCESS being returned or not and ignore
        // all other JASPIC AuthStatus values.
        isValidateSuccess = SUCCESS.equals(authContext.validateRequest(messageInfo, subject, null));
        if (isValidateSuccess) {
            // store it only if validateRequest = true
            storeInRequest(servletRequest, messageInfo, authContext);
        }
    } catch (AuthException ae) {
        logger.log(WARNING, "JMAC: http msg authentication fail", ae);
        servletResponse.setStatus(SC_INTERNAL_SERVER_ERROR);
    } catch (RuntimeException e) {
        logger.log(WARNING, "JMAC: Exception during validateRequest", e);
        servletResponse.sendError(SC_INTERNAL_SERVER_ERROR);
    }
    if (isValidateSuccess) {
        Set<Principal> principalSet = subject.getPrincipals();
        // Must be at least one new principal to establish non-default security context
        if (hasNewPrincipal(principalSet)) {
            SecurityContext securityContext = new SecurityContext(subject);
            // Assuming no null principal here
            Principal callerPrincipal = securityContext.getCallerPrincipal();
            WebPrincipal webPrincipal = new WebPrincipal(callerPrincipal, securityContext);
            // TODO: check Java SE SecurityManager access
            SecurityContext.setCurrent(securityContext);
            try {
                String authType = getAuthType(messageInfo, config);
                if (shouldRegisterSession(messageInfo)) {
                    new AuthenticatorProxy(authenticator, webPrincipal, authType).authenticate(request, response, config);
                } else {
                    request.setAuthType(authType == null ? PROXY_AUTH_TYPE : authType);
                    request.setUserPrincipal(webPrincipal);
                }
            } catch (LifecycleException le) {
                logger.log(SEVERE, "[Web-Security] unable to register session", le);
            }
        } else {
            // GLASSFISH-20930. Set null for the case when SAM does not indicate that it needs the session
            if (hasRequestPrincipal(messageInfo)) {
                request.setUserPrincipal(null);
                request.setAuthType(null);
            }
            // If authentication is mandatory, we must have a non-anonymous principal
            if (isMandatory) {
                isValidateSuccess = false;
            }
        }
        if (isValidateSuccess) {
            // Check if the SAM instructed us to wrap the request and response
            HttpServletRequest wrappedServletRequest = (HttpServletRequest) messageInfo.getRequestMessage();
            if (wrappedServletRequest != servletRequest) {
                request.setNote(WRAPPED_REQUEST, new HttpRequestWrapper(request, wrappedServletRequest));
            }
            HttpServletResponse wrappedServletResponse = (HttpServletResponse) messageInfo.getResponseMessage();
            if (wrappedServletResponse != servletResponse) {
                request.setNote(WRAPPED_RESPONSE, new HttpResponseWrapper(response, wrappedServletResponse));
            }
        }
    }
    return isValidateSuccess;
}
Also used : LifecycleException(org.apache.catalina.LifecycleException) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthException(javax.security.auth.message.AuthException) Subject(javax.security.auth.Subject) MessageInfo(javax.security.auth.message.MessageInfo) ServerAuthContext(javax.security.auth.message.config.ServerAuthContext) HttpServletRequest(javax.servlet.http.HttpServletRequest) SecurityContext(com.sun.enterprise.security.SecurityContext) WebPrincipal(com.sun.enterprise.security.web.integration.WebPrincipal) WebPrincipal(com.sun.enterprise.security.web.integration.WebPrincipal) Principal(java.security.Principal)

Example 5 with ServerAuthContext

use of javax.security.auth.message.config.ServerAuthContext in project Payara by payara.

the class CommonServerSecurityPipe method processRequest.

private Packet processRequest(Packet request) throws Exception {
    AuthStatus status = AuthStatus.SUCCESS;
    PacketMessageInfo info = new PacketMapMessageInfo(request, new Packet());
    // XXX at this time, we expect the server subject to be null
    Subject serverSubject = (Subject) request.invocationProperties.get(PipeConstants.SERVER_SUBJECT);
    // could change the request packet
    ServerAuthContext sAC = helper.getServerAuthContext(info, serverSubject);
    Subject clientSubject = getClientSubject(request);
    final Packet validatedRequest;
    try {
        if (sAC != null) {
            // client subject must not be null
            // and when return status is SUCCESS, module
            // must have called handler.handle(CallerPrincipalCallback)
            status = sAC.validateRequest(info, clientSubject, serverSubject);
        }
    } catch (Exception e) {
        _logger.log(Level.SEVERE, LogUtils.ERROR_REQUEST_VALIDATION, e);
        WebServiceException wse = new WebServiceException(localStrings.getLocalString("enterprise.webservice.cantValidateRequest", "Cannot validate request for {0}", new Object[] { helper.getModelName() }), e);
        // set status for audit
        status = AuthStatus.SEND_FAILURE;
        // if unable to determine if two-way will return empty response
        return helper.getFaultResponse(info.getRequestPacket(), info.getResponsePacket(), wse);
    } finally {
        validatedRequest = info.getRequestPacket();
        helper.auditInvocation(validatedRequest, status);
    }
    Packet response = null;
    if (status == AuthStatus.SUCCESS) {
        boolean authorized = false;
        try {
            helper.authorize(validatedRequest);
            authorized = true;
        } catch (Exception e) {
            // not authorized, construct fault and proceded
            response = helper.getFaultResponse(validatedRequest, info.getResponsePacket(), e);
        }
        if (authorized) {
            // only do doAdPriv if SecurityManager is in effect
            if (System.getSecurityManager() == null) {
                try {
                    // proceed to invoke the endpoint
                    response = next.process(validatedRequest);
                } catch (Exception e) {
                    _logger.log(Level.SEVERE, LogUtils.NEXT_PIPE, e);
                    response = helper.getFaultResponse(validatedRequest, info.getResponsePacket(), e);
                }
            } else {
                try {
                    response = (Packet) Subject.doAsPrivileged(clientSubject, new PrivilegedExceptionAction() {

                        @Override
                        public Object run() throws Exception {
                            // proceed to invoke the endpoint
                            return next.process(validatedRequest);
                        }
                    }, null);
                } catch (PrivilegedActionException pae) {
                    Throwable cause = pae.getCause();
                    _logger.log(Level.SEVERE, LogUtils.NEXT_PIPE, cause);
                    response = helper.getFaultResponse(validatedRequest, info.getResponsePacket(), cause);
                }
            }
        }
        // pipes are not supposed to return a null response packet
        if (response == null) {
            WebServiceException wse = new WebServiceException(localStrings.getLocalString("enterprise.webservice.nullResponsePacket", "Invocation of Service {0} returned null response packet", new Object[] { helper.getModelName() }));
            response = helper.getFaultResponse(validatedRequest, info.getResponsePacket(), wse);
            _logger.log(Level.SEVERE, LogUtils.EXCEPTION_THROWN, wse);
        }
        // secure response, including if it is a fault
        if (sAC != null && response.getMessage() != null) {
            info.setResponsePacket(response);
            response = processResponse(info, sAC, serverSubject);
        }
    } else {
        // validateRequest did not return success
        if (_logger.isLoggable(Level.FINE)) {
            _logger.log(Level.FINE, "ws.status_validate_request", status);
        }
        // even for one-way mep, may return response with non-empty message
        response = info.getResponsePacket();
    }
    return response;
}
Also used : Packet(com.sun.xml.ws.api.message.Packet) WebServiceException(javax.xml.ws.WebServiceException) PrivilegedActionException(java.security.PrivilegedActionException) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) Subject(javax.security.auth.Subject) PrivilegedActionException(java.security.PrivilegedActionException) AuthException(javax.security.auth.message.AuthException) WebServiceException(javax.xml.ws.WebServiceException) ServerAuthContext(javax.security.auth.message.config.ServerAuthContext) PacketMapMessageInfo(com.sun.enterprise.security.jauth.jaspic.provider.PacketMapMessageInfo) AuthStatus(javax.security.auth.message.AuthStatus) PacketMessageInfo(com.sun.enterprise.security.jauth.jaspic.provider.PacketMessageInfo)

Aggregations

ServerAuthContext (javax.security.auth.message.config.ServerAuthContext)13 AuthException (javax.security.auth.message.AuthException)9 Subject (javax.security.auth.Subject)8 MessageInfo (javax.security.auth.message.MessageInfo)6 HttpServletRequest (javax.servlet.http.HttpServletRequest)6 AuthStatus (javax.security.auth.message.AuthStatus)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 HttpMessageInfo (com.sun.jaspic.config.servlet.HttpMessageInfo)3 IOException (java.io.IOException)3 ServerAuthConfig (javax.security.auth.message.config.ServerAuthConfig)3 SecurityContext (com.sun.enterprise.security.SecurityContext)2 PacketMapMessageInfo (com.sun.enterprise.security.jauth.jaspic.provider.PacketMapMessageInfo)2 PacketMessageInfo (com.sun.enterprise.security.jauth.jaspic.provider.PacketMessageInfo)2 Packet (com.sun.xml.ws.api.message.Packet)2 Principal (java.security.Principal)2 PrivilegedActionException (java.security.PrivilegedActionException)2 Properties (java.util.Properties)2 AuthConfigFactory (javax.security.auth.message.config.AuthConfigFactory)2 AuthConfigProvider (javax.security.auth.message.config.AuthConfigProvider)2 WebServiceException (javax.xml.ws.WebServiceException)2