Search in sources :

Example 26 with Status

use of com.sun.identity.saml2.protocol.Status in project OpenAM by OpenRock.

the class AssertionIDRequestUtil method processAssertionIDRequest.

/**
     * This method processes the <code>AssertionIDRequest</code> coming
     * from a requester.
     *
     * @param assertionIDRequest the <code>AssertionIDRequest</code> object
     * @param request the <code>HttpServletRequest</code> object
     * @param response the <code>HttpServletResponse</code> object
     * @param samlAuthorityEntityID entity ID of SAML authority
     * @param role the role of SAML authority
     * @param realm the realm of SAML authority
     * @return the <code>Response</code> object
     * @exception SAML2Exception if the operation is not successful
     */
public static Response processAssertionIDRequest(AssertionIDRequest assertionIDRequest, HttpServletRequest request, HttpServletResponse response, String samlAuthorityEntityID, String role, String realm) throws SAML2Exception {
    try {
        verifyAssertionIDRequest(assertionIDRequest, samlAuthorityEntityID, role, realm);
    } catch (SAML2Exception se) {
        SAML2Utils.debug.error("AssertionIDRequestUtil." + "processAssertionIDRequest:", se);
        return SAML2Utils.getErrorResponse(assertionIDRequest, SAML2Constants.REQUESTER, null, se.getMessage(), samlAuthorityEntityID);
    }
    Issuer issuer = assertionIDRequest.getIssuer();
    String spEntityID = issuer.getValue();
    RoleDescriptorType roled = null;
    try {
        if (SAML2Constants.IDP_ROLE.equals(role)) {
            roled = metaManager.getIDPSSODescriptor(realm, samlAuthorityEntityID);
        } else if (SAML2Constants.AUTHN_AUTH_ROLE.equals(role)) {
            roled = metaManager.getAuthnAuthorityDescriptor(realm, samlAuthorityEntityID);
        } else if (SAML2Constants.ATTR_AUTH_ROLE.equals(role)) {
            roled = metaManager.getAttributeAuthorityDescriptor(realm, samlAuthorityEntityID);
        }
    } catch (SAML2MetaException sme) {
        SAML2Utils.debug.error("AssertionIDRequestUtil." + "processAssertionIDRequest:", sme);
        return SAML2Utils.getErrorResponse(assertionIDRequest, SAML2Constants.RESPONDER, null, sme.getMessage(), samlAuthorityEntityID);
    }
    if (roled == null) {
        return SAML2Utils.getErrorResponse(assertionIDRequest, SAML2Constants.REQUESTER, null, SAML2Utils.bundle.getString("samlAuthorityNotFound"), samlAuthorityEntityID);
    }
    List returnAssertions = null;
    List assertionIDRefs = assertionIDRequest.getAssertionIDRefs();
    for (Iterator iter = assertionIDRefs.iterator(); iter.hasNext(); ) {
        AssertionIDRef assertionIDRef = (AssertionIDRef) iter.next();
        String assertionID = assertionIDRef.getValue();
        Assertion assertion = (Assertion) IDPCache.assertionByIDCache.get(assertionID);
        if ((assertion == null) && (SAML2FailoverUtils.isSAML2FailoverEnabled())) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message("AssertionIDRequestUtil.processAssertionIDRequest: " + "reading assertion from the SAML2 Token Repository using assertionID:" + assertionID);
            }
            String assertionStr = null;
            try {
                assertionStr = (String) SAML2FailoverUtils.retrieveSAML2Token(assertionID);
            } catch (SAML2TokenRepositoryException se) {
                SAML2Utils.debug.error("AssertionIDRequestUtil.processAssertionIDRequest: " + "There was a problem reading assertion from the SAML2 Token Repository using assertionID:" + assertionID, se);
            }
            if (assertionStr != null) {
                assertion = AssertionFactory.getInstance().createAssertion(assertionStr);
            }
        }
        if ((assertion != null) && (assertion.isTimeValid())) {
            if (returnAssertions == null) {
                returnAssertions = new ArrayList();
            }
            returnAssertions.add(assertion);
        }
    }
    ProtocolFactory protocolFactory = ProtocolFactory.getInstance();
    Response samlResp = protocolFactory.createResponse();
    samlResp.setAssertion(returnAssertions);
    samlResp.setID(SAML2Utils.generateID());
    samlResp.setInResponseTo(assertionIDRequest.getID());
    samlResp.setVersion(SAML2Constants.VERSION_2_0);
    samlResp.setIssueInstant(new Date());
    Status status = protocolFactory.createStatus();
    StatusCode statusCode = protocolFactory.createStatusCode();
    statusCode.setValue(SAML2Constants.SUCCESS);
    status.setStatusCode(statusCode);
    samlResp.setStatus(status);
    Issuer respIssuer = AssertionFactory.getInstance().createIssuer();
    respIssuer.setValue(samlAuthorityEntityID);
    samlResp.setIssuer(respIssuer);
    signResponse(samlResp, samlAuthorityEntityID, role, realm, false);
    return samlResp;
}
Also used : Status(com.sun.identity.saml2.protocol.Status) Issuer(com.sun.identity.saml2.assertion.Issuer) AssertionIDRef(com.sun.identity.saml2.assertion.AssertionIDRef) Assertion(com.sun.identity.saml2.assertion.Assertion) ArrayList(java.util.ArrayList) StatusCode(com.sun.identity.saml2.protocol.StatusCode) Date(java.util.Date) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) ProtocolFactory(com.sun.identity.saml2.protocol.ProtocolFactory) Response(com.sun.identity.saml2.protocol.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) RoleDescriptorType(com.sun.identity.saml2.jaxb.metadata.RoleDescriptorType) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException)

