Search in sources :

Example 41 with SAML2Exception

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

the class SPSingleLogout method processLogoutResponse.

/**
     * Gets and processes the Single <code>LogoutResponse</code> from IDP,
     * destroys the local session, checks response's issuer
     * and inResponseTo.
     *
     * @param request the HttpServletRequest.
     * @param response the HttpServletResponse.
     * @param samlResponse <code>LogoutResponse</code> in the
     *          XML string format.
     * @param relayState the target URL on successful
     * <code>LogoutResponse</code>.
     * @throws SAML2Exception if error processing
     *          <code>LogoutResponse</code>.
     * @throws SessionException if error processing
     *          <code>LogoutResponse</code>.
     */
public static Map<String, String> processLogoutResponse(HttpServletRequest request, HttpServletResponse response, String samlResponse, String relayState) throws SAML2Exception, SessionException {
    String method = "SPSingleLogout:processLogoutResponse : ";
    if (debug.messageEnabled()) {
        debug.message(method + "samlResponse : " + samlResponse);
        debug.message(method + "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());
    if ((SPCache.isFedlet) && ((metaAlias == null) || (metaAlias.length() == 0))) {
        List spMetaAliases = sm.getAllHostedServiceProviderMetaAliases("/");
        if ((spMetaAliases != null) && !spMetaAliases.isEmpty()) {
            // get first one
            metaAlias = (String) spMetaAliases.get(0);
        }
    }
    if ((metaAlias == null) || (metaAlias.length() == 0)) {
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullSPEntityID"));
    }
    String realm = SAML2Utils.getRealm(SAML2MetaUtils.getRealmByMetaAlias(metaAlias));
    String spEntityID = sm.getEntityByMetaAlias(metaAlias);
    if (!SAML2Utils.isSPProfileBindingSupported(realm, spEntityID, SAML2Constants.SLO_SERVICE, binding)) {
        throw new SAML2Exception(SAML2Utils.bundle.getString("unsupportedBinding"));
    }
    // Validate the RelayState URL.
    SAML2Utils.validateRelayStateURL(realm, spEntityID, relayState, SAML2Constants.SP_ROLE);
    LogoutResponse logoutRes = null;
    if (rmethod.equals("POST")) {
        logoutRes = LogoutUtil.getLogoutResponseFromPost(samlResponse, response);
    } else if (rmethod.equals("GET")) {
        String decodedStr = SAML2Utils.decodeFromRedirect(samlResponse);
        if (decodedStr == null) {
            throw new SAML2Exception(SAML2Utils.bundle.getString("nullDecodedStrFromSamlResponse"));
        }
        logoutRes = ProtocolFactory.getInstance().createLogoutResponse(decodedStr);
    }
    if (logoutRes == null) {
        if (debug.messageEnabled()) {
            debug.message("SSingleLogout:processLogoutResponse: logoutRes " + "is null");
        }
        return null;
    }
    String idpEntityID = logoutRes.getIssuer().getValue();
    Issuer resIssuer = logoutRes.getIssuer();
    String inResponseTo = logoutRes.getInResponseTo();
    LogoutRequest logoutReq = (LogoutRequest) SPCache.logoutRequestIDHash.remove(inResponseTo);
    if (logoutReq == null) {
        logoutReq = (LogoutRequest) SAML2Store.getTokenFromStore(inResponseTo);
    }
    if (logoutReq == null && SAML2FailoverUtils.isSAML2FailoverEnabled()) {
        //check the samlFailover cache instead
        try {
            logoutReq = (LogoutRequest) SAML2FailoverUtils.retrieveSAML2Token(inResponseTo);
        } catch (SAML2TokenRepositoryException e) {
            throw new SAML2Exception(SAML2Utils.bundle.getString("LogoutRequestIDandInResponseToDoNotMatch"));
        }
    }
    // invoke SPAdapter preSingleLogoutProcess
    String userId = null;
    if (!SPCache.isFedlet) {
        userId = preSingleLogoutProcess(spEntityID, realm, request, response, null, logoutReq, logoutRes, binding);
    }
    SAML2Utils.verifyResponseIssuer(realm, spEntityID, resIssuer, inResponseTo);
    boolean needToVerify = SAML2Utils.getWantLogoutResponseSigned(realm, spEntityID, SAML2Constants.SP_ROLE);
    if (debug.messageEnabled()) {
        debug.message(method + "metaAlias : " + metaAlias);
        debug.message(method + "realm : " + realm);
        debug.message(method + "idpEntityID : " + idpEntityID);
        debug.message(method + "spEntityID : " + spEntityID);
    }
    Map<String, String> infoMap = new HashMap<String, String>();
    infoMap.put("entityid", spEntityID);
    infoMap.put(SAML2Constants.REALM, realm);
    if (needToVerify) {
        boolean valid = false;
        if (rmethod.equals("GET")) {
            String queryString = request.getQueryString();
            valid = SAML2Utils.verifyQueryString(queryString, realm, SAML2Constants.SP_ROLE, idpEntityID);
        } else {
            valid = LogoutUtil.verifySLOResponse(logoutRes, realm, idpEntityID, spEntityID, SAML2Constants.SP_ROLE);
        }
        if (!valid) {
            debug.error("SPSingleLogout.processLogoutResponse: " + "Invalid signature in SLO Response.");
            throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignInResponse"));
        }
        SPSSODescriptorElement spsso = sm.getSPSSODescriptor(realm, spEntityID);
        String loc = getSLOResponseLocationOrLocation(spsso, binding);
        if (!SAML2Utils.verifyDestination(logoutRes.getDestination(), loc)) {
            throw new SAML2Exception(SAML2Utils.bundle.getString("invalidDestination"));
        }
    }
    if (inResponseTo == null || inResponseTo.length() == 0) {
        if (debug.messageEnabled()) {
            debug.message("LogoutResponse inResponseTo is null");
        }
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullInResponseToFromSamlResponse"));
    }
    if (logoutReq != null) {
        if (debug.messageEnabled()) {
            debug.message("LogoutResponse inResponseTo matches " + "LogoutRequest ID.");
        }
    } else {
        if (debug.messageEnabled()) {
            debug.message("LogoutResponse inResponseTo does not match " + "LogoutRequest ID.");
        }
        throw new SAML2Exception(SAML2Utils.bundle.getString("LogoutRequestIDandInResponseToDoNotMatch"));
    }
    infoMap.put("inResponseTo", inResponseTo);
    infoMap.put(SAML2Constants.RELAY_STATE, relayState);
    // destroy session
    try {
        Object session = sessionProvider.getSession(request);
        if ((session != null) && sessionProvider.isValid(session)) {
            sessionProvider.invalidateSession(session, request, response);
        }
    } catch (SessionException se) {
        debug.message("SPSingleLogout.processLogoutResponse() : Unable to invalidate session: " + se.getMessage());
    }
    if (!SPCache.isFedlet) {
        if (isSuccess(logoutRes)) {
            // invoke SPAdapter postSingleLogoutSucces
            postSingleLogoutSuccess(spEntityID, realm, request, response, userId, logoutReq, logoutRes, binding);
        } else {
            throw new SAML2Exception(SAML2Utils.BUNDLE_NAME, "sloFailed", null);
        }
    } else {
        // obtain fedlet adapter
        FedletAdapter fedletAdapter = SAML2Utils.getFedletAdapterClass(spEntityID, realm);
        if (fedletAdapter != null) {
            if (isSuccess(logoutRes)) {
                fedletAdapter.onFedletSLOSuccess(request, response, logoutReq, logoutRes, spEntityID, idpEntityID, binding);
            } else {
                fedletAdapter.onFedletSLOFailure(request, response, logoutReq, logoutRes, spEntityID, idpEntityID, binding);
                throw new SAML2Exception(SAML2Utils.BUNDLE_NAME, "sloFailed", null);
            }
        }
    }
    return infoMap;
}
Also used : LogoutResponse(com.sun.identity.saml2.protocol.LogoutResponse) Issuer(com.sun.identity.saml2.assertion.Issuer) HashMap(java.util.HashMap) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) SessionException(com.sun.identity.plugin.session.SessionException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) FedletAdapter(com.sun.identity.saml2.plugins.FedletAdapter) List(java.util.List) ArrayList(java.util.ArrayList) LogoutRequest(com.sun.identity.saml2.protocol.LogoutRequest) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)

