Search in sources :

Example 46 with SPSSODescriptorElement

use of com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement in project OpenAM by OpenRock.

the class DoManageNameID method getSPManageNameIDConfig.

/**
     * Returns first ManageNameID configuration in an entity under
     * the realm.
     * @param realm The realm under which the entity resides.
     * @param entityId ID of the entity to be retrieved.
     * @param binding bind type need to has to be matched.
     * @return <code>ManageNameIDServiceElement</code> for the entity or null
     * @throws SAML2MetaException if unable to retrieve the first identity
     *                            provider's SSO configuration.
     * @throws SessionException invalid or expired single-sign-on session.
     */
public static ManageNameIDServiceElement getSPManageNameIDConfig(String realm, String entityId, String binding) throws SAML2MetaException, SessionException {
    ManageNameIDServiceElement mni = null;
    SPSSODescriptorElement spSSODesc = metaManager.getSPSSODescriptor(realm, entityId);
    if (spSSODesc == null) {
        return null;
    }
    List list = spSSODesc.getManageNameIDService();
    if ((list != null) && !list.isEmpty()) {
        if (binding == null) {
            return (ManageNameIDServiceElement) list.get(0);
        }
        Iterator it = list.iterator();
        while (it.hasNext()) {
            mni = (ManageNameIDServiceElement) it.next();
            if (binding.equalsIgnoreCase(mni.getBinding())) {
                break;
            }
        }
    }
    return mni;
}
Also used : ManageNameIDServiceElement(com.sun.identity.saml2.jaxb.metadata.ManageNameIDServiceElement) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) Iterator(java.util.Iterator) List(java.util.List)

Example 47 with SPSSODescriptorElement

use of com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement in project OpenAM by OpenRock.

the class DoManageNameID method verifyMNIRequest.

private static boolean verifyMNIRequest(ManageNameIDRequest mniRequest, String realm, String remoteEntity, String hostEntity, String hostEntityRole, String destination) throws SAML2Exception {
    String method = "verifyMNIRequest : ";
    if (debug.messageEnabled()) {
        debug.message(method + "realm is : " + realm);
        debug.message(method + "remoteEntity is : " + remoteEntity);
        debug.message(method + "Host Entity role is : " + hostEntityRole);
    }
    boolean needVerifySignature = SAML2Utils.getWantMNIRequestSigned(realm, hostEntity, hostEntityRole);
    if (!needVerifySignature) {
        if (debug.messageEnabled()) {
            debug.message(method + "MNIRequest doesn't need to be verified.");
        }
        return true;
    }
    boolean valid;
    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()) {
        valid = mniRequest.isSignatureValid(signingCerts);
        if (debug.messageEnabled()) {
            debug.message(method + "Signature is : " + valid);
        }
    } else {
        logError("missingSigningCertAlias.", LogUtil.METADATA_ERROR, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("missingSigningCertAlias"));
    }
    return valid;
}
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 48 with SPSSODescriptorElement

use of com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement in project OpenAM by OpenRock.

the class DoManageNameID method verifyMNIResponse.

private static boolean verifyMNIResponse(ManageNameIDResponse mniResponse, String realm, String remoteEntity, String hostEntity, String hostEntityRole, String destination) throws SAML2Exception, SessionException {
    String method = "verifyMNIResponse : ";
    if (debug.messageEnabled()) {
        debug.message(method + "realm is : " + realm);
        debug.message(method + "remoteEntity is : " + remoteEntity);
        debug.message(method + "Host Entity role is : " + hostEntityRole);
    }
    boolean needVerifySignature = SAML2Utils.getWantMNIResponseSigned(realm, hostEntity, hostEntityRole);
    if (!needVerifySignature) {
        if (debug.messageEnabled()) {
            debug.message(method + "MNIResponse doesn't need to be verified.");
        }
        return true;
    }
    boolean valid;
    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()) {
        valid = mniResponse.isSignatureValid(signingCerts);
        if (debug.messageEnabled()) {
            debug.message(method + "Signature is : " + valid);
        }
    } else {
        logError("missingSigningCertAlias", LogUtil.METADATA_ERROR, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("missingSigningCertAlias"));
    }
    return valid;
}
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 49 with SPSSODescriptorElement

use of com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement in project OpenAM by OpenRock.

the class SPACSUtils method getPrincipalWithoutLogin.

/**
     * Returns the username if there was one from the Assertion we were able to map into a local user account. Returns
     * null if not. Should only be used from the SP side. Should only be called in conjuncture with the Auth Module.
     * In addition, it performs what attribute federation it can.
     *
     * This method is a picked apart version of the "processResponse" function.
     */
