Search in sources :

Example 1 with WebPrincipal

use of com.sun.enterprise.security.web.integration.WebPrincipal in project Payara by payara.

the class WebProgrammaticLoginImpl method login.

/**
 * Login and set up principal in request and session. This implements programmatic login for servlets.
 *
 * <P>
 * Due to a number of bugs in RI the security context is not shared between web container and ejb container. In order
 * for an identity established by programmatic login to be known to both containers, it needs to be set not only in the
 * security context but also in the current request and, if applicable, the session object. If a session does not exist
 * this method does not create one.
 *
 * <P>
 * See bugs 4646134, 4688449 and other referenced bugs for more background.
 *
 * <P>
 * Note also that this login does not hook up into SSO.
 *
 * @param user User name to login.
 * @param password User password.
 * @param request HTTP request object provided by caller application. It should be an instance of HttpRequestFacade.
 * @param response HTTP response object provided by called application. It should be an instance of HttpServletResponse.
 * This is not used currently.
 * @param realm the realm name to be authenticated to. If the realm is null, authentication takes place in default realm
 * @returns A Boolean object; true if login succeeded, false otherwise.
 * @see com.sun.enterprise.security.ee.auth.login.ProgrammaticLogin
 * @throws Exception on login failure.
 */
@Override
public Boolean login(String user, char[] password, String realm, HttpServletRequest request, HttpServletResponse response) {
    // Need real request object not facade
    Request req = getUnwrappedCoyoteRequest(request);
    if (req == null) {
        return Boolean.valueOf(false);
    }
    // Try to login - this will set up security context on success
    LoginContextDriver.login(user, password, realm);
    // Create a WebPrincipal for tomcat and store in current request
    // This will allow programmatic authorization later in this request
    // to work as expected.
    SecurityContext secCtx = SecurityContext.getCurrent();
    // since login succeeded above
    assert (secCtx != null);
    WebPrincipal principal = new WebPrincipal(user, password, secCtx);
    req.setUserPrincipal(principal);
    req.setAuthType(WEBAUTH_PROGRAMMATIC);
    if (logger.isLoggable(Level.FINE)) {
        logger.log(Level.FINE, "Programmatic login set principal in http request to: " + user);
    }
    // Try to retrieve a Session object (not the facade); if it exists
    // store the principal there as well. This will allow web container
    // authorization to work in subsequent requests in this session.
    Session realSession = getSession(req);
    if (realSession != null) {
        realSession.setPrincipal(principal);
        realSession.setAuthType(WEBAUTH_PROGRAMMATIC);
        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE, "Programmatic login set principal in session.");
        }
    } else {
        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE, "Programmatic login: No session available.");
        }
    }
    return Boolean.valueOf(true);
}
Also used : Request(org.apache.catalina.connector.Request) ServletRequest(javax.servlet.ServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) SecurityContext(com.sun.enterprise.security.SecurityContext) WebPrincipal(com.sun.enterprise.security.web.integration.WebPrincipal) HttpSession(javax.servlet.http.HttpSession) Session(org.apache.catalina.Session)

Example 2 with WebPrincipal

use of com.sun.enterprise.security.web.integration.WebPrincipal in project Payara by payara.

the class SecurityServiceImpl method doSecurity.