Example 42 with SAML2Exception

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

the class NameIDMapping method signNIMResponse.

static void signNIMResponse(NameIDMappingResponse nimResponse, String realm, String idpEntityID, boolean includeCert) throws SAML2Exception {
    String alias = SAML2Utils.getSigningCertAlias(realm, idpEntityID, SAML2Constants.IDP_ROLE);
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message("NameIDMapping.signNIMResponse: " + realm);
        SAML2Utils.debug.message("NameIDMapping.signNIMResponse: " + idpEntityID);
        SAML2Utils.debug.message("NameIDMapping.signNIMResponse: " + alias);
    }
    String encryptedKeyPass = SAML2Utils.getSigningCertEncryptedKeyPass(realm, idpEntityID, SAML2Constants.IDP_ROLE);
    PrivateKey signingKey;
    if (encryptedKeyPass == null || encryptedKeyPass.isEmpty()) {
        signingKey = keyProvider.getPrivateKey(alias);
    } else {
        signingKey = keyProvider.getPrivateKey(alias, encryptedKeyPass);
    }
    X509Certificate signingCert = null;
    if (includeCert) {
        signingCert = keyProvider.getX509Certificate(alias);
    }
    if (signingKey != null) {
        nimResponse.sign(signingKey, signingCert);
    } else {
        SAML2Utils.debug.error("NameIDMapping.signNIMResponse: " + "Incorrect configuration for Signing Certificate.");
        throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) PrivateKey(java.security.PrivateKey) X509Certificate(java.security.cert.X509Certificate)