Example 27 with Status

use of com.sun.identity.saml2.protocol.Status in project OpenAM by OpenRock.

the class SPACSUtils method getResponseFromSOAP.

/**
     * Obtains <code>SAML Response</code> from <code>SOAPBody</code>.
     * Used by Artifact profile.
     */
private static Response getResponseFromSOAP(SOAPMessage resMsg, ArtifactResolve resolve, HttpServletRequest request, HttpServletResponse response, String idpEntityID, IDPSSODescriptorElement idp, String orgName, String hostEntityId, SAML2MetaManager sm) throws SAML2Exception, IOException {
    String method = "SPACSUtils.getResponseFromSOAP:";
    Element resElem = null;
    try {
        resElem = SOAPCommunicator.getInstance().getSamlpElement(resMsg, "ArtifactResponse");
    } catch (SAML2Exception se) {
        String[] data = { idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.SOAP_ERROR, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "soapError", se.getMessage());
        throw se;
    }
    ArtifactResponse artiResp = null;
    try {
        artiResp = ProtocolFactory.getInstance().createArtifactResponse(resElem);
    } catch (SAML2Exception se) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(method + "Couldn't create " + "ArtifactResponse:", se);
        }
        String[] data = { idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.CANNOT_INSTANTIATE_ARTIFACT_RESPONSE, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "failedToCreateArtifactResponse", se.getMessage());
        throw se;
    }
    if (artiResp == null) {
        String[] data = { idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.MISSING_ARTIFACT_RESPONSE, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "missingArtifactResponse", SAML2Utils.bundle.getString("missingArtifactResponse"));
        throw new SAML2Exception(SAML2Utils.bundle.getString("missingArtifactResponse"));
    } else {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(method + "Received ArtifactResponse:" + artiResp.toXMLString(true, true));
        }
    }
    // verify ArtifactResponse
    String wantArtiRespSigned = getAttributeValueFromSPSSOConfig(orgName, hostEntityId, sm, SAML2Constants.WANT_ARTIFACT_RESPONSE_SIGNED);
    if (wantArtiRespSigned != null && wantArtiRespSigned.equals("true")) {
        Set<X509Certificate> verificationCerts = KeyUtil.getVerificationCerts(idp, idpEntityID, SAML2Constants.IDP_ROLE);
        if (!artiResp.isSigned() || !artiResp.isSignatureValid(verificationCerts)) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(method + "ArtifactResponse's signature is invalid.");
            }
            String[] data = { idpEntityID };
            LogUtil.error(Level.INFO, LogUtil.ARTIFACT_RESPONSE_INVALID_SIGNATURE, data, null);
            SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "invalidSignature", SAML2Utils.bundle.getString("invalidSignature"));
            throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignature"));
        }
    }
    String inResponseTo = artiResp.getInResponseTo();
    if (inResponseTo == null || !inResponseTo.equals(resolve.getID())) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(method + "ArtifactResponse's InResponseTo is invalid.");
        }
        String[] data = { idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.ARTIFACT_RESPONSE_INVALID_INRESPONSETO, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "invalidInResponseTo", SAML2Utils.bundle.getString("invalidInResponseTo"));
        throw new SAML2Exception(SAML2Utils.bundle.getString("invalidInResponseTo"));
    }
    Issuer idpIssuer = artiResp.getIssuer();
    if (idpIssuer == null || !idpIssuer.getValue().equals(idpEntityID)) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(method + "ArtifactResponse's Issuer is invalid.");
        }
        String[] data = { idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.ARTIFACT_RESPONSE_INVALID_ISSUER, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "invalidIssuer", SAML2Utils.bundle.getString("invalidIssuer"));
        throw new SAML2Exception(SAML2Utils.bundle.getString("invalidIssuer"));
    }
    // check time?
    Status status = artiResp.getStatus();
    if (status == null || !status.getStatusCode().getValue().equals(SAML2Constants.SUCCESS)) {
        String statusCode = (status == null) ? "" : status.getStatusCode().getValue();
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(method + "ArtifactResponse's status code is not success." + statusCode);
        }
        String[] data = { idpEntityID, "" };
        if (LogUtil.isErrorLoggable(Level.FINE)) {
            data[1] = statusCode;
        }
        LogUtil.error(Level.INFO, LogUtil.ARTIFACT_RESPONSE_INVALID_STATUS_CODE, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "invalidStatusCode", SAML2Utils.bundle.getString("invalidStatusCode"));
        throw new SAML2Exception(SAML2Utils.bundle.getString("invalidStatusCode"));
    }
    try {
        return ProtocolFactory.getInstance().createResponse(artiResp.getAny());
    } catch (SAML2Exception se) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(method + "couldn't instantiate Response:", se);
        }
        String[] data = { idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.CANNOT_INSTANTIATE_RESPONSE_ARTIFACT, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "failedToCreateResponse", se.getMessage());
        throw se;
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Status(com.sun.identity.saml2.protocol.Status) Issuer(com.sun.identity.saml2.assertion.Issuer) ArtifactResponse(com.sun.identity.saml2.protocol.ArtifactResponse) SPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.SPSSOConfigElement) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) IDPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.IDPSSOConfigElement) ArtifactResolutionServiceElement(com.sun.identity.saml2.jaxb.metadata.ArtifactResolutionServiceElement) Element(org.w3c.dom.Element) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement) X509Certificate(java.security.cert.X509Certificate)

