Search in sources :

Example 36 with SAML2Exception

use of com.sun.identity.saml2.common.SAML2Exception in project OpenAM by OpenRock.

the class LogoutUtil method doLogout.

public static StringBuffer doLogout(String metaAlias, String recipientEntityID, List extensionsList, EndpointType logoutEndpoint, String relayState, String sessionIndex, NameID nameID, HttpServletRequest request, HttpServletResponse response, Map paramsMap, BaseConfigType config) throws SAML2Exception, SessionException {
    StringBuffer logoutRequestID = new StringBuffer();
    String classMethod = "LogoutUtil.doLogout: ";
    String requesterEntityID = metaManager.getEntityByMetaAlias(metaAlias);
    String realm = SAML2MetaUtils.getRealmByMetaAlias(metaAlias);
    String hostEntityRole = SAML2Utils.getHostEntityRole(paramsMap);
    String location = null;
    String binding = null;
    if (logoutEndpoint != null) {
        location = logoutEndpoint.getLocation();
        binding = logoutEndpoint.getBinding();
    } else {
        debug.error(classMethod + "Unable to find the recipient's single logout service with the binding " + binding);
        throw new SAML2Exception(SAML2Utils.bundle.getString("sloServiceNotfound"));
    }
    if (debug.messageEnabled()) {
        debug.message(classMethod + "Entering ..." + "\nrequesterEntityID=" + requesterEntityID + "\nrecipientEntityID=" + recipientEntityID + "\nbinding=" + binding + "\nrelayState=" + relayState + "\nsessionIndex=" + sessionIndex);
    }
    // generate unique request ID
    String requestID = SAML2Utils.generateID();
    if ((requestID == null) || (requestID.length() == 0)) {
        throw new SAML2Exception(SAML2Utils.bundle.getString("cannotGenerateID"));
    }
    // retrieve data from the params map
    // destinationURI required if message is signed.
    String destinationURI = SAML2Utils.getParameter(paramsMap, SAML2Constants.DESTINATION);
    String consent = SAML2Utils.getParameter(paramsMap, SAML2Constants.CONSENT);
    Extensions extensions = createExtensions(extensionsList);
    Issuer issuer = SAML2Utils.createIssuer(requesterEntityID);
    // construct LogoutRequest
    LogoutRequest logoutReq = null;
    try {
        logoutReq = ProtocolFactory.getInstance().createLogoutRequest();
    } catch (Exception e) {
        debug.error(classMethod + "Unable to create LogoutRequest : ", e);
        throw new SAML2Exception(SAML2Utils.bundle.getString("errorCreatingLogoutRequest"));
    }
    // set required attributes / elements
    logoutReq.setID(requestID);
    logoutReq.setVersion(SAML2Constants.VERSION_2_0);
    logoutReq.setIssueInstant(new Date());
    setNameIDForSLORequest(logoutReq, nameID, realm, requesterEntityID, hostEntityRole, recipientEntityID);
    // set optional attributes / elements
    logoutReq.setDestination(XMLUtils.escapeSpecialCharacters(destinationURI));
    logoutReq.setConsent(consent);
    logoutReq.setIssuer(issuer);
    if (hostEntityRole.equals(SAML2Constants.IDP_ROLE)) {
        // use the assertion effective time (in seconds)
        int effectiveTime = SAML2Constants.ASSERTION_EFFECTIVE_TIME;
        String effectiveTimeStr = SAML2Utils.getAttributeValueFromSSOConfig(realm, requesterEntityID, SAML2Constants.IDP_ROLE, SAML2Constants.ASSERTION_EFFECTIVE_TIME_ATTRIBUTE);
        if (effectiveTimeStr != null) {
            try {
                effectiveTime = Integer.parseInt(effectiveTimeStr);
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.message(classMethod + "got effective time from config:" + effectiveTime);
                }
            } catch (NumberFormatException nfe) {
                SAML2Utils.debug.error(classMethod + "Failed to get assertion effective time from " + "IDP SSO config: ", nfe);
                effectiveTime = SAML2Constants.ASSERTION_EFFECTIVE_TIME;
            }
        }
        Date date = new Date();
        date.setTime(date.getTime() + effectiveTime * 1000);
        logoutReq.setNotOnOrAfter(date);
    }
    if (extensions != null) {
        logoutReq.setExtensions(extensions);
    }
    if (sessionIndex != null) {
        List list = new ArrayList();
        list.add(sessionIndex);
        logoutReq.setSessionIndex(list);
    }
    debug.message(classMethod + "Recipient's single logout service location = " + location);
    if (destinationURI == null || destinationURI.isEmpty()) {
        logoutReq.setDestination(XMLUtils.escapeSpecialCharacters(location));
    }
    if (debug.messageEnabled()) {
        debug.message(classMethod + "SLO Request before signing : ");
        debug.message(logoutReq.toXMLString(true, true));
    }
    if (binding.equals(SAML2Constants.HTTP_REDIRECT)) {
        try {
            doSLOByHttpRedirect(logoutReq.toXMLString(true, true), location, relayState, realm, requesterEntityID, hostEntityRole, recipientEntityID, response);
            logoutRequestID.append(requestID);
            String[] data = { location };
            LogUtil.access(Level.INFO, LogUtil.REDIRECT_TO_IDP, data, null);
        } catch (Exception e) {
            debug.error("Exception :", e);
            throw new SAML2Exception(SAML2Utils.bundle.getString("errorRedirectingLogoutRequest"));
        }
    } else if (binding.equals(SAML2Constants.SOAP)) {
        logoutRequestID.append(requestID);
        signSLORequest(logoutReq, realm, requesterEntityID, hostEntityRole, recipientEntityID);
        if (debug.messageEnabled()) {
            debug.message(classMethod + "SLO Request after signing : ");
            debug.message(logoutReq.toXMLString(true, true));
        }
        location = SAML2Utils.fillInBasicAuthInfo(config, location);
        doSLOBySOAP(requestID, logoutReq, location, realm, requesterEntityID, hostEntityRole, request, response);
    } else if (binding.equals(SAML2Constants.HTTP_POST)) {
        logoutRequestID.append(requestID);
        signSLORequest(logoutReq, realm, requesterEntityID, hostEntityRole, recipientEntityID);
        if (debug.messageEnabled()) {
            debug.message(classMethod + "SLO Request after signing : ");
            debug.message(logoutReq.toXMLString(true, true));
        }
        doSLOByPOST(requestID, logoutReq.toXMLString(true, true), location, relayState, realm, requesterEntityID, hostEntityRole, response, request);
    }
    SPCache.logoutRequestIDHash.put(logoutRequestID.toString(), logoutReq);
    return logoutRequestID;
}
Also used : Issuer(com.sun.identity.saml2.assertion.Issuer) ArrayList(java.util.ArrayList) Extensions(com.sun.identity.saml2.protocol.Extensions) SOAPException(javax.xml.soap.SOAPException) SessionException(com.sun.identity.plugin.session.SessionException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) IOException(java.io.IOException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Date(java.util.Date) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) LogoutRequest(com.sun.identity.saml2.protocol.LogoutRequest) List(java.util.List) ArrayList(java.util.ArrayList)