Example 43 with SAML2Exception

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

the class NameIDMapping method initiateNameIDMappingRequest.

/**
     * Parses the request parameters and builds the NameIDMappingRequest to
     * sent to remote identity provider.
     *
     * @param session user session.
     * @param realm the realm of hosted entity
     * @param spEntityID entity ID of hosted service provider
     * @param idpEntityID entity ID of remote idendity provider
     * @param targetSPEntityID entity ID of target entity ID of service
     *     provider
     * @param targetNameIDFormat format of target Name ID
     * @param paramsMap Map of all other parameters
     *
     * @return the <code>NameIDMappingResponse</code>
     * @throws SAML2Exception if error initiating request to remote entity.
     *
     * @supported.api
     */
public static NameIDMappingResponse initiateNameIDMappingRequest(Object session, String realm, String spEntityID, String idpEntityID, String targetSPEntityID, String targetNameIDFormat, Map paramsMap) throws SAML2Exception {
    if (spEntityID == null) {
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullSPEntityID"));
    }
    if (idpEntityID == null) {
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullIDPEntityID"));
    }
    String userID = null;
    try {
        userID = sessionProvider.getPrincipalName(session);
    } catch (SessionException e) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message("NameIDMapping.createNameIDMappingRequest: ", e);
        }
    }
    if (userID == null) {
        throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
    }
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message("NameIDMapping.initiateNameMappingRequest:" + " IDP EntityID is : " + idpEntityID);
        SAML2Utils.debug.message("NameIDMapping.initiateNameMappingRequest:" + " SP HOST EntityID is : " + spEntityID);
        SAML2Utils.debug.message("NameIDMapping.initiateNameMappingRequest:" + " target SP EntityID is : " + targetSPEntityID);
    }
    try {
        // nameIDMappingService
        String binding = SAML2Utils.getParameter(paramsMap, SAML2Constants.BINDING);
        if (binding == null) {
            binding = SAML2Constants.SOAP;
        } else if (!binding.equals(SAML2Constants.SOAP)) {
            throw new SAML2Exception(SAML2Utils.bundle.getString("nimServiceBindingUnsupport"));
        }
        String nimURL = SAML2Utils.getParameter(paramsMap, "nimURL");
        if (nimURL == null) {
            NameIDMappingServiceElement nameIDMappingService = getNameIDMappingService(realm, idpEntityID, binding);
            if (nameIDMappingService != null) {
                nimURL = nameIDMappingService.getLocation();
            }
        }
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message("NameIDMapping.initiateNameMappingRequest:" + " nimURL" + nimURL);
        }
        if (nimURL == null) {
            throw new SAML2Exception(SAML2Utils.bundle.getString("nimServiceNotFound"));
        }
        NameIDMappingRequest nimRequest = createNameIDMappingRequest(userID, realm, spEntityID, idpEntityID, nimURL, targetSPEntityID, targetNameIDFormat);
        signNIMRequest(nimRequest, realm, spEntityID, false);
        BaseConfigType config = metaManager.getIDPSSOConfig(realm, idpEntityID);
        nimURL = SAML2SDKUtils.fillInBasicAuthInfo(config, nimURL);
        return doNIMBySOAP(nimRequest.toXMLString(true, true), nimURL, realm, spEntityID);
    } catch (SAML2MetaException sme) {
        throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) NameIDMappingServiceElement(com.sun.identity.saml2.jaxb.metadata.NameIDMappingServiceElement) BaseConfigType(com.sun.identity.saml2.jaxb.entityconfig.BaseConfigType) SessionException(com.sun.identity.plugin.session.SessionException) NameIDMappingRequest(com.sun.identity.saml2.protocol.NameIDMappingRequest) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException)

