Search in sources :

Example 16 with SPSSODescriptorElement

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

the class IDPProxyUtil method sendProxyAuthnRequest.

/**
     * Sends a new AuthnRequest to the authenticating provider. 
     * @param authnRequest original AuthnRequest sent by the service provider.
     * @param preferredIDP IDP to be proxied. 
     * @param spSSODescriptor SPSSO Descriptor Element
     * @param hostedEntityId hosted provider ID 
     * @param request HttpServletRequest 
     * @param response HttpServletResponse
     * @param realm Realm
     * @param relayState the Relay State 
     * @param originalBinding The binding used to send the original AuthnRequest.
     * @exception SAML2Exception for any SAML2 failure.
     * @exception IOException if there is a failure in redirection.
     */
public static void sendProxyAuthnRequest(AuthnRequest authnRequest, String preferredIDP, SPSSODescriptorElement spSSODescriptor, String hostedEntityId, HttpServletRequest request, HttpServletResponse response, String realm, String relayState, String originalBinding) throws SAML2Exception, IOException {
    String classMethod = "IDPProxyUtil.sendProxyAuthnRequest: ";
    String destination = null;
    SPSSODescriptorElement localDescriptor = null;
    SPSSOConfigElement localDescriptorConfig = null;
    IDPSSODescriptorElement idpDescriptor = null;
    String binding;
    try {
        idpDescriptor = IDPSSOUtil.metaManager.getIDPSSODescriptor(realm, preferredIDP);
        List<SingleSignOnServiceElement> ssoServiceList = idpDescriptor.getSingleSignOnService();
        SingleSignOnServiceElement endpoint = getMatchingSSOEndpoint(ssoServiceList, originalBinding);
        if (endpoint == null) {
            SAML2Utils.debug.error(classMethod + "Single Sign-on service is not found for the proxying IDP.");
            throw new SAML2Exception(SAML2Utils.bundle.getString("ssoServiceNotFoundIDPProxy"));
        }
        binding = endpoint.getBinding();
        destination = endpoint.getLocation();
        localDescriptor = IDPSSOUtil.metaManager.getSPSSODescriptor(realm, hostedEntityId);
        localDescriptorConfig = IDPSSOUtil.metaManager.getSPSSOConfig(realm, hostedEntityId);
    } catch (SAML2MetaException e) {
        SAML2Utils.debug.error(classMethod, e);
        throw new SAML2Exception(e.getMessage());
    }
    AuthnRequest newAuthnRequest = getNewAuthnRequest(hostedEntityId, destination, realm, authnRequest);
    // invoke SP Adapter class if registered
    SAML2ServiceProviderAdapter spAdapter = SAML2Utils.getSPAdapterClass(hostedEntityId, realm);
    if (spAdapter != null) {
        spAdapter.preSingleSignOnRequest(hostedEntityId, preferredIDP, realm, request, response, newAuthnRequest);
    }
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message(classMethod + "New Authentication request:" + newAuthnRequest.toXMLString());
    }
    String requestID = newAuthnRequest.getID();
    // save the AuthnRequest in the IDPCache so that it can be
    // retrieved later when the user successfully authenticates
    IDPCache.authnRequestCache.put(requestID, newAuthnRequest);
    // save the original AuthnRequest
    IDPCache.proxySPAuthnReqCache.put(requestID, authnRequest);
    boolean signingNeeded = idpDescriptor.isWantAuthnRequestsSigned() || localDescriptor.isAuthnRequestsSigned();
    // 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 = SPSSOFederate.getRelayStateID(relayState, authnRequest.getID());
    }
    if (binding.equals(SAML2Constants.HTTP_POST)) {
        if (signingNeeded) {
            String certAlias = SPSSOFederate.getParameter(SAML2MetaUtils.getAttributes(localDescriptorConfig), SAML2Constants.SIGNING_CERT_ALIAS);
            SPSSOFederate.signAuthnRequest(certAlias, newAuthnRequest);
        }
        String authXMLString = newAuthnRequest.toXMLString(true, true);
        String encodedReqMsg = SAML2Utils.encodeForPOST(authXMLString);
        SAML2Utils.postToTarget(request, response, "SAMLRequest", encodedReqMsg, "RelayState", relayStateID, destination);
    } else {
        String authReqXMLString = newAuthnRequest.toXMLString(true, true);
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + " AuthnRequest: " + authReqXMLString);
        }
        String encodedXML = SAML2Utils.encodeForRedirect(authReqXMLString);
        StringBuffer queryString = new StringBuffer().append(SAML2Constants.SAML_REQUEST).append(SAML2Constants.EQUAL).append(encodedXML);
        //TODO:  should it be newAuthnRequest??? 
        if (relayStateID != null && relayStateID.length() > 0) {
            queryString.append("&").append(SAML2Constants.RELAY_STATE).append("=").append(URLEncDec.encode(relayStateID));
        }
        StringBuffer redirectURL = new StringBuffer().append(destination).append(destination.contains("?") ? "&" : "?");
        if (signingNeeded) {
            String certAlias = SPSSOFederate.getParameter(SAML2MetaUtils.getAttributes(localDescriptorConfig), SAML2Constants.SIGNING_CERT_ALIAS);
            String signedQueryStr = SPSSOFederate.signQueryString(queryString.toString(), certAlias);
            redirectURL.append(signedQueryStr);
        } else {
            redirectURL.append(queryString);
        }
        response.sendRedirect(redirectURL.toString());
    }
    String[] data = { destination };
    LogUtil.access(Level.INFO, LogUtil.REDIRECT_TO_SP, data, null);
    AuthnRequestInfo reqInfo = new AuthnRequestInfo(request, response, realm, hostedEntityId, preferredIDP, newAuthnRequest, relayState, null);
    synchronized (SPCache.requestHash) {
        SPCache.requestHash.put(requestID, reqInfo);
    }
    if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
        try {
            // sessionExpireTime is counted in seconds
            long sessionExpireTime = System.currentTimeMillis() / 1000 + SPCache.interval;
            SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(requestID, new AuthnRequestInfoCopy(reqInfo), sessionExpireTime);
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + " SAVE AuthnRequestInfoCopy for requestID " + requestID);
            }
        } catch (SAML2TokenRepositoryException se) {
            SAML2Utils.debug.error(classMethod + " SAVE AuthnRequestInfoCopy for requestID " + requestID + ", failed!", se);
        }
    }
}
Also used : SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) SPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.SPSSOConfigElement) SingleSignOnServiceElement(com.sun.identity.saml2.jaxb.metadata.SingleSignOnServiceElement) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) AuthnRequest(com.sun.identity.saml2.protocol.AuthnRequest) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) SAML2ServiceProviderAdapter(com.sun.identity.saml2.plugins.SAML2ServiceProviderAdapter) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Example 17 with SPSSODescriptorElement

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