Example 28 with Status

use of com.sun.identity.saml2.protocol.Status in project OpenAM by OpenRock.

the class IDPSingleLogout method sendLastResponse.

private static boolean sendLastResponse(IDPSession idpSession, LogoutResponse logoutRes, HttpServletRequest request, HttpServletResponse response, String idpSessionIndex, Object session, String realm, String idpEntityID, String relayState) throws SAML2Exception, SessionException, SAML2MetaException {
    String binding;
    //resetting the binding to the original value so the response is sent back with the correct binding
    binding = idpSession.getOriginatingLogoutRequestBinding();
    String originatingRequestID = idpSession.getOriginatingLogoutRequestID();
    String originatingLogoutSPEntityID = idpSession.getOriginatingLogoutSPEntityID();
    if (originatingRequestID == null) {
        // this is IDP initiated SLO
        if (idpSession.getLogoutAll()) {
            String userID = sessionProvider.getPrincipalName(idpSession.getSession());
            destroyAllTokenForUser(userID, request, response);
        } else {
            IDPCache.idpSessionsByIndices.remove(idpSessionIndex);
            if (agent != null && agent.isRunning() && saml2Svc != null) {
                saml2Svc.setIdpSessionCount((long) IDPCache.idpSessionsByIndices.size());
            }
            try {
                if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
                    SAML2FailoverUtils.deleteSAML2Token(idpSessionIndex);
                }
            } catch (SAML2TokenRepositoryException se) {
                debug.error("IDPSingleLogout.sendLastResponse: Error while deleting token from " + "SAML2 Token Repository for idpSessionIndex:" + idpSessionIndex, se);
            }
            IDPCache.authnContextCache.remove(idpSessionIndex);
            if (!MultiProtocolUtils.isMultipleProtocolSession(idpSession.getSession(), SingleLogoutManager.SAML2)) {
                sessionProvider.invalidateSession(idpSession.getSession(), request, response);
            } else {
                MultiProtocolUtils.removeFederationProtocol(idpSession.getSession(), SingleLogoutManager.SAML2);
                // call Multi-Federation protocol SingleLogoutManager
                SingleLogoutManager sloManager = SingleLogoutManager.getInstance();
                Set<Object> set = new HashSet<Object>(1);
                set.add(session);
                SessionProvider provider = SessionManager.getProvider();
                String uid = provider.getPrincipalName(session);
                debug.message("IDPSingleLogout.sendLastResponse: MP/Http");
                int retStatus = SingleLogoutManager.LOGOUT_SUCCEEDED_STATUS;
                try {
                    retStatus = sloManager.doIDPSingleLogout(set, uid, request, response, false, true, SingleLogoutManager.SAML2, realm, idpEntityID, originatingLogoutSPEntityID, relayState, null, null, getLogoutStatus(logoutRes));
                } catch (SAML2Exception ex) {
                    throw ex;
                } catch (Exception ex) {
                    debug.error("IDPSIngleLogout.sendLastResponse: MP/IDP initiated HTTP", ex);
                    throw new SAML2Exception(ex.getMessage());
                }
                if (retStatus == SingleLogoutManager.LOGOUT_REDIRECTED_STATUS) {
                    return true;
                }
            }
        }
        debug.message("IDP initiated SLO Success");
        return false;
    }
    List<SingleLogoutServiceElement> slosList = getSPSLOServiceEndpoints(realm, originatingLogoutSPEntityID);
    String location = LogoutUtil.getSLOResponseServiceLocation(slosList, binding);
    if (location == null || location.isEmpty()) {
        location = LogoutUtil.getSLOServiceLocation(slosList, binding);
        if (location == null || location.length() == 0) {
            debug.error("Unable to find the IDP's single logout response service with the HTTP-Redirect binding");
            throw new SAML2Exception(SAML2Utils.bundle.getString("sloResponseServiceLocationNotfound"));
        } else {
            if (debug.messageEnabled()) {
                debug.message("SP's single logout response service location = " + location);
            }
        }
    } else {
        if (debug.messageEnabled()) {
            debug.message("IDP's single logout response service location = " + location);
        }
    }
    Status status = destroyTokenAndGenerateStatus(idpSessionIndex, idpSession.getSession(), request, response, true);
    //here we are providing null for remote entity, because it's an unused variable in the method...
    logoutRes = LogoutUtil.generateResponse(status, originatingRequestID, SAML2Utils.createIssuer(idpEntityID), realm, SAML2Constants.IDP_ROLE, null);
    if (logoutRes != null) {
        logoutRes.setDestination(XMLUtils.escapeSpecialCharacters(location));
        IDPCache.idpSessionsByIndices.remove(idpSessionIndex);
        if (agent != null && agent.isRunning() && saml2Svc != null) {
            saml2Svc.setIdpSessionCount((long) IDPCache.idpSessionsByIndices.size());
        }
        try {
            if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
                SAML2FailoverUtils.deleteSAML2Token(idpSessionIndex);
            }
        } catch (SAML2TokenRepositoryException se) {
            debug.error("IDPSingleLogout.sendLastResponse: Error while deleting token from " + "SAML2 Token Repository for idpSessionIndex:" + idpSessionIndex, se);
        }
        IDPCache.authnContextCache.remove(idpSessionIndex);
        // call multi-federation protocol processing
        // this is the SP initiated HTTP binding case
        boolean isMultiProtocolSession = false;
        int retStatus = SingleLogoutManager.LOGOUT_SUCCEEDED_STATUS;
        try {
            SessionProvider provider = SessionManager.getProvider();
            session = idpSession.getSession();
            if (session != null && provider.isValid(session) && MultiProtocolUtils.isMultipleProtocolSession(session, SingleLogoutManager.SAML2)) {
                isMultiProtocolSession = true;
                // call Multi-Federation protocol SingleLogoutManager
                SingleLogoutManager sloManager = SingleLogoutManager.getInstance();
                Set set = new HashSet();
                set.add(session);
                String uid = provider.getPrincipalName(session);
                debug.message("IDPSingleLogout.sendLastResponse: MP/Http");
                retStatus = sloManager.doIDPSingleLogout(set, uid, request, response, false, true, SingleLogoutManager.SAML2, realm, idpEntityID, originatingLogoutSPEntityID, relayState, null, logoutRes.toXMLString(), getLogoutStatus(logoutRes));
            }
        } catch (SessionException e) {
            // ignore as session might not be valid
            debug.message("IDPSingleLogout.sendLastResponse: session", e);
        } catch (Exception e) {
            debug.message("IDPSingleLogout.sendLastResponse: MP2", e);
            retStatus = SingleLogoutManager.LOGOUT_FAILED_STATUS;
        }
        if (!isMultiProtocolSession || (retStatus != SingleLogoutManager.LOGOUT_REDIRECTED_STATUS)) {
            logoutRes = updateLogoutResponse(logoutRes, retStatus);
            LogoutUtil.sendSLOResponse(response, request, logoutRes, location, relayState, realm, idpEntityID, SAML2Constants.IDP_ROLE, originatingLogoutSPEntityID, binding);
            return true;
        } else {
            return false;
        }
    }
    IDPCache.idpSessionsByIndices.remove(idpSessionIndex);
    if (agent != null && agent.isRunning() && saml2Svc != null) {
        saml2Svc.setIdpSessionCount((long) IDPCache.idpSessionsByIndices.size());
    }
    try {
        if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
            SAML2FailoverUtils.deleteSAML2Token(idpSessionIndex);
        }
    } catch (SAML2TokenRepositoryException se) {
        debug.error("IDPSingleLogout.sendLastResponse: Error while deleting token from " + "SAML2 Token Repository for idpSessionIndex:" + idpSessionIndex, se);
    }
    IDPCache.authnContextCache.remove(idpSessionIndex);
    return false;
}
Also used : Status(com.sun.identity.saml2.protocol.Status) HashSet(java.util.HashSet) Set(java.util.Set) SessionException(com.sun.identity.plugin.session.SessionException) SessionException(com.sun.identity.plugin.session.SessionException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) IOException(java.io.IOException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) SingleLogoutManager(com.sun.identity.multiprotocol.SingleLogoutManager) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) SingleLogoutServiceElement(com.sun.identity.saml2.jaxb.metadata.SingleLogoutServiceElement) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) HashSet(java.util.HashSet) SessionProvider(com.sun.identity.plugin.session.SessionProvider)