Example 44 with SAML2Exception

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

the class NameIDMapping method createNameIDMappingRequest.

private static NameIDMappingRequest createNameIDMappingRequest(String userID, String realm, String spEntityID, String idpEntityID, String destination, String targetSPEntityID, String targetNameIDFormat) throws SAML2Exception {
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message("NameIDMapping.createNameIDMappingRequest: User ID : " + userID);
    }
    NameIDMappingRequest nimRequest = pf.createNameIDMappingRequest();
    nimRequest.setID(SAML2Utils.generateID());
    nimRequest.setVersion(SAML2Constants.VERSION_2_0);
    nimRequest.setDestination(XMLUtils.escapeSpecialCharacters(destination));
    nimRequest.setIssuer(SAML2Utils.createIssuer(spEntityID));
    nimRequest.setIssueInstant(new Date());
    setNameIDForNIMRequest(nimRequest, realm, spEntityID, idpEntityID, targetSPEntityID, targetNameIDFormat, userID);
    return nimRequest;
}
Also used : NameIDMappingRequest(com.sun.identity.saml2.protocol.NameIDMappingRequest) Date(java.util.Date)

Example 45 with SAML2Exception

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

the class AttributeQueryUtil method signAttributeQuery.

private static void signAttributeQuery(AttributeQuery attrQuery, String realm, boolean includeCert) throws SAML2Exception {
    String requesterEntityID = attrQuery.getIssuer().getValue();
    String alias = SAML2Utils.getSigningCertAlias(realm, requesterEntityID, SAML2Constants.ATTR_QUERY_ROLE);
    PrivateKey signingKey = keyProvider.getPrivateKey(alias);
    if (signingKey == null) {
        throw new SAML2Exception(SAML2Utils.bundle.getString("missingSigningCertAlias"));
    }
    X509Certificate signingCert = null;
    if (includeCert) {
        signingCert = keyProvider.getX509Certificate(alias);
    }
    if (signingKey != null) {
        attrQuery.sign(signingKey, signingCert);
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) PrivateKey(java.security.PrivateKey) X509Certificate(java.security.cert.X509Certificate)

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