public boolean doSecurity(HttpServletRequest hreq, EjbRuntimeEndpointInfo epInfo, String realmName, WebServiceContextImpl context) {
    // BUG2263 - Clear the value of UserPrincipal from previous request
    // If authentication succeeds, the proper value will be set later in
    // this method.
    boolean authenticated = false;
    try {
        // calling this for a GET request WSDL query etc can cause problems
        String method = hreq.getMethod();
        if (context != null) {
            context.setUserPrincipal(null);
        }
        WebServiceEndpoint endpoint = epInfo.getEndpoint();
        String rawAuthInfo = hreq.getHeader(AUTHORIZATION_HEADER);
        if (method.equals("GET") || !endpoint.hasAuthMethod()) {
            // if (method.equals("GET") || rawAuthInfo == null) {
            authenticated = true;
            return true;
        }
        WebPrincipal webPrincipal = null;
        String endpointName = endpoint.getEndpointName();
        if (endpoint.hasBasicAuth() || rawAuthInfo != null) {
            // String rawAuthInfo = hreq.getHeader(AUTHORIZATION_HEADER);
            if (rawAuthInfo == null) {
                sendAuthenticationEvents(false, hreq.getRequestURI(), null);
                authenticated = false;
                return false;
            }
            List<Object> usernamePassword = parseUsernameAndPassword(rawAuthInfo);
            if (usernamePassword != null) {
                webPrincipal = new WebPrincipal((String) usernamePassword.get(0), (char[]) usernamePassword.get(1), SecurityContext.init());
            } else {
                _logger.log(Level.WARNING, LogUtils.BASIC_AUTH_ERROR, endpointName);
            }
        } else {
            // org.apache.coyote.request.X509Certificate
            X509Certificate[] certs = (X509Certificate[]) hreq.getAttribute(Globals.CERTIFICATES_ATTR);
            if ((certs == null) || (certs.length < 1)) {
                certs = (X509Certificate[]) hreq.getAttribute(Globals.SSL_CERTIFICATE_ATTR);
            }
            if (certs != null) {
                webPrincipal = new WebPrincipal(certs, SecurityContext.init());
            } else {
                _logger.log(Level.WARNING, LogUtils.CLIENT_CERT_ERROR, endpointName);
            }
        }
        if (webPrincipal == null) {
            sendAuthenticationEvents(false, hreq.getRequestURI(), null);
            return authenticated;
        }
        RealmAdapter ra = new RealmAdapter(realmName, endpoint.getBundleDescriptor().getModuleID());
        authenticated = ra.authenticate(webPrincipal);
        if (authenticated == false) {
            sendAuthenticationEvents(false, hreq.getRequestURI(), webPrincipal);
            if (_logger.isLoggable(Level.FINE)) {
                _logger.fine("authentication failed for " + endpointName);
            }
        } else {
            sendAuthenticationEvents(true, hreq.getRequestURI(), webPrincipal);
        }
        if (epInfo instanceof Ejb2RuntimeEndpointInfo) {
            // For JAXRPC based EJb endpoints the rest of the steps are not needed
            return authenticated;
        }
        // Setting if userPrincipal in WSCtxt applies for JAXWS endpoints only
        epInfo.prepareInvocation(false);
        WebServiceContextImpl ctxt = (WebServiceContextImpl) epInfo.getWebServiceContext();
        ctxt.setUserPrincipal(webPrincipal);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (auditManager != null && auditManager.isAuditOn()) {
            auditManager.ejbAsWebServiceInvocation(epInfo.getEndpoint().getEndpointName(), authenticated);
        }
    }
    return authenticated;
}
Also used : Ejb2RuntimeEndpointInfo(org.glassfish.webservices.Ejb2RuntimeEndpointInfo) X509Certificate(java.security.cert.X509Certificate) AuthException(com.sun.enterprise.security.jauth.AuthException) WebServiceEndpoint(com.sun.enterprise.deployment.WebServiceEndpoint) RealmAdapter(com.sun.web.security.RealmAdapter) WebPrincipal(com.sun.enterprise.security.web.integration.WebPrincipal) WebServiceContextImpl(org.glassfish.webservices.WebServiceContextImpl)

Example 3 with WebPrincipal

use of com.sun.enterprise.security.web.integration.WebPrincipal in project Payara by payara.

the class RealmAdapter method authenticate.

/**
 * This HttpServletRequest authenticate variant is primarily used by the DigestAuthenticator
 */