Example 29 with Status

use of com.sun.identity.saml2.protocol.Status in project OpenAM by OpenRock.

the class IDPSingleLogout method processLogoutRequest.

/**
     * Gets and processes the Single <code>LogoutRequest</code> from SP.
     *
     * @param request the HttpServletRequest.
     * @param response the HttpServletResponse.
     * @param out the print writer for writing out presentation
     * @param samlRequest <code>LogoutRequest</code> in the
     *          XML string format.
     * @param relayState the target URL on successful
     * <code>LogoutRequest</code>.
     * @throws SAML2Exception if error processing
     *          <code>LogoutRequest</code>.
     * @throws SessionException if error processing
     *          <code>LogoutRequest</code>.
     */
public static void processLogoutRequest(HttpServletRequest request, HttpServletResponse response, PrintWriter out, String samlRequest, String relayState) throws SAML2Exception, SessionException {
    String classMethod = "IDPSingleLogout.processLogoutRequest : ";
    if (debug.messageEnabled()) {
        debug.message(classMethod + "IDPSingleLogout:processLogoutRequest");
        debug.message(classMethod + "samlRequest : " + samlRequest);
        debug.message(classMethod + "relayState : " + relayState);
    }
    String rmethod = request.getMethod();
    String binding = SAML2Constants.HTTP_REDIRECT;
    if (rmethod.equals("POST")) {
        binding = SAML2Constants.HTTP_POST;
    }
    String metaAlias = SAML2MetaUtils.getMetaAliasByUri(request.getRequestURI());
    String realm = SAML2Utils.getRealm(SAML2MetaUtils.getRealmByMetaAlias(metaAlias));
    String idpEntityID = sm.getEntityByMetaAlias(metaAlias);
    if (!SAML2Utils.isIDPProfileBindingSupported(realm, idpEntityID, SAML2Constants.SLO_SERVICE, binding)) {
        debug.error(classMethod + "SLO service binding " + binding + " is not supported for " + idpEntityID);
        throw new SAML2Exception(SAML2Utils.bundle.getString("unsupportedBinding"));
    }
    LogoutRequest logoutReq = null;
    if (rmethod.equals("POST")) {
        logoutReq = LogoutUtil.getLogoutRequestFromPost(samlRequest, response);
    } else if (rmethod.equals("GET")) {
        String decodedStr = SAML2Utils.decodeFromRedirect(samlRequest);
        if (decodedStr == null) {
            throw new SAML2Exception(SAML2Utils.bundle.getString("nullDecodedStrFromSamlRequest"));
        }
        logoutReq = ProtocolFactory.getInstance().createLogoutRequest(decodedStr);
    }
    if (logoutReq == null) {
        if (debug.messageEnabled()) {
            debug.message("IDPSingleLogout:processLogoutRequest: logoutReq " + "is null");
        }
        return;
    }
    String spEntityID = logoutReq.getIssuer().getValue();
    boolean needToVerify = SAML2Utils.getWantLogoutRequestSigned(realm, idpEntityID, SAML2Constants.IDP_ROLE);
    if (debug.messageEnabled()) {
        debug.message(classMethod + "metaAlias : " + metaAlias);
        debug.message(classMethod + "realm : " + realm);
        debug.message(classMethod + "idpEntityID : " + idpEntityID);
        debug.message(classMethod + "spEntityID : " + spEntityID);
    }
    if (needToVerify) {
        boolean valid = false;
        if (binding.equals(SAML2Constants.HTTP_REDIRECT)) {
            String queryString = request.getQueryString();
            valid = SAML2Utils.verifyQueryString(queryString, realm, SAML2Constants.IDP_ROLE, spEntityID);
        } else {
            valid = LogoutUtil.verifySLORequest(logoutReq, realm, spEntityID, idpEntityID, SAML2Constants.IDP_ROLE);
        }
        if (!valid) {
            debug.error("Invalid signature in SLO Request.");
            throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignInRequest"));
        }
        IDPSSODescriptorElement idpsso = sm.getIDPSSODescriptor(realm, idpEntityID);
        String loc = null;
        if (idpsso != null) {
            List sloList = idpsso.getSingleLogoutService();
            if ((sloList != null) && (!sloList.isEmpty())) {
                loc = LogoutUtil.getSLOResponseServiceLocation(sloList, binding);
                if ((loc == null) || (loc.length() == 0)) {
                    loc = LogoutUtil.getSLOServiceLocation(sloList, binding);
                }
            }
        }
        if (!SAML2Utils.verifyDestination(logoutReq.getDestination(), loc)) {
            throw new SAML2Exception(SAML2Utils.bundle.getString("invalidDestination"));
        }
    }
    // Get the local session, if it does not exist send a succesful
    // Logout Response with a status message of "Already Logout"
    Object session = null;
    try {
        session = sessionProvider.getSession(request);
    } catch (SessionException ssoe) {
        sendAlreadyLogedOutResp(response, request, logoutReq, relayState, realm, idpEntityID, spEntityID, binding);
        return;
    }
    // then send the request to the original server
    if (session != null && !SAML2FailoverUtils.isSAML2FailoverEnabled() && isMisroutedRequest(request, response, out, session)) {
        return;
    } else {
        if (debug.messageEnabled()) {
            debug.message(classMethod + "SAML2 Failover will be attempted. Be sure SFO is " + "properly configured or the attempt will fail");
        }
    }
    LogoutResponse logoutRes = processLogoutRequest(logoutReq, request, response, binding, relayState, idpEntityID, realm, true);
    if (logoutRes == null) {
        // through HTTP_Redirect, nothing to do here
        return;
    }
    // this is the case where there is no more SP session
    // participant
    SingleLogoutServiceElement endpoint = getLogoutResponseEndpoint(realm, spEntityID, binding);
    binding = endpoint.getBinding();
    String location = getResponseLocation(endpoint);
    logoutRes.setDestination(XMLUtils.escapeSpecialCharacters(location));
    // call multi-federation protocol processing
    // this is SP initiated HTTP based single logout
    boolean isMultiProtocolSession = false;
    int retStatus = SingleLogoutManager.LOGOUT_SUCCEEDED_STATUS;
    try {
        if ((session != null) && (sessionProvider.isValid(session)) && MultiProtocolUtils.isMultipleProtocolSession(session, SingleLogoutManager.SAML2)) {
            isMultiProtocolSession = true;
            // call Multi-Federation protocol SingleLogoutManager
            SingleLogoutManager sloManager = SingleLogoutManager.getInstance();
            Set set = new HashSet();
            set.add(session);
            String uid = sessionProvider.getPrincipalName(session);
            debug.message("IDPSingleLogout.processLogReq: MP/SPinit/Http");
            retStatus = sloManager.doIDPSingleLogout(set, uid, request, response, false, false, SingleLogoutManager.SAML2, realm, idpEntityID, spEntityID, relayState, logoutReq.toString(), logoutRes.toXMLString(), getLogoutStatus(logoutRes));
        }
    } catch (SessionException e) {
        // ignore as session might not be valid
        debug.message("IDPSingleLogout.processLogoutRequest: session", e);
    } catch (Exception e) {
        debug.message("IDPSingleLogout.processLogoutRequest: MP2", e);
        retStatus = SingleLogoutManager.LOGOUT_FAILED_STATUS;
    }
    if (!isMultiProtocolSession || (retStatus != SingleLogoutManager.LOGOUT_REDIRECTED_STATUS)) {
        logoutRes = updateLogoutResponse(logoutRes, retStatus);
        List partners = IDPProxyUtil.getSessionPartners(request);
        if (partners != null && !partners.isEmpty()) {
            IDPProxyUtil.sendProxyLogoutRequest(request, response, out, logoutReq, partners, binding, relayState);
        } else {
            LogoutUtil.sendSLOResponse(response, request, logoutRes, location, relayState, realm, idpEntityID, SAML2Constants.IDP_ROLE, spEntityID, binding);
        }
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) LogoutResponse(com.sun.identity.saml2.protocol.LogoutResponse) SessionException(com.sun.identity.plugin.session.SessionException) SessionException(com.sun.identity.plugin.session.SessionException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) IOException(java.io.IOException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) SingleLogoutManager(com.sun.identity.multiprotocol.SingleLogoutManager) SingleLogoutServiceElement(com.sun.identity.saml2.jaxb.metadata.SingleLogoutServiceElement) LogoutRequest(com.sun.identity.saml2.protocol.LogoutRequest) List(java.util.List) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement) HashSet(java.util.HashSet)