Example 37 with SAML2Exception

use of com.sun.identity.saml2.common.SAML2Exception in project OpenAM by OpenRock.

the class LogoutUtil method doSLOBySOAP.

/**
     * Performs SOAP logout, this method will send LogoutResuest to IDP using
     * SOAP binding, and process LogoutResponse.
     * @param requestID Request id.
     * @param sloRequest  a string representation of LogoutRequest.
     * @param sloURL SOAP logout URL on IDP side.
     * @param realm  a string representation of LogoutRequest.
     * @param hostEntity  host entity is sending the request.
     * @param hostRole SOAP logout URL on IDP side.
     * @throws SAML2Exception if logout failed. 
     * @throws SessionException if logout failed. 
     */
private static void doSLOBySOAP(String requestID, LogoutRequest sloRequest, String sloURL, String realm, String hostEntity, String hostRole, HttpServletRequest request, HttpServletResponse response) throws SAML2Exception, SessionException {
    String sloRequestXMLString = sloRequest.toXMLString(true, true);
    if (debug.messageEnabled()) {
        debug.message("LogoutUtil.doSLOBySOAP : SLORequestXML: " + sloRequestXMLString + "\nSOAPURL : " + sloURL);
    }
    SOAPMessage resMsg = null;
    try {
        resMsg = SOAPCommunicator.getInstance().sendSOAPMessage(sloRequestXMLString, sloURL, true);
    } catch (SOAPException se) {
        debug.error("Unable to send SOAPMessage to IDP ", se);
        throw new SAML2Exception(se.getMessage());
    }
    // get the LogoutResponse element from SOAP message
    Element respElem = SOAPCommunicator.getInstance().getSamlpElement(resMsg, "LogoutResponse");
    LogoutResponse sloResponse = ProtocolFactory.getInstance().createLogoutResponse(respElem);
    String userId = null;
    // invoke SPAdapter for preSingleLogoutProcess : SP initiated SOAP
    if ((hostRole != null) && hostRole.equals(SAML2Constants.SP_ROLE)) {
        userId = SPSingleLogout.preSingleLogoutProcess(hostEntity, realm, request, response, null, sloRequest, sloResponse, SAML2Constants.SOAP);
    }
    if (sloResponse == null) {
        debug.error("LogoutUtil.doSLOBySoap : null response");
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullLogoutResponse"));
    }
    if (debug.messageEnabled()) {
        debug.message("LogoutUtil.doSLOBySOAP : " + "LogoutResponse without SOAP envelope:\n" + sloResponse.toXMLString());
    }
    Issuer resIssuer = sloResponse.getIssuer();
    String requestId = sloResponse.getInResponseTo();
    SAML2Utils.verifyResponseIssuer(realm, hostEntity, resIssuer, requestId);
    String remoteEntityID = sloResponse.getIssuer().getValue();
    verifySLOResponse(sloResponse, realm, remoteEntityID, hostEntity, hostRole);
    boolean success = checkSLOResponse(sloResponse, requestID);
    if (debug.messageEnabled()) {
        debug.message("Request success : " + success);
    }
    if (success == false) {
        if (SPCache.isFedlet) {
            FedletAdapter fedletAdapter = SAML2Utils.getFedletAdapterClass(hostEntity, realm);
            if (fedletAdapter != null) {
                fedletAdapter.onFedletSLOFailure(request, response, sloRequest, sloResponse, hostEntity, remoteEntityID, SAML2Constants.SOAP);
            }
        }
        throw new SAML2Exception(SAML2Utils.bundle.getString("sloFailed"));
    } else {
        // invoke SPAdapter for postSLOSuccess : SP inited SOAP 
        if ((hostRole != null) && hostRole.equals(SAML2Constants.SP_ROLE)) {
            if (SPCache.isFedlet) {
                FedletAdapter fedletAdapter = SAML2Utils.getFedletAdapterClass(hostEntity, realm);
                if (fedletAdapter != null) {
                    fedletAdapter.onFedletSLOSuccess(request, response, sloRequest, sloResponse, hostEntity, remoteEntityID, SAML2Constants.SOAP);
                }
            } else {
                SPSingleLogout.postSingleLogoutSuccess(hostEntity, realm, request, response, userId, sloRequest, sloResponse, SAML2Constants.SOAP);
            }
        }
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) FedletAdapter(com.sun.identity.saml2.plugins.FedletAdapter) LogoutResponse(com.sun.identity.saml2.protocol.LogoutResponse) Issuer(com.sun.identity.saml2.assertion.Issuer) SOAPException(javax.xml.soap.SOAPException) SingleLogoutServiceElement(com.sun.identity.saml2.jaxb.metadata.SingleLogoutServiceElement) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) Element(org.w3c.dom.Element) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement) SOAPMessage(javax.xml.soap.SOAPMessage)

