Search in sources :

Example 11 with ManageNameIDRequest

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

the class DoManageNameID method initiateManageNameIDRequest.

/**
     * Parses the request parameters and builds the ManageNameID
     * Request to sent to remote Entity.
     *
     * @param request the HttpServletRequest.
     * @param response the HttpServletResponse.
     * @param metaAlias entityID of hosted entity.
     * @param remoteEntityID entityID of remote entity.
     * @param paramsMap Map of all other parameters.
     * @throws SAML2Exception if error initiating request to remote entity.
     */
public static void initiateManageNameIDRequest(HttpServletRequest request, HttpServletResponse response, String metaAlias, String remoteEntityID, Map paramsMap) throws SAML2Exception {
    String method = "DoManageNameID.initiateManageNameIDRequest: ";
    if (metaManager == null) {
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorMetaManager"));
    }
    if (metaAlias == null) {
        logError("MetaAliasNotFound", LogUtil.MISSING_META_ALIAS, metaAlias);
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullEntityID"));
    }
    if (remoteEntityID == null) {
        logError("nullRemoteEntityID", LogUtil.MISSING_ENTITY, remoteEntityID);
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullRemoteEntityID"));
    }
    Object session = null;
    try {
        session = SessionManager.getProvider().getSession(request);
    } catch (SessionException se) {
        if (debug.messageEnabled()) {
            debug.message(method, se);
        }
    }
    String realm = SAML2MetaUtils.getRealmByMetaAlias(metaAlias);
    String hostEntityID = metaManager.getEntityByMetaAlias(metaAlias);
    String hostEntityRole = SAML2Utils.getHostEntityRole(paramsMap);
    if (session == null) {
        if (debug.messageEnabled()) {
            debug.message(method + "Session is missing." + "redirect to the authentication service");
        }
        // redirect to the authentication service
        try {
            SAML2Utils.redirectAuthentication(request, response, realm, hostEntityID, hostEntityRole);
        } catch (IOException ioe) {
            logError("UnableToRedirectToAuth", LogUtil.REDIRECT_TO_AUTH, null);
            throw new SAML2Exception(ioe.toString());
        }
        return;
    }
    if (debug.messageEnabled()) {
        debug.message(method + "Meta Alias is : " + metaAlias);
        debug.message(method + "Remote EntityID is : " + remoteEntityID);
        debug.message(method + "Host EntityID is : " + hostEntityID);
    }
    try {
        String binding = SAML2Utils.getParameter(paramsMap, SAML2Constants.BINDING);
        ManageNameIDServiceElement mniService = getMNIServiceElement(realm, remoteEntityID, hostEntityRole, binding);
        if (binding == null) {
            binding = mniService.getBinding();
        }
        if (binding == null) {
            logError("UnableTofindBinding", LogUtil.METADATA_ERROR, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("UnableTofindBinding"));
        }
        String mniURL = null;
        if (mniService != null) {
            mniURL = mniService.getLocation();
        }
        if (mniURL == null) {
            logError("mniServiceNotFound", LogUtil.METADATA_ERROR, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("mniServiceNotFound"));
        }
        String requestType = (String) paramsMap.get("requestType");
        boolean changeID = "NewID".equals(requestType);
        String affiliationID = SAML2Utils.getParameter(paramsMap, SAML2Constants.AFFILIATION_ID);
        ManageNameIDRequest mniRequest = createManageNameIDRequest(session, realm, hostEntityID, hostEntityRole, remoteEntityID, mniURL, changeID, affiliationID);
        String relayState = SAML2Utils.getParameter(paramsMap, SAML2Constants.RELAY_STATE);
        if ((relayState == null) || (relayState.equals(""))) {
            relayState = SAML2Utils.getAttributeValueFromSSOConfig(realm, hostEntityID, hostEntityRole, SAML2Constants.DEFAULT_RELAY_STATE);
        }
        // Validate the RelayState URL.
        SAML2Utils.validateRelayStateURL(realm, hostEntityID, relayState, hostEntityRole);
        mniRequest.setDestination(XMLUtils.escapeSpecialCharacters(mniURL));
        saveMNIRequestInfo(request, response, paramsMap, mniRequest, relayState, hostEntityRole, session);
        String mniRequestXMLString = null;
        if (binding.equalsIgnoreCase(SAML2Constants.HTTP_REDIRECT)) {
            mniRequestXMLString = mniRequest.toXMLString(true, true);
            doMNIByHttpRedirect(mniRequestXMLString, mniURL, relayState, realm, hostEntityID, hostEntityRole, remoteEntityID, response);
        } else if (binding.equalsIgnoreCase(SAML2Constants.SOAP)) {
            signMNIRequest(mniRequest, realm, hostEntityID, hostEntityRole, remoteEntityID);
            BaseConfigType config = null;
            if (hostEntityRole.equalsIgnoreCase(SAML2Constants.SP_ROLE)) {
                config = metaManager.getIDPSSOConfig(realm, remoteEntityID);
            } else {
                config = metaManager.getSPSSOConfig(realm, remoteEntityID);
            }
            mniURL = SAML2Utils.fillInBasicAuthInfo(config, mniURL);
            if (!doMNIBySOAP(mniRequest, mniURL, metaAlias, hostEntityRole, request, response)) {
                throw new SAML2Exception(SAML2Utils.bundle.getString("mniFailed"));
            }
        } else if (binding.equalsIgnoreCase(SAML2Constants.HTTP_POST)) {
            signMNIRequest(mniRequest, realm, hostEntityID, hostEntityRole, remoteEntityID);
            mniRequestXMLString = mniRequest.toXMLString(true, true);
            doMNIByPOST(mniRequestXMLString, mniURL, relayState, realm, hostEntityID, hostEntityRole, remoteEntityID, response, request);
        }
    } catch (IOException ioe) {
        logError("errorCreatingMNIRequest", LogUtil.CANNOT_INSTANTIATE_MNI_REQUEST, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("errorCreatingMNIRequest"));
    } catch (SAML2MetaException sme) {
        logError("metaDataError", LogUtil.METADATA_ERROR, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
    } catch (SessionException ssoe) {
        logError("invalidSSOToken", LogUtil.INVALID_SSOTOKEN, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) ManageNameIDServiceElement(com.sun.identity.saml2.jaxb.metadata.ManageNameIDServiceElement) BaseConfigType(com.sun.identity.saml2.jaxb.entityconfig.BaseConfigType) ManageNameIDRequest(com.sun.identity.saml2.protocol.ManageNameIDRequest) SessionException(com.sun.identity.plugin.session.SessionException) IOException(java.io.IOException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException)

Example 12 with ManageNameIDRequest

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

the class DoManageNameID method doMNIBySOAP.

private static boolean doMNIBySOAP(ManageNameIDRequest mniRequest, String mniURL, String metaAlias, String hostRole, HttpServletRequest request, HttpServletResponse response) throws SAML2Exception {
    String method = "doMNIBySOAP: ";
    boolean success = false;
    String mniRequestXMLString = mniRequest.toXMLString(true, true);
    if (debug.messageEnabled()) {
        debug.message(method + "MNIRequestXMLString : " + mniRequestXMLString);
        debug.message(method + "MNIRedirectURL : " + mniURL);
    }
    SOAPMessage resMsg = null;
    try {
        resMsg = SOAPCommunicator.getInstance().sendSOAPMessage(mniRequestXMLString, mniURL, true);
    } catch (SOAPException se) {
        debug.error(SAML2Utils.bundle.getString("invalidSOAPMessge"), se);
        return false;
    }
    Element mniRespElem = SOAPCommunicator.getInstance().getSamlpElement(resMsg, "ManageNameIDResponse");
    ManageNameIDResponse mniResponse = mniResponse = pf.createManageNameIDResponse(mniRespElem);
    if (debug.messageEnabled()) {
        if (mniResponse != null) {
            debug.message(method + "ManageNameIDResponse without " + "SOAP envelope:\n" + mniResponse.toXMLString());
        } else {
            debug.message(method + "ManageNameIDResponse is null ");
        }
    }
    if (mniResponse != null) {
        try {
            String realm = SAML2MetaUtils.getRealmByMetaAlias(metaAlias);
            String hostEntityID = metaManager.getEntityByMetaAlias(metaAlias);
            String remoteEntityID = mniResponse.getIssuer().getValue();
            Issuer resIssuer = mniResponse.getIssuer();
            String requestId = mniResponse.getInResponseTo();
            SAML2Utils.verifyResponseIssuer(realm, hostEntityID, resIssuer, requestId);
            boolean validSign = verifyMNIResponse(mniResponse, realm, remoteEntityID, hostEntityID, hostRole, mniResponse.getDestination());
            if (!validSign) {
                logError("invalidSignInResponse", LogUtil.CANNOT_INSTANTIATE_MNI_RESPONSE, null);
                throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignInResponse"));
            }
            StringBuffer mniUserId = new StringBuffer();
            success = checkMNIResponse(mniResponse, realm, hostEntityID, hostRole, mniUserId);
            if (success && hostRole.equals(SAML2Constants.SP_ROLE)) {
                // invoke SPAdapter for termination success, SP initied SOAP
                postTerminationSuccess(hostEntityID, realm, request, response, mniUserId.toString(), mniRequest, mniResponse, SAML2Constants.SOAP);
            }
        } catch (SessionException e) {
            debug.error(SAML2Utils.bundle.getString("invalidSSOToken"), e);
            throw new SAML2Exception(e.toString());
        }
    }
    if (debug.messageEnabled()) {
        debug.message(method + "Request success : " + success);
    }
    return success;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Issuer(com.sun.identity.saml2.assertion.Issuer) SOAPException(javax.xml.soap.SOAPException) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) ManageNameIDServiceElement(com.sun.identity.saml2.jaxb.metadata.ManageNameIDServiceElement) Element(org.w3c.dom.Element) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement) SessionException(com.sun.identity.plugin.session.SessionException) SOAPMessage(javax.xml.soap.SOAPMessage) ManageNameIDResponse(com.sun.identity.saml2.protocol.ManageNameIDResponse)

Example 13 with ManageNameIDRequest

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

the class DoManageNameID method checkMNIResponse.

private static boolean checkMNIResponse(ManageNameIDResponse mniResponse, String realm, String hostEntityID, String hostRole, StringBuffer mniUserId) throws SAML2Exception, SessionException {
    boolean success = false;
    String remoteEntityID = mniResponse.getIssuer().getValue();
    String requestID = mniResponse.getInResponseTo();
    ManageNameIDRequestInfo reqInfo = getMNIRequestInfo(requestID, hostRole);
    if (reqInfo == null) {
        logError("invalidInResponseToInResponse", LogUtil.INVALID_MNI_RESPONSE, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("invalidInResponseToInResponse"));
    }
    String retCode = mniResponse.getStatus().getStatusCode().getValue();
    if (retCode.equalsIgnoreCase(SAML2Constants.SUCCESS)) {
        Object session = reqInfo.getSession();
        if (session == null) {
            logError("nullSSOToken", LogUtil.INVALID_SSOTOKEN, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("nullSSOToken"));
        }
        String userID = sessionProvider.getPrincipalName(session);
        mniUserId.append(userID);
        ManageNameIDRequest origMniReq = reqInfo.getManageNameIDRequest();
        NameID oldNameID = origMniReq.getNameID();
        List spFedSessions = null;
        NameIDInfo oldNameIDInfo = getNameIDInfo(userID, hostEntityID, remoteEntityID, hostRole, realm, oldNameID.getSPNameQualifier(), true);
        if (oldNameIDInfo == null) {
            debug.error("DoManageNameID.checkMNIResponse: NameIDInfo " + "not found.");
            return false;
        }
        // Terminate
        if (hostRole.equalsIgnoreCase(SAML2Constants.SP_ROLE)) {
            String infoKeyStr = oldNameIDInfo.getNameIDInfoKey().toValueString();
            spFedSessions = (List) SPCache.fedSessionListsByNameIDInfoKey.remove(infoKeyStr);
            removeInfoKeyFromSession(session, infoKeyStr);
            if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
                saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
            }
        } else {
            removeIDPFedSession(remoteEntityID, oldNameID.getValue());
        }
        if (!AccountUtils.removeAccountFederation(oldNameIDInfo, userID)) {
            // log termination failure
            logError("unableToTerminate", LogUtil.UNABLE_TO_TERMINATE, userID);
            return false;
        }
        if (origMniReq.getTerminate()) {
            // log termination success
            logAccess("requestSuccess", LogUtil.SUCCESS_FED_TERMINATION, userID);
            return true;
        }
        // newID case
        String newIDValue = origMniReq.getNewID().getValue();
        boolean isAffiliation = oldNameIDInfo.isAffiliation();
        String spNameQualifier = oldNameID.getSPNameQualifier();
        if (hostRole.equalsIgnoreCase(SAML2Constants.SP_ROLE)) {
            NameID newNameID = AssertionFactory.getInstance().createNameID();
            newNameID.setValue(oldNameID.getValue());
            newNameID.setFormat(oldNameID.getFormat());
            newNameID.setSPProvidedID(newIDValue);
            newNameID.setSPNameQualifier(spNameQualifier);
            newNameID.setNameQualifier(oldNameID.getNameQualifier());
            NameIDInfo newNameIDInfo = new NameIDInfo((isAffiliation ? spNameQualifier : hostEntityID), remoteEntityID, newNameID, hostRole, isAffiliation);
            String newInfoKeyStr = newNameIDInfo.getNameIDInfoKey().toValueString();
            if (spFedSessions != null) {
                SPCache.fedSessionListsByNameIDInfoKey.put(newInfoKeyStr, spFedSessions);
                if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
                    saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
                }
            }
            AccountUtils.setAccountFederation(newNameIDInfo, userID);
            try {
                String infoKeyAttribute = AccountUtils.getNameIDInfoKeyAttribute();
                String[] fromToken = sessionProvider.getProperty(session, infoKeyAttribute);
                if ((fromToken == null) || (fromToken.length == 0) || (fromToken[0] == null) || (fromToken[0].length() == 0)) {
                    String[] values = { newInfoKeyStr };
                    sessionProvider.setProperty(session, infoKeyAttribute, values);
                } else {
                    if (fromToken[0].indexOf(newInfoKeyStr) == -1) {
                        String[] values = { fromToken[0] + SAML2Constants.SECOND_DELIM + newInfoKeyStr };
                        sessionProvider.setProperty(session, infoKeyAttribute, values);
                    }
                }
            } catch (Exception e) {
                debug.message("DoManageNameID.checkMNIResponse:", e);
            }
        } else if (hostRole.equalsIgnoreCase(SAML2Constants.IDP_ROLE)) {
            NameID newNameID = AssertionFactory.getInstance().createNameID();
            newNameID.setValue(newIDValue);
            newNameID.setFormat(oldNameID.getFormat());
            newNameID.setSPProvidedID(oldNameID.getSPProvidedID());
            newNameID.setSPNameQualifier(spNameQualifier);
            newNameID.setNameQualifier(hostEntityID);
            NameIDInfo newNameIDInfo = new NameIDInfo(hostEntityID, (isAffiliation ? spNameQualifier : remoteEntityID), newNameID, SAML2Constants.IDP_ROLE, isAffiliation);
            AccountUtils.setAccountFederation(newNameIDInfo, userID);
            NameIDandSPpair pair = new NameIDandSPpair(newNameID, remoteEntityID);
            IDPSession idpSession = (IDPSession) IDPCache.idpSessionsBySessionID.get(sessionProvider.getSessionID(session));
            if (idpSession != null) {
                synchronized (IDPCache.idpSessionsByIndices) {
                    List list = (List) idpSession.getNameIDandSPpairs();
                    list.add(pair);
                }
            }
        }
        // log manage name id success
        logAccess("newNameIDSuccess", LogUtil.SUCCESS_NEW_NAMEID, userID);
        success = true;
    } else {
        logError("mniFailed", LogUtil.INVALID_MNI_RESPONSE, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("mniFailed"));
    }
    return success;
}
Also used : NameIDInfo(com.sun.identity.saml2.common.NameIDInfo) ManageNameIDRequest(com.sun.identity.saml2.protocol.ManageNameIDRequest) NameID(com.sun.identity.saml2.assertion.NameID) ServletException(javax.servlet.ServletException) 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) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) List(java.util.List)