Example 30 with Status

use of com.sun.identity.saml2.protocol.Status in project OpenAM by OpenRock.

the class LogoutUtil method generateResponse.

/**
    * Builds the <code>LogoutResponse</code> to be sent to IDP.
     *
     * @param status status of the response.
     * @param inResponseTo inResponseTo.
     * @param issuer issuer of the response, which is SP.
     * @param realm inResponseTo.
     * @param hostRole issuer of the response, which is SP.
     * @param remoteEntity will get this response.
     *
     * @return <code>LogoutResponse</code>
     *
     */
public static LogoutResponse generateResponse(Status status, String inResponseTo, Issuer issuer, String realm, String hostRole, String remoteEntity) {
    if (status == null) {
        status = SAML2Utils.generateStatus(SAML2Constants.SUCCESS, SAML2Utils.bundle.getString("requestSuccess"));
    }
    LogoutResponse logoutResponse = ProtocolFactory.getInstance().createLogoutResponse();
    String responseID = SAMLUtils.generateID();
    try {
        logoutResponse.setStatus(status);
        logoutResponse.setID(responseID);
        logoutResponse.setInResponseTo(inResponseTo);
        logoutResponse.setVersion(SAML2Constants.VERSION_2_0);
        logoutResponse.setIssueInstant(new Date());
        logoutResponse.setIssuer(issuer);
    } catch (SAML2Exception e) {
        debug.error("Error in generating LogoutResponse.", e);
    }
    return logoutResponse;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) LogoutResponse(com.sun.identity.saml2.protocol.LogoutResponse) Date(java.util.Date)

Aggregations

SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)27 Status (com.sun.identity.saml2.protocol.Status)16 List (java.util.List)16 ArrayList (java.util.ArrayList)11 Date (java.util.Date)11 Element (org.w3c.dom.Element)11 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)10 Issuer (com.sun.identity.saml2.assertion.Issuer)9 IOException (java.io.IOException)9 SessionException (com.sun.identity.plugin.session.SessionException)8 ProtocolFactory (com.sun.identity.saml2.protocol.ProtocolFactory)8 Iterator (java.util.Iterator)8 SAML2TokenRepositoryException (org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)8 Response (com.sun.identity.saml2.protocol.Response)7 StatusCode (com.sun.identity.saml2.protocol.StatusCode)7 HttpServletResponse (javax.servlet.http.HttpServletResponse)7 Assertion (com.sun.identity.saml2.assertion.Assertion)6 LogoutResponse (com.sun.identity.saml2.protocol.LogoutResponse)6 Node (org.w3c.dom.Node)6 NodeList (org.w3c.dom.NodeList)6