@Override
public Principal authenticate(HttpServletRequest httpServletRequest) {
    try {
        DigestAlgorithmParameter[] params = DigestParameterGenerator.getInstance(HTTP_DIGEST).generateParameters(new HttpAlgorithmParameterImpl(httpServletRequest));
        Key key = null;
        if (cnonces == null) {
            String appName = webDescriptor.getApplication().getAppName();
            synchronized (this) {
                if (haCNonceCacheMap == null) {
                    haCNonceCacheMap = appCNonceCacheMapProvider.get();
                }
                if (haCNonceCacheMap != null) {
                    // get the initialized HA CNonceCache
                    cnonces = haCNonceCacheMap.get(appName);
                }
                if (cnonces == null) {
                    if (cNonceCacheFactory == null) {
                        cNonceCacheFactory = cNonceCacheFactoryProvider.get();
                    }
                    // create a Non-HA CNonce Cache
                    cnonces = cNonceCacheFactory.createCNonceCache(webDescriptor.getApplication().getAppName(), null, null, null);
                }
            }
        }
        String nc = null;
        String cnonce = null;
        for (DigestAlgorithmParameter p : params) {
            if (p instanceof NestedDigestAlgoParamImpl) {
                NestedDigestAlgoParamImpl np = (NestedDigestAlgoParamImpl) p;
                DigestAlgorithmParameter[] nps = (DigestAlgorithmParameter[]) np.getNestedParams();
                for (DigestAlgorithmParameter p1 : nps) {
                    if ("cnonce".equals(p1.getName())) {
                        cnonce = new String(p1.getValue());
                    } else if ("nc".equals(p1.getName())) {
                        nc = new String(p1.getValue());
                    }
                    if (cnonce != null && nc != null) {
                        break;
                    }
                }
                if (cnonce != null && nc != null) {
                    break;
                }
            }
            if ("cnonce".equals(p.getName())) {
                cnonce = new String(p.getValue());
            } else if ("nc".equals(p.getName())) {
                nc = new String(p.getValue());
            }
        }
        long count;
        long currentTime = System.currentTimeMillis();
        try {
            count = Long.parseLong(nc, 16);
        } catch (NumberFormatException nfe) {
            throw new RuntimeException(nfe);
        }
        NonceInfo info;
        synchronized (cnonces) {
            info = cnonces.get(cnonce);
        }
        if (info == null) {
            info = new NonceInfo();
        } else {
            if (count <= info.getCount()) {
                throw new RuntimeException("Invalid Request : Possible Replay Attack detected ?");
            }
        }
        info.setCount(count);
        info.setTimestamp(currentTime);
        synchronized (cnonces) {
            cnonces.put(cnonce, info);
        }
        for (int i = 0; i < params.length; i++) {
            DigestAlgorithmParameter dap = params[i];
            if (A1.equals(dap.getName()) && (dap instanceof Key)) {
                key = (Key) dap;
                break;
            }
        }
        if (key != null) {
            DigestCredentials creds = new DigestCredentials(realmName, key.getUsername(), params);
            LoginContextDriver.login(creds);
            return new WebPrincipal(creds.getUserName(), (char[]) null, SecurityContext.getCurrent());
        }
        throw new RuntimeException("No key found in parameters");
    } catch (Exception le) {
        if (logger.isLoggable(WARNING)) {
            logger.log(WARNING, "web.login.failed", le.toString());
        }
    }
    return null;
}
Also used : DigestCredentials(com.sun.enterprise.security.auth.login.DigestCredentials) DigestAlgorithmParameter(com.sun.enterprise.security.auth.digest.api.DigestAlgorithmParameter) SecurityConstraint(org.apache.catalina.deploy.SecurityConstraint) LifecycleException(org.apache.catalina.LifecycleException) IOException(java.io.IOException) AuthException(javax.security.auth.message.AuthException) ProtocolException(java.net.ProtocolException) MalformedURLException(java.net.MalformedURLException) HttpAlgorithmParameterImpl(com.sun.enterprise.security.auth.digest.impl.HttpAlgorithmParameterImpl) NonceInfo(org.glassfish.security.common.NonceInfo) NestedDigestAlgoParamImpl(com.sun.enterprise.security.auth.digest.impl.NestedDigestAlgoParamImpl) WebPrincipal(com.sun.enterprise.security.web.integration.WebPrincipal) Key(com.sun.enterprise.security.auth.digest.api.Key)

Example 4 with WebPrincipal

use of com.sun.enterprise.security.web.integration.WebPrincipal 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 WebPrincipal

use of com.sun.enterprise.security.web.integration.WebPrincipal in project Payara by payara.

the class RealmAdapter method getSecurityContextForPrincipal.

// Moved from J2EEInstanceListener.java
private SecurityContext getSecurityContextForPrincipal(final Principal p) {
    if (p == null) {
        return null;
    } else if (p instanceof WebPrincipal) {
        return ((WebPrincipal) p).getSecurityContext();
    } else {
        return AccessController.doPrivileged(new PrivilegedAction<SecurityContext>() {

            @Override
            public SecurityContext run() {
                Subject s = new Subject();
                s.getPrincipals().add(p);
                return new SecurityContext(p.getName(), s);
            }
        });
    }
}
Also used : PrivilegedAction(java.security.PrivilegedAction) SecurityContext(com.sun.enterprise.security.SecurityContext) WebPrincipal(com.sun.enterprise.security.web.integration.WebPrincipal) Subject(javax.security.auth.Subject)

Aggregations

WebPrincipal (com.sun.enterprise.security.web.integration.WebPrincipal)8 SecurityContext (com.sun.enterprise.security.SecurityContext)6 Principal (java.security.Principal)4 Subject (javax.security.auth.Subject)4 PrivilegedAction (java.security.PrivilegedAction)3 DistinguishedPrincipalCredential (com.sun.enterprise.security.auth.login.DistinguishedPrincipalCredential)2 Iterator (java.util.Iterator)2 AuthException (javax.security.auth.message.AuthException)2 X500Principal (javax.security.auth.x500.X500Principal)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 LifecycleException (org.apache.catalina.LifecycleException)2 WebServiceEndpoint (com.sun.enterprise.deployment.WebServiceEndpoint)1 DigestAlgorithmParameter (com.sun.enterprise.security.auth.digest.api.DigestAlgorithmParameter)1 Key (com.sun.enterprise.security.auth.digest.api.Key)1 HttpAlgorithmParameterImpl (com.sun.enterprise.security.auth.digest.impl.HttpAlgorithmParameterImpl)1 NestedDigestAlgoParamImpl (com.sun.enterprise.security.auth.digest.impl.NestedDigestAlgoParamImpl)1 DigestCredentials (com.sun.enterprise.security.auth.login.DigestCredentials)1 AuthException (com.sun.enterprise.security.jauth.AuthException)1 RealmAdapter (com.sun.web.security.RealmAdapter)1 IOException (java.io.IOException)1