Example 38 with SAML2Exception

use of com.sun.identity.saml2.common.SAML2Exception in project OpenAM by OpenRock.

the class LogoutUtil method getSLOBindingInfo.

/**
     * Returns binding information of SLO Service for remote entity 
     * from request or meta configuration.
     *
     * @param request the HttpServletRequest.
     * @param metaAlias entityID of hosted entity.
     * @param hostEntityRole Role of hosted entity.
     * @param remoteEntityID entityID of remote entity.
     * @return return true if the processing is successful.
     * @throws SAML2Exception if no binding information is configured.
     */
public static String getSLOBindingInfo(HttpServletRequest request, String metaAlias, String hostEntityRole, String remoteEntityID) throws SAML2Exception {
    String binding = request.getParameter(SAML2Constants.BINDING);
    try {
        if (binding == null) {
            String realm = SAML2MetaUtils.getRealmByMetaAlias(metaAlias);
            SingleLogoutServiceElement sloService = getSLOServiceElement(realm, remoteEntityID, hostEntityRole, null);
            if (sloService != null) {
                binding = sloService.getBinding();
            }
        }
    } catch (SessionException e) {
        debug.error("Invalid SSOToken", e);
        throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
    }
    if (binding == null) {
        debug.error("Incorrect configuration for SingleLogout Service.");
        throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
    }
    return binding;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) SingleLogoutServiceElement(com.sun.identity.saml2.jaxb.metadata.SingleLogoutServiceElement) SessionException(com.sun.identity.plugin.session.SessionException)