public static String getPrincipalWithoutLogin(Subject assertionSubject, Assertion authnAssertion, String realm, String spEntityId, SAML2MetaManager metaManager, String idpEntityId, String storageKey) throws SAML2Exception {
    final EncryptedID encId = assertionSubject.getEncryptedID();
    final SPSSOConfigElement spssoconfig = metaManager.getSPSSOConfig(realm, spEntityId);
    final Set<PrivateKey> decryptionKeys = KeyUtil.getDecryptionKeys(spssoconfig);
    final SPAccountMapper acctMapper = SAML2Utils.getSPAccountMapper(realm, spEntityId);
    boolean needNameIDEncrypted = false;
    NameID nameId = assertionSubject.getNameID();
    String assertionEncryptedAttr = SAML2Utils.getAttributeValueFromSPSSOConfig(spssoconfig, SAML2Constants.WANT_ASSERTION_ENCRYPTED);
    if (assertionEncryptedAttr == null || !Boolean.parseBoolean(assertionEncryptedAttr)) {
        String idEncryptedStr = SAML2Utils.getAttributeValueFromSPSSOConfig(spssoconfig, SAML2Constants.WANT_NAMEID_ENCRYPTED);
        if (idEncryptedStr != null && Boolean.parseBoolean(idEncryptedStr)) {
            needNameIDEncrypted = true;
        }
    }
    if (needNameIDEncrypted && encId == null) {
        throw new SAML2Exception(SAML2Utils.bundle.getString("nameIDNotEncrypted"));
    }
    if (encId != null) {
        nameId = encId.decrypt(decryptionKeys);
    }
    SPSSODescriptorElement spDesc = null;
    try {
        spDesc = metaManager.getSPSSODescriptor(realm, spEntityId);
    } catch (SAML2MetaException ex) {
        SAML2Utils.debug.error("Unable to read SPSSODescription", ex);
    }
    if (spDesc == null) {
        throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
    }
    final String nameIDFormat = nameId.getFormat();
    if (nameIDFormat != null) {
        List spNameIDFormatList = spDesc.getNameIDFormat();
        if (CollectionUtils.isNotEmpty(spNameIDFormatList) && !spNameIDFormatList.contains(nameIDFormat)) {
            Object[] args = { nameIDFormat };
            throw new SAML2Exception(SAML2Utils.BUNDLE_NAME, "unsupportedNameIDFormatSP", args);
        }
    }
    final boolean isTransient = SAML2Constants.NAMEID_TRANSIENT_FORMAT.equals(nameIDFormat);
    final boolean isPersistent = SAML2Constants.PERSISTENT.equals(nameIDFormat);
    final boolean ignoreProfile = SAML2PluginsUtils.isIgnoredProfile(realm);
    final boolean shouldPersistNameID = isPersistent || (!isTransient && !ignoreProfile && acctMapper.shouldPersistNameIDFormat(realm, spEntityId, idpEntityId, nameIDFormat));
    String userName = null;
    boolean isNewAccountLink = false;
    try {
        if (shouldPersistNameID) {
            try {
                userName = SAML2Utils.getDataStoreProvider().getUserID(realm, SAML2Utils.getNameIDKeyMap(nameId, spEntityId, idpEntityId, realm, SAML2Constants.SP_ROLE));
            } catch (DataStoreProviderException dse) {
                throw new SAML2Exception(dse.getMessage());
            }
        }
        //if we can't get an already linked account, see if we'll be generating a new one based on federated data
        if (userName == null) {
            userName = acctMapper.getIdentity(authnAssertion, spEntityId, realm);
            //we'll use this later to inform us
            isNewAccountLink = true;
        }
    } catch (SAML2Exception se) {
        return null;
    }
    //if we're new and we're persistent, store the federation data in the user pref
    if (isNewAccountLink && isPersistent) {
        try {
            writeFedData(nameId, spEntityId, realm, metaManager, idpEntityId, userName, storageKey);
        } catch (SAML2Exception se) {
            return userName;
        }
    }
    return userName;
}
Also used : DataStoreProviderException(com.sun.identity.plugin.datastore.DataStoreProviderException) PrivateKey(java.security.PrivateKey) NameID(com.sun.identity.saml2.assertion.NameID) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) SPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.SPSSOConfigElement) EncryptedID(com.sun.identity.saml2.assertion.EncryptedID) SPAccountMapper(com.sun.identity.saml2.plugins.SPAccountMapper) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) List(java.util.List) ArrayList(java.util.ArrayList) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException)