the class IDPSSOUtil method getSPSSODescriptor.

/**
     * Returns the service provider's SSO descriptor in an entity under the realm.
     * @param realm The realm under which the entity resides.
     * @param spEntityID ID of the SP entity to be retrieved.
     * @param classMethod the calling class method
     * @return <code>SPSSODescriptorElement</code> for the entity
     * @throws SAML2Exception if entity is not found
     */
private static SPSSODescriptorElement getSPSSODescriptor(String realm, String spEntityID, String classMethod) throws SAML2Exception {
    SPSSODescriptorElement spSSODescriptor = null;
    if (metaManager == null) {
        SAML2Utils.debug.error(classMethod + "Unable to get meta manager.");
        throw new SAML2Exception(SAML2Utils.bundle.getString("errorMetaManager"));
    }
    try {
        spSSODescriptor = metaManager.getSPSSODescriptor(realm, spEntityID);
        if (spSSODescriptor == null) {
            SAML2Utils.debug.error(classMethod + "Unable to get SP SSO Descriptor from metadata, descriptor is null.");
            String[] data = { spEntityID };
            LogUtil.error(Level.INFO, LogUtil.SP_METADATA_ERROR, data, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
        }
    } catch (SAML2MetaException sme) {
        SAML2Utils.debug.error(classMethod + "Unable to get SP SSO Descriptor from metadata, descriptor is null.");
        String[] data = { spEntityID };
        LogUtil.error(Level.INFO, LogUtil.SP_METADATA_ERROR, data, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
    }
    return spSSODescriptor;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException)

Example 18 with SPSSODescriptorElement

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

the class SAML2Utils method verifyResponse.

/**
     * Verifies single sign on <code>Response</code> and returns information
     * to SAML2 auth module for further processing. This method is used by
     * SAML2 auth module only.
     *
     * @param httpRequest    HttpServletRequest
     * @param httpResponse   HttpServletResponse
     * @param response       Single Sign On <code>Response</code>.
     * @param orgName        name of the realm or organization the provider is in.
     * @param hostEntityId   Entity ID of the hosted provider.
     * @param profileBinding Profile binding used.
     * @return A Map of information extracted from the Response. The keys of
     * map are:
     * <code>SAML2Constants.SUBJECT</code>,
     * <code>SAML2Constants.POST_ASSERTION</code>,
     * <code>SAML2Constants.ASSERTIONS</code>,
     * <code>SAML2Constants.SESSION_INDEX</code>,
     * <code>SAML2Constants.AUTH_LEVEL</code>,
     * <code>SAML2Constants.MAX_SESSION_TIME</code>.
     * @throws SAML2Exception if the Response is not valid according to the
     *                        processing rules.
     */
public static Map verifyResponse(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final Response response, final String orgName, final String hostEntityId, final String profileBinding) throws SAML2Exception {
    final String method = "SAML2Utils.verifyResponse:";
    if (response == null || orgName == null || orgName.length() == 0) {
        if (debug.messageEnabled()) {
            debug.message(method + "response or orgName is null.");
        }
        throw new SAML2Exception(bundle.getString("nullInput"));
    }
    String respID = response.getID();
    AuthnRequestInfo reqInfo = null;
    String inRespToResp = response.getInResponseTo();
    if (inRespToResp != null && inRespToResp.length() != 0) {
        reqInfo = (AuthnRequestInfo) SPCache.requestHash.get(inRespToResp);
        if (reqInfo == null) {
            if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
                // Attempt to read AuthnRequestInfoCopy from SAML2 repository
                AuthnRequestInfoCopy reqInfoCopy = null;
                try {
                    reqInfoCopy = (AuthnRequestInfoCopy) SAML2FailoverUtils.retrieveSAML2Token(inRespToResp);
                } catch (SAML2TokenRepositoryException se) {
                    debug.error(method + "AuthnRequestInfoCopy" + " unable to retrieve from SAML2 repository for inResponseTo: " + inRespToResp);
                }
                if (reqInfoCopy != null) {
                    // Get back the AuthnRequestInfo
                    reqInfo = reqInfoCopy.getAuthnRequestInfo(httpRequest, httpResponse);
                    if (debug.messageEnabled()) {
                        debug.message(method + "AuthnRequestInfoCopy" + " retrieved from SAML2 repository for inResponseTo: " + inRespToResp);
                    }
                } else {
                    debug.error(method + "InResponseTo attribute in Response" + " is invalid: " + inRespToResp + ", SAML2 failover is enabled");
                    String[] data = { respID };
                    LogUtil.error(Level.INFO, LogUtil.INVALID_INRESPONSETO_RESPONSE, data, null);
                    throw new SAML2Exception(bundle.getString("invalidInResponseToInResponse"));
                }
            } else {
                AuthnRequestInfoCopy reqInfoCopy = (AuthnRequestInfoCopy) SAML2Store.getTokenFromStore(inRespToResp);
                if (reqInfoCopy != null) {
                    // Get back the AuthnRequestInfo
                    reqInfo = reqInfoCopy.getAuthnRequestInfo(httpRequest, httpResponse);
                    if (debug.messageEnabled()) {
                        debug.message(method + "AuthnRequestInfoCopy" + " retrieved from SAML2 repository for inResponseTo: " + inRespToResp);
                    }
                } else {
                    debug.error(method + "InResponseTo attribute in Response" + " is invalid: " + inRespToResp + ", SAML2 failover is enabled");
                    String[] data = { respID };
                    LogUtil.error(Level.INFO, LogUtil.INVALID_INRESPONSETO_RESPONSE, data, null);
                    throw new SAML2Exception(bundle.getString("invalidInResponseToInResponse"));
                }
            }
        }
    }
    // reqInfo can remain null and will do for IDP initiated SSO requests
    // invoke SP Adapter
    SAML2ServiceProviderAdapter spAdapter = SAML2Utils.getSPAdapterClass(hostEntityId, orgName);
    if (spAdapter != null) {
        AuthnRequest authnRequest = null;
        if (reqInfo != null) {
            authnRequest = reqInfo.getAuthnRequest();
        }
        spAdapter.preSingleSignOnProcess(hostEntityId, orgName, httpRequest, httpResponse, authnRequest, response, profileBinding);
    }
    String idpEntityId = null;
    Issuer respIssuer = response.getIssuer();
    if (respIssuer != null) {
        // optional
        if (!isSourceSiteValid(respIssuer, orgName, hostEntityId)) {
            if (debug.messageEnabled()) {
                debug.message(method + "Issuer in Response is not valid.");
            }
            String[] data = { hostEntityId, orgName, respID };
            LogUtil.error(Level.INFO, LogUtil.INVALID_ISSUER_RESPONSE, data, null);
            throw new SAML2Exception(bundle.getString("invalidIssuerInResponse"));
        } else {
            idpEntityId = respIssuer.getValue();
        }
    }
    Status status = response.getStatus();
    if (status == null || !status.getStatusCode().getValue().equals(SAML2Constants.SUCCESS)) {
        String statusCode = (status == null) ? "" : status.getStatusCode().getValue();
        if (debug.messageEnabled()) {
            debug.message(method + "Response's status code is not success: " + statusCode);
        }
        String[] data = { respID, "" };
        if (LogUtil.isErrorLoggable(Level.FINE)) {
            data[1] = statusCode;
        }
        LogUtil.error(Level.INFO, LogUtil.WRONG_STATUS_CODE, data, null);
        if (SAML2Constants.RESPONDER.equals(statusCode)) {
            //In case of passive authentication the NoPassive response will be sent using two StatusCode nodes:
            //the outer StatusCode will be Responder and the inner StatusCode will contain the NoPassive URN
            StatusCode secondLevelStatusCode = status.getStatusCode().getStatusCode();
            if (secondLevelStatusCode != null && SAML2Constants.NOPASSIVE.equals(secondLevelStatusCode.getValue())) {
                throw new SAML2Exception(SAML2Utils.BUNDLE_NAME, "noPassiveResponse", null);
            }
        } else if (SAML2Constants.REQUESTER.equals(statusCode)) {
            // when is AllowCreate=false mode the auth module gets here with a
            // statusCode of urn:oasis:names:tc:SAML:2.0:status:Requester
            StatusCode secondLevelStatusCode = status.getStatusCode().getStatusCode();
            if (secondLevelStatusCode != null && SAML2Constants.INVALID_NAME_ID_POLICY.equals(secondLevelStatusCode.getValue())) {
                throw new SAML2Exception(SAML2Utils.BUNDLE_NAME, "nameIDMReqInvalidNameIDPolicy", null);
            }
        }
        throw new SAML2Exception(bundle.getString("invalidStatusCodeInResponse"));
    }
    if (saml2MetaManager == null) {
        throw new SAML2Exception(bundle.getString("nullMetaManager"));
    }
    SPSSOConfigElement spConfig = null;
    SPSSODescriptorElement spDesc = null;
    spConfig = saml2MetaManager.getSPSSOConfig(orgName, hostEntityId);
    spDesc = saml2MetaManager.getSPSSODescriptor(orgName, hostEntityId);
    if (debug.messageEnabled()) {
        debug.message(method + "binding is :" + profileBinding);
    }
    // SAML spec processing
    //  4.1.4.3   Verify any signatures present on the assertion(s) or the response
    boolean responseIsSigned = false;
    if (response.isSigned()) {
        IDPSSODescriptorElement idpSSODescriptor = null;
        try {
            idpSSODescriptor = saml2MetaManager.getIDPSSODescriptor(orgName, idpEntityId);
        } catch (SAML2MetaException sme) {
            String[] data = { orgName, idpEntityId };
            LogUtil.error(Level.INFO, LogUtil.IDP_METADATA_ERROR, data, null);
            throw new SAML2Exception(sme);
        }
        if (idpSSODescriptor != null) {
            Set<X509Certificate> verificationCerts = KeyUtil.getVerificationCerts(idpSSODescriptor, idpEntityId, SAML2Constants.IDP_ROLE);
            if (CollectionUtils.isEmpty(verificationCerts) || !response.isSignatureValid(verificationCerts)) {
                debug.error(method + "Response is not signed or signature is not valid.");
                String[] data = { orgName, hostEntityId, idpEntityId };
                LogUtil.error(Level.INFO, LogUtil.POST_RESPONSE_INVALID_SIGNATURE, data, null);
                throw new SAML2Exception(bundle.getString("invalidSignInResponse"));
            }
        } else {
            String[] data = { idpEntityId };
            LogUtil.error(Level.INFO, LogUtil.IDP_METADATA_ERROR, data, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
        }
        responseIsSigned = true;
    }
    if (debug.messageEnabled()) {
        debug.message(method + "responseIsSigned is :" + responseIsSigned);
    }
    // assertion encryption check
    boolean needAssertionEncrypted = false;
    String assertionEncryptedAttr = getAttributeValueFromSPSSOConfig(spConfig, SAML2Constants.WANT_ASSERTION_ENCRYPTED);
    needAssertionEncrypted = Boolean.parseBoolean(assertionEncryptedAttr);
    if (debug.messageEnabled()) {
        debug.message(method + "NeedAssertionEncrypted is :" + needAssertionEncrypted);
    }
    List<Assertion> assertions = response.getAssertion();
    if (needAssertionEncrypted && !CollectionUtils.isEmpty(assertions)) {
        String[] data = { respID };
        LogUtil.error(Level.INFO, LogUtil.ASSERTION_NOT_ENCRYPTED, data, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("assertionNotEncrypted"));
    }
    Set<PrivateKey> decryptionKeys;
    List<EncryptedAssertion> encAssertions = response.getEncryptedAssertion();
    if (encAssertions != null) {
        decryptionKeys = KeyUtil.getDecryptionKeys(spConfig);
        for (EncryptedAssertion encAssertion : encAssertions) {
            Assertion assertion = encAssertion.decrypt(decryptionKeys);
            if (assertions == null) {
                assertions = new ArrayList<>();
            }
            assertions.add(assertion);
        }
    }
    if (CollectionUtils.isEmpty(assertions)) {
        if (debug.messageEnabled()) {
            debug.message(method + "no assertion in the Response.");
        }
        String[] data = { respID };
        LogUtil.error(Level.INFO, LogUtil.MISSING_ASSERTION, data, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("missingAssertion"));
    }
    boolean wantAssertionsSigned = spDesc.isWantAssertionsSigned();
    if (debug.messageEnabled()) {
        debug.message(method + "wantAssertionsSigned is :" + wantAssertionsSigned);
    }
    // validate the assertions
    Map smap = null;
    Map bearerMap = null;
    IDPSSODescriptorElement idp = null;
    Set<X509Certificate> verificationCerts = null;
    boolean allAssertionsSigned = true;
    for (Assertion assertion : assertions) {
        String assertionID = assertion.getID();
        Issuer issuer = assertion.getIssuer();
        if (!isSourceSiteValid(issuer, orgName, hostEntityId)) {
            debug.error("assertion's source site is not valid.");
            String[] data = { assertionID };
            LogUtil.error(Level.INFO, LogUtil.INVALID_ISSUER_ASSERTION, data, null);
            throw new SAML2Exception(bundle.getString("invalidIssuerInAssertion"));
        }
        if (idpEntityId == null) {
            idpEntityId = issuer.getValue();
        } else {
            if (!idpEntityId.equals(issuer.getValue())) {
                if (debug.messageEnabled()) {
                    debug.message(method + "Issuer in Assertion doesn't " + "match the Issuer in Response or other " + "Assertions in the Response.");
                }
                String[] data = { assertionID };
                LogUtil.error(Level.INFO, LogUtil.MISMATCH_ISSUER_ASSERTION, data, null);
                throw new SAML2Exception(SAML2Utils.bundle.getString("mismatchIssuer"));
            }
        }
        if (assertion.isSigned()) {
            if (verificationCerts == null) {
                idp = saml2MetaManager.getIDPSSODescriptor(orgName, idpEntityId);
                verificationCerts = KeyUtil.getVerificationCerts(idp, idpEntityId, SAML2Constants.IDP_ROLE);
            }
            if (CollectionUtils.isEmpty(verificationCerts) || !assertion.isSignatureValid(verificationCerts)) {
                debug.error(method + "Assertion is not signed or signature is not valid.");
                String[] data = { assertionID };
                LogUtil.error(Level.INFO, LogUtil.INVALID_SIGNATURE_ASSERTION, data, null);
                throw new SAML2Exception(bundle.getString("invalidSignatureOnAssertion"));
            }
        } else {
            allAssertionsSigned = false;
        }
        List authnStmts = assertion.getAuthnStatements();
        if (authnStmts != null && !authnStmts.isEmpty()) {
            Subject subject = assertion.getSubject();
            if (subject == null) {
                continue;
            }
            List subjectConfirms = subject.getSubjectConfirmation();
            if (subjectConfirms == null || subjectConfirms.isEmpty()) {
                continue;
            }
            bearerMap = isBearerSubjectConfirmation(subjectConfirms, inRespToResp, spDesc, spConfig, assertionID);
            if (!((Boolean) bearerMap.get(SAML2Constants.IS_BEARER))) {
                continue;
            }
            boolean foundAssertion = false;
            if ((SPCache.assertionByIDCache != null) && (SPCache.assertionByIDCache.containsKey(assertionID))) {
                foundAssertion = true;
            }
            if ((!foundAssertion) && SAML2FailoverUtils.isSAML2FailoverEnabled()) {
                try {
                    if (SAML2FailoverUtils.retrieveSAML2Token(assertionID) != null) {
                        foundAssertion = true;
                    }
                } catch (SAML2TokenRepositoryException e) {
                    if (debug.messageEnabled()) {
                        debug.message("Session not found in AMTokenSAML2Repository.", e);
                    }
                }
            }
            if (foundAssertion) {
                debug.error("Bearer Assertion is one time use only!");
                throw new SAML2Exception(bundle.getString("usedBearAssertion"));
            }
            checkAudience(assertion.getConditions(), hostEntityId, assertionID);
            if (smap == null) {
                smap = fillMap(authnStmts, subject, assertion, assertions, reqInfo, inRespToResp, orgName, hostEntityId, idpEntityId, spConfig, (Date) bearerMap.get(SAML2Constants.NOTONORAFTER));
            }
        }
    // end of having authnStmt
    }
    if (smap == null) {
        debug.error("No Authentication Assertion in Response.");
        throw new SAML2Exception(bundle.getString("missingAuthnAssertion"));
    }
    // the enclosing element
    if (wantAssertionsSigned && !(responseIsSigned || allAssertionsSigned)) {
        debug.error(method + "WantAssertionsSigned is true and response or all assertions are not signed");
        String[] data = { orgName, hostEntityId, idpEntityId };
        LogUtil.error(Level.INFO, LogUtil.INVALID_SIGNATURE_ASSERTION, data, null);
        throw new SAML2Exception(bundle.getString("assertionNotSigned"));
    }
    // signing each individual <Assertion> element or by signing the <Response> element.
    if (profileBinding.equals(SAML2Constants.HTTP_POST)) {
        boolean wantPostResponseSigned = SAML2Utils.wantPOSTResponseSigned(orgName, hostEntityId, SAML2Constants.SP_ROLE);
        if (debug.messageEnabled()) {
            debug.message(method + "wantPostResponseSigned is :" + wantPostResponseSigned);
        }
        if (wantPostResponseSigned && !responseIsSigned) {
            debug.error(method + "wantPostResponseSigned is true but response is not signed");
            String[] data = { orgName, hostEntityId, idpEntityId };
            LogUtil.error(Level.INFO, LogUtil.POST_RESPONSE_INVALID_SIGNATURE, data, null);
            throw new SAML2Exception(bundle.getString("responseNotSigned"));
        }
        if (!responseIsSigned && !allAssertionsSigned) {
            debug.error(method + "WantAssertionsSigned is true but some or all assertions are not signed");
            String[] data = { orgName, hostEntityId, idpEntityId };
            LogUtil.error(Level.INFO, LogUtil.INVALID_SIGNATURE_ASSERTION, data, null);
            throw new SAML2Exception(bundle.getString("assertionNotSigned"));
        }
    }
    return smap;
}
Also used : PrivateKey(java.security.PrivateKey) Issuer(com.sun.identity.saml2.assertion.Issuer) AuthnRequestInfo(com.sun.identity.saml2.profile.AuthnRequestInfo) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) StatusCode(com.sun.identity.saml2.protocol.StatusCode) ArrayList(java.util.ArrayList) List(java.util.List) AuthnRequestInfoCopy(com.sun.identity.saml2.profile.AuthnRequestInfoCopy) SAML2ServiceProviderAdapter(com.sun.identity.saml2.plugins.SAML2ServiceProviderAdapter) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) Status(com.sun.identity.saml2.protocol.Status) SPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.SPSSOConfigElement) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) Assertion(com.sun.identity.saml2.assertion.Assertion) X509Certificate(java.security.cert.X509Certificate) Subject(com.sun.identity.saml2.assertion.Subject) Date(java.util.Date) AuthnRequest(com.sun.identity.saml2.protocol.AuthnRequest) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) Map(java.util.Map) HashMap(java.util.HashMap) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Example 19 with SPSSODescriptorElement

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