Example 14 with ManageNameIDRequest

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

the class DoManageNameID method signMNIRequest.

public static void signMNIRequest(String certAlias, ManageNameIDRequest mniRequest) throws SAML2Exception {
    KeyProvider kp = KeyUtil.getKeyProviderInstance();
    if (kp == null) {
        SAML2Utils.debug.error("DoManageNameID.signMNIRequest: " + "Unable to get a key provider instance.");
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullKeyProvider"));
    }
    mniRequest.sign(kp.getPrivateKey(certAlias), kp.getX509Certificate(certAlias));
}
Also used : KeyProvider(com.sun.identity.saml.xmlsig.KeyProvider) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception)

Example 15 with ManageNameIDRequest

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

the class DoManageNameID method createManageNameIDRequest.

private static ManageNameIDRequest createManageNameIDRequest(Object session, String realm, String hostEntityID, String hostEntityRole, String remoteEntityID, String destination, boolean changeID, String affiliationID) throws SAML2Exception {
    String method = "DoManageNameID.createManageNameIDRequest: ";
    NameID nameID = null;
    String userID = null;
    try {
        userID = sessionProvider.getPrincipalName(session);
        nameID = getNameID(userID, hostEntityID, remoteEntityID, hostEntityRole, affiliationID, realm);
    } catch (SessionException e) {
        logError("invalidSSOToken", LogUtil.INVALID_SSOTOKEN, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
    }
    if (debug.messageEnabled()) {
        debug.message(method + "User ID : " + userID);
        debug.message(method + "NameID : " + nameID.toXMLString());
    }
    ManageNameIDRequest mniRequest = pf.createManageNameIDRequest();
    mniRequest.setID(SAML2Utils.generateID());
    mniRequest.setVersion(SAML2Constants.VERSION_2_0);
    mniRequest.setDestination(XMLUtils.escapeSpecialCharacters(destination));
    mniRequest.setIssuer(SAML2Utils.createIssuer(hostEntityID));
    mniRequest.setIssueInstant(new Date());
    setNameIDForMNIRequest(mniRequest, nameID, changeID, realm, hostEntityID, hostEntityRole, remoteEntityID);
    if (!changeID) {
        mniRequest.setTerminate(true);
    }
    return mniRequest;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) NameID(com.sun.identity.saml2.assertion.NameID) ManageNameIDRequest(com.sun.identity.saml2.protocol.ManageNameIDRequest) SessionException(com.sun.identity.plugin.session.SessionException) Date(java.util.Date)

Aggregations

SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)15 ManageNameIDRequest (com.sun.identity.saml2.protocol.ManageNameIDRequest)9 SessionException (com.sun.identity.plugin.session.SessionException)8 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)7 NameID (com.sun.identity.saml2.assertion.NameID)5 ManageNameIDServiceElement (com.sun.identity.saml2.jaxb.metadata.ManageNameIDServiceElement)5 ManageNameIDResponse (com.sun.identity.saml2.protocol.ManageNameIDResponse)5 IOException (java.io.IOException)5 SOAPException (javax.xml.soap.SOAPException)5 EncryptedID (com.sun.identity.saml2.assertion.EncryptedID)4 IDPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)4 SPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement)4 NewEncryptedID (com.sun.identity.saml2.protocol.NewEncryptedID)4 ServletException (javax.servlet.ServletException)4 NewID (com.sun.identity.saml2.protocol.NewID)3 Element (org.w3c.dom.Element)3 NameIDInfo (com.sun.identity.saml2.common.NameIDInfo)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 PrivateKey (java.security.PrivateKey)2 X509Certificate (java.security.cert.X509Certificate)2