Example 50 with SPSSODescriptorElement

use of com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement in project OpenAM by OpenRock.

the class SPSSOFederate method initiateAuthnRequest.

/**
     * Parses the request parameters and builds the Authentication
     * Request to sent to the IDP.
     *
     * @param request the HttpServletRequest.
     * @param response the HttpServletResponse.
     * @param spEntityID entityID of Service Provider.
     * @param idpEntityID entityID of Identity Provider.
     * @param paramsMap Map of all other parameters.The key in the
     *              map are the parameter names of the type String. 
     *              The values in the paramsMap are of the type List.
     *              Some of the possible keys are:RelayState,NameIDFormat,
     *              reqBinding, binding, AssertionConsumerServiceIndex,
     *              AttributeConsumingServiceIndex (currently not supported),
     *              isPassive, ForceAuthN, AllowCreate, Destination,
     *              AuthnContextDeclRef, AuthnContextClassRef,
     *              AuthComparison, Consent (currently not supported),
     *              AuthLevel, and sunamcompositeadvice.
     * @param auditor the auditor for logging SAML2 Events - may be null
     * @throws SAML2Exception if error initiating request to IDP.
     */
private static void initiateAuthnRequest(final HttpServletRequest request, final HttpServletResponse response, final String spEntityID, final String idpEntityID, final String realmName, final Map paramsMap, final SAML2EventLogger auditor) throws SAML2Exception {
    if (FSUtils.needSetLBCookieAndRedirect(request, response, false)) {
        return;
    }
    if (spEntityID == null) {
        SAML2Utils.debug.error("SPSSOFederate:Service Provider ID  is missing.");
        String[] data = { spEntityID };
        LogUtil.error(Level.INFO, LogUtil.INVALID_SP, data, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullSPEntityID"));
    }
    if (idpEntityID == null) {
        SAML2Utils.debug.error("SPSSOFederate: Identity Provider ID is missing .");
        String[] data = { idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.INVALID_IDP, data, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullIDPEntityID"));
    }
    String binding = getParameter(paramsMap, SAML2Constants.REQ_BINDING);
    if (binding == null) {
        binding = SAML2Constants.HTTP_REDIRECT;
    }
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message("SPSSOFederate: in initiateSSOFed");
        SAML2Utils.debug.message("SPSSOFederate: spEntityID is : " + spEntityID);
        SAML2Utils.debug.message("SPSSOFederate: idpEntityID : " + idpEntityID);
    }
    String realm = getRealm(realmName);
    try {
        // Retreive MetaData 
        if (sm == null) {
            throw new SAML2Exception(SAML2Utils.bundle.getString("errorMetaManager"));
        }
        Map spConfigAttrsMap = getAttrsMapForAuthnReq(realm, spEntityID);
        // get SPSSODescriptor
        SPSSODescriptorElement spsso = getSPSSOForAuthnReq(realm, spEntityID);
        if (spsso == null) {
            String[] data = { spEntityID };
            LogUtil.error(Level.INFO, LogUtil.SP_METADATA_ERROR, data, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
        }
        List extensionsList = getExtensionsList(spEntityID, realm);
        // get IDP Descriptor
        IDPSSODescriptorElement idpsso = getIDPSSOForAuthnReq(realm, idpEntityID);
        if (idpsso == null) {
            String[] data = { idpEntityID };
            LogUtil.error(Level.INFO, LogUtil.IDP_METADATA_ERROR, data, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
        }
        List ssoServiceList = idpsso.getSingleSignOnService();
        String ssoURL = getSSOURL(ssoServiceList, binding);
        if (ssoURL == null || ssoURL.length() == 0) {
            String[] data = { idpEntityID };
            LogUtil.error(Level.INFO, LogUtil.SSO_NOT_FOUND, data, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("ssoServiceNotfound"));
        }
        // create AuthnRequest 
        AuthnRequest authnRequest = createAuthnRequest(realm, spEntityID, paramsMap, spConfigAttrsMap, extensionsList, spsso, idpsso, ssoURL, false);
        if (null != auditor && null != authnRequest) {
            auditor.setRequestId(authnRequest.getID());
        }
        // invoke SP Adapter class if registered
        SAML2ServiceProviderAdapter spAdapter = SAML2Utils.getSPAdapterClass(spEntityID, realmName);
        if (spAdapter != null) {
            spAdapter.preSingleSignOnRequest(spEntityID, idpEntityID, realmName, request, response, authnRequest);
        }
        String authReqXMLString = authnRequest.toXMLString(true, true);
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message("SPSSOFederate: AuthnRequest:" + authReqXMLString);
        }
        // Default URL if relayState not present? in providerConfig?
        // TODO get Default URL from metadata 
        String relayState = getParameter(paramsMap, SAML2Constants.RELAY_STATE);
        // Validate the RelayState URL.
        SAML2Utils.validateRelayStateURL(realm, spEntityID, relayState, SAML2Constants.SP_ROLE);
        // check if relayState is present and get the unique
        // id which will be appended to the SSO URL before
        // redirecting.
        String relayStateID = null;
        if (relayState != null && relayState.length() > 0) {
            relayStateID = getRelayStateID(relayState, authnRequest.getID());
        }
        if (binding.equals(SAML2Constants.HTTP_POST)) {
            String encodedReqMsg = getPostBindingMsg(idpsso, spsso, spConfigAttrsMap, authnRequest);
            SAML2Utils.postToTarget(request, response, "SAMLRequest", encodedReqMsg, "RelayState", relayStateID, ssoURL);
        } else {
            String redirect = getRedirect(authReqXMLString, relayStateID, ssoURL, idpsso, spsso, spConfigAttrsMap);
            response.sendRedirect(redirect);
        }
        String[] data = { ssoURL };
        LogUtil.access(Level.INFO, LogUtil.REDIRECT_TO_IDP, data, null);
        AuthnRequestInfo reqInfo = new AuthnRequestInfo(request, response, realm, spEntityID, idpEntityID, authnRequest, relayState, paramsMap);
        synchronized (SPCache.requestHash) {
            SPCache.requestHash.put(authnRequest.getID(), reqInfo);
        }
        if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
            // sessionExpireTime is counted in seconds
            long sessionExpireTime = System.currentTimeMillis() / 1000 + SPCache.interval;
            String key = authnRequest.getID();
            try {
                SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(key, new AuthnRequestInfoCopy(reqInfo), sessionExpireTime);
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.message("SPSSOFederate.initiateAuthnRequest:" + " SAVE AuthnRequestInfoCopy for requestID " + key);
                }
            } catch (SAML2TokenRepositoryException e) {
                SAML2Utils.debug.error("SPSSOFederate.initiateAuthnRequest: There was a problem saving the " + "AuthnRequestInfoCopy in the SAML2 Token Repository for requestID " + key, e);
                throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
            }
        }
    } catch (IOException ioe) {
        SAML2Utils.debug.error("SPSSOFederate: Exception :", ioe);
        throw new SAML2Exception(SAML2Utils.bundle.getString("errorCreatingAuthnRequest"));
    } catch (SAML2MetaException sme) {
        SAML2Utils.debug.error("SPSSOFederate:Error retrieving metadata", sme);
        throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
    }
}
Also used : SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) IOException(java.io.IOException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) AuthnRequest(com.sun.identity.saml2.protocol.AuthnRequest) List(java.util.List) IDPList(com.sun.identity.saml2.protocol.IDPList) ArrayList(java.util.ArrayList) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) SAML2ServiceProviderAdapter(com.sun.identity.saml2.plugins.SAML2ServiceProviderAdapter) Map(java.util.Map) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Aggregations

SPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement)47 List (java.util.List)32 SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)29 ArrayList (java.util.ArrayList)25 IDPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)19 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)18 X509Certificate (java.security.cert.X509Certificate)11 SPSSOConfigElement (com.sun.identity.saml2.jaxb.entityconfig.SPSSOConfigElement)10 Iterator (java.util.Iterator)10 Map (java.util.Map)10 AssertionConsumerServiceElement (com.sun.identity.saml2.jaxb.metadata.AssertionConsumerServiceElement)9 SAML2MetaManager (com.sun.identity.saml2.meta.SAML2MetaManager)9 SAML2TokenRepositoryException (org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)8 Issuer (com.sun.identity.saml2.assertion.Issuer)7 AuthnRequest (com.sun.identity.saml2.protocol.AuthnRequest)7 IOException (java.io.IOException)7 HashMap (java.util.HashMap)7 SessionException (com.sun.identity.plugin.session.SessionException)6 EncryptedID (com.sun.identity.saml2.assertion.EncryptedID)5 EntityDescriptorElement (com.sun.identity.saml2.jaxb.metadata.EntityDescriptorElement)5