the class SAML2Utils method isSPProfileBindingSupported.

/**
     * Checks if a profile binding is suppported by a SP.
     *
     * @param realm      Realm the SP is in.
     * @param spEntityID SP entity id.
     * @param profile    name of the profile/service
     * @param binding    binding to be checked on
     * @return <code>true</code> if the binding is supported;
     * <code>false</code> otherwise.
     */
public static boolean isSPProfileBindingSupported(String realm, String spEntityID, String profile, String binding) {
    if ((saml2MetaManager == null) || (realm == null) || (spEntityID == null) || (profile == null) || (binding == null)) {
        return false;
    }
    try {
        SPSSODescriptorElement spDescriptor = saml2MetaManager.getSPSSODescriptor(realm, spEntityID);
        List services = null;
        if (SAML2Constants.ACS_SERVICE.equals(profile)) {
            services = spDescriptor.getAssertionConsumerService();
        } else if (SAML2Constants.SLO_SERVICE.equals(profile)) {
            services = spDescriptor.getSingleLogoutService();
        } else if (SAML2Constants.MNI_SERVICE.equals(profile)) {
            services = spDescriptor.getManageNameIDService();
        }
        if ((services != null) && (!services.isEmpty())) {
            Iterator iter = services.iterator();
            while (iter.hasNext()) {
                EndpointType endpoint = (EndpointType) iter.next();
                if (binding.equals(endpoint.getBinding())) {
                    return true;
                }
            }
        }
    } catch (SAML2MetaException me) {
        debug.error("SAML2Utils.isSPProfileBindingSupported:", me);
    }
    return false;
}
Also used : SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) Iterator(java.util.Iterator) EndpointType(com.sun.identity.saml2.jaxb.metadata.EndpointType) ArrayList(java.util.ArrayList) List(java.util.List) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException)