Example 39 with SAML2Exception

use of com.sun.identity.saml2.common.SAML2Exception in project OpenAM by OpenRock.

the class LogoutUtil method verifySLOResponse.

/**
     * Verify the signature in LogoutResponse.
     *
     * @param sloResponse SLO response will be verified.
     * @param realm realm of host entity.
     * @param remoteEntity entity ID of remote host entity.
     * @param hostEntity entity ID of host entity.
     * @param hostEntityRole role of host entity.
     * @return returns true if signature is valid.
     * @throws SAML2Exception if error in verifying the signature.
     * @throws SessionException if error in verifying the signature.
     */
public static boolean verifySLOResponse(LogoutResponse sloResponse, String realm, String remoteEntity, String hostEntity, String hostEntityRole) throws SAML2Exception, SessionException {
    String method = "verifySLOResponse : ";
    boolean needVerifySignature = SAML2Utils.getWantLogoutResponseSigned(realm, hostEntity, hostEntityRole);
    if (needVerifySignature == false) {
        if (debug.messageEnabled()) {
            debug.message(method + "SLOResponse doesn't need to be verified.");
        }
        return true;
    }
    Set<X509Certificate> signingCerts;
    if (hostEntityRole.equalsIgnoreCase(SAML2Constants.IDP_ROLE)) {
        SPSSODescriptorElement spSSODesc = metaManager.getSPSSODescriptor(realm, remoteEntity);
        signingCerts = KeyUtil.getVerificationCerts(spSSODesc, remoteEntity, SAML2Constants.SP_ROLE);
    } else {
        IDPSSODescriptorElement idpSSODesc = metaManager.getIDPSSODescriptor(realm, remoteEntity);
        signingCerts = KeyUtil.getVerificationCerts(idpSSODesc, remoteEntity, SAML2Constants.IDP_ROLE);
    }
    if (!signingCerts.isEmpty()) {
        boolean valid = sloResponse.isSignatureValid(signingCerts);
        if (debug.messageEnabled()) {
            debug.message(method + "Signature is : " + valid);
        }
        return valid;
    } else {
        debug.error("Incorrect configuration for Signing Certificate.");
        throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) X509Certificate(java.security.cert.X509Certificate) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Example 40 with SAML2Exception

use of com.sun.identity.saml2.common.SAML2Exception in project OpenAM by OpenRock.

the class LogoutUtil method createExtensions.

/* Creates Extensions */
private static com.sun.identity.saml2.protocol.Extensions createExtensions(List extensionsList) throws SAML2Exception {
    Extensions extensions = null;
    if (extensionsList != null && !extensionsList.isEmpty()) {
        extensions = ProtocolFactory.getInstance().createExtensions();
        extensions.setAny(extensionsList);
    }
    return extensions;
}
Also used : Extensions(com.sun.identity.saml2.protocol.Extensions)

Aggregations

SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)275 ArrayList (java.util.ArrayList)92 List (java.util.List)86 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)72 Element (org.w3c.dom.Element)64 SessionException (com.sun.identity.plugin.session.SessionException)56 IOException (java.io.IOException)51 SPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement)44 Map (java.util.Map)44 HashMap (java.util.HashMap)43 Iterator (java.util.Iterator)43 Issuer (com.sun.identity.saml2.assertion.Issuer)42 Date (java.util.Date)40 SOAPException (javax.xml.soap.SOAPException)39 SAML2TokenRepositoryException (org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)39 X509Certificate (java.security.cert.X509Certificate)36 NodeList (org.w3c.dom.NodeList)36 IDPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)35 Node (org.w3c.dom.Node)34 Response (com.sun.identity.saml2.protocol.Response)30