Example 20 with SPSSODescriptorElement

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

the class DoManageNameID method setNameIDForMNIRequest.

private static void setNameIDForMNIRequest(ManageNameIDRequest mniRequest, NameID nameID, boolean changeID, String realm, String hostEntity, String hostEntityRole, String remoteEntity) throws SAML2Exception {
    String method = "DoManageNameID.setNameIDForMNIRequest: ";
    boolean needEncryptIt = false;
    if (hostEntityRole.equalsIgnoreCase(SAML2Constants.IDP_ROLE)) {
        needEncryptIt = SAML2Utils.getWantNameIDEncrypted(realm, remoteEntity, SAML2Constants.SP_ROLE);
    } else {
        needEncryptIt = SAML2Utils.getWantNameIDEncrypted(realm, remoteEntity, SAML2Constants.IDP_ROLE);
    }
    NewID newID = null;
    if (changeID) {
        String newIDValue = SAML2Utils.createNameIdentifier();
        newID = ProtocolFactory.getInstance().createNewID(newIDValue);
        mniRequest.setNewID(newID);
    }
    mniRequest.setNameID(nameID);
    if (!needEncryptIt) {
        if (debug.messageEnabled()) {
            debug.message(method + "NamID doesn't need to be encrypted.");
        }
        return;
    }
    EncInfo encInfo = null;
    if (hostEntityRole.equalsIgnoreCase(SAML2Constants.IDP_ROLE)) {
        SPSSODescriptorElement spSSODesc = metaManager.getSPSSODescriptor(realm, remoteEntity);
        encInfo = KeyUtil.getEncInfo(spSSODesc, remoteEntity, SAML2Constants.SP_ROLE);
    } else {
        IDPSSODescriptorElement idpSSODesc = metaManager.getIDPSSODescriptor(realm, remoteEntity);
        encInfo = KeyUtil.getEncInfo(idpSSODesc, remoteEntity, SAML2Constants.IDP_ROLE);
    }
    if (debug.messageEnabled()) {
        debug.message(method + "realm is : " + realm);
        debug.message(method + "hostEntity is : " + hostEntity);
        debug.message(method + "Host Entity role is : " + hostEntityRole);
        debug.message(method + "remoteEntity is : " + remoteEntity);
    }
    if (encInfo == null) {
        logError("UnableToFindEncryptKeyInfo", LogUtil.METADATA_ERROR, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("UnableToFindEncryptKeyInfo"));
    }
    EncryptedID encryptedID = nameID.encrypt(encInfo.getWrappingKey(), encInfo.getDataEncAlgorithm(), encInfo.getDataEncStrength(), remoteEntity);
    // This non-encrypted NameID will be removed just 
    // after saveMNIRequestInfo and just before it send to 
    mniRequest.setEncryptedID(encryptedID);
    if (newID != null) {
        NewEncryptedID newEncID = newID.encrypt(encInfo.getWrappingKey(), encInfo.getDataEncAlgorithm(), encInfo.getDataEncStrength(), remoteEntity);
        // This non-encrypted newID will be removed just 
        // after saveMNIRequestInfo and just before it send to 
        mniRequest.setNewEncryptedID(newEncID);
    }
}
Also used : EncInfo(com.sun.identity.saml2.key.EncInfo) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) NewID(com.sun.identity.saml2.protocol.NewID) NewEncryptedID(com.sun.identity.saml2.protocol.NewEncryptedID) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) NewEncryptedID(com.sun.identity.saml2.protocol.NewEncryptedID) EncryptedID(com.sun.identity.saml2.assertion.EncryptedID) 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