Search in sources :

Example 86 with Assertion

use of com.sun.identity.saml2.assertion.Assertion in project OpenAM by OpenRock.

the class UtilProxySAMLAuthenticatorLookup method retrieveAuthenticationFromCache.

@Override
public void retrieveAuthenticationFromCache() throws SessionException, ServerFaultException, ClientFaultException {
    final String classMethod = "UtilProxySAMLAuthenticatorLookup.retrieveAuthenticationFromCache: ";
    // the second visit, the user has already authenticated
    // retrieve the cache authn request and relay state
    // We need the session to pass it to the IDP Adapter preSendResponse
    SessionProvider sessionProvider = SessionManager.getProvider();
    try {
        data.setSession(sessionProvider.getSession(request));
        data.getEventAuditor().setSSOTokenId(data.getSession());
    } catch (SessionException se) {
        SAML2Utils.debug.error("An error occurred while retrieving the session: " + se.getMessage());
        data.setSession(null);
    }
    // Get the cached Authentication Request and Relay State before
    // invoking the IDP Adapter
    CacheObject cacheObj;
    synchronized (IDPCache.authnRequestCache) {
        cacheObj = (CacheObject) IDPCache.authnRequestCache.get(data.getRequestID());
    }
    if (cacheObj != null) {
        data.setAuthnRequest((AuthnRequest) cacheObj.getObject());
    }
    data.setRelayState((String) IDPCache.relayStateCache.get(data.getRequestID()));
    if (!isSessionValid(sessionProvider)) {
        return;
    }
    // Invoke the IDP Adapter after the user has been authenticated
    if (preSendResponse(request, response, data)) {
        return;
    }
    synchronized (IDPCache.authnRequestCache) {
        cacheObj = (CacheObject) IDPCache.authnRequestCache.remove(data.getRequestID());
    }
    if (cacheObj != null) {
        data.setAuthnRequest((AuthnRequest) cacheObj.getObject());
    }
    synchronized (IDPCache.idpAuthnContextCache) {
        cacheObj = (CacheObject) IDPCache.idpAuthnContextCache.remove(data.getRequestID());
    }
    if (cacheObj != null) {
        data.setMatchingAuthnContext((AuthnContext) cacheObj.getObject());
    }
    data.setRelayState((String) IDPCache.relayStateCache.remove(data.getRequestID()));
    if (data.getAuthnRequest() == null) {
        authNotAvailable();
        return;
    }
    SAML2Utils.debug.message("{} RequestID= {}", classMethod, data.getRequestID());
    boolean isSessionUpgrade = false;
    if (CollectionUtils.isNotEmpty(IDPCache.isSessionUpgradeCache)) {
        isSessionUpgrade = IDPCache.isSessionUpgradeCache.contains(data.getRequestID());
    }
    if (isSessionUpgrade) {
        IDPSession oldSess = (IDPSession) IDPCache.oldIDPSessionCache.remove(data.getRequestID());
        String sessionIndex = IDPSSOUtil.getSessionIndex(data.getSession());
        if (StringUtils.isNotEmpty(sessionIndex)) {
            IDPCache.idpSessionsByIndices.put(sessionIndex, oldSess);
            final FedMonAgent agent = MonitorManager.getAgent();
            if (agent != null && agent.isRunning()) {
                final FedMonSAML2Svc saml2Svc = MonitorManager.getSAML2Svc();
                if (saml2Svc != null) {
                    saml2Svc.setIdpSessionCount(IDPCache.idpSessionsByIndices.size());
                }
            }
        }
    }
    if (data.getSession() != null) {
        // call multi-federation protocol to set the protocol
        MultiProtocolUtils.addFederationProtocol(data.getSession(), SingleLogoutManager.SAML2);
    }
    // generate assertion response
    data.setSpEntityID(data.getAuthnRequest().getIssuer().getValue());
    NameIDPolicy policy = data.getAuthnRequest().getNameIDPolicy();
    String nameIDFormat = (policy == null) ? null : policy.getFormat();
    try {
        IDPSSOUtil.sendResponseToACS(request, response, out, data.getSession(), data.getAuthnRequest(), data.getSpEntityID(), data.getIdpEntityID(), data.getIdpMetaAlias(), data.getRealm(), nameIDFormat, data.getRelayState(), data.getMatchingAuthnContext());
    } catch (SAML2Exception se) {
        SAML2Utils.debug.error(classMethod + "Unable to do sso or federation.", se);
        throw new ServerFaultException(data.getIdpAdapter(), SSO_OR_FEDERATION_ERROR, se.getMessage());
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) IDPSession(com.sun.identity.saml2.profile.IDPSession) FedMonSAML2Svc(com.sun.identity.plugin.monitoring.FedMonSAML2Svc) NameIDPolicy(com.sun.identity.saml2.protocol.NameIDPolicy) ServerFaultException(com.sun.identity.saml2.profile.ServerFaultException) SessionException(com.sun.identity.plugin.session.SessionException) CacheObject(com.sun.identity.saml2.profile.CacheObject) FedMonAgent(com.sun.identity.plugin.monitoring.FedMonAgent) SessionProvider(com.sun.identity.plugin.session.SessionProvider)

Example 87 with Assertion

use of com.sun.identity.saml2.assertion.Assertion in project OpenAM by OpenRock.

the class OAuth2Saml2GrantSPAdapter method postSingleSignOnSuccess.

/**
     * @{inheritDoc}
     */
public boolean postSingleSignOnSuccess(String hostedEntityID, String realm, HttpServletRequest request, HttpServletResponse response, PrintWriter out, Object session, AuthnRequest authnRequest, Response ssoResponse, String profile, boolean isFederation) throws SAML2Exception {
    AssertionImpl assertion = (AssertionImpl) ssoResponse.getAssertion().get(0);
    StringBuilder sb = new StringBuilder();
    try {
        //post assertion to the OAuth 2 token endpoint using the saml2 grant.
        sb.append("<form name=\"postForm\" action=\"");
        sb.append(hostedEntityID);
        if (hostedEntityID.endsWith("/")) {
            sb.append("oauth2/access_token");
        } else {
            sb.append("/oauth2/access_token");
        }
        sb.append("?realm=" + (StringUtils.isEmpty(realm) ? "/" : realm));
        sb.append("\" method=\"post\">");
        sb.append("<input type=\"hidden\" name=\"grant_type\" value=\"");
        sb.append(OAuth2Constants.SAML20.GRANT_TYPE_URI);
        sb.append("\">");
        sb.append("<input type=\"hidden\" name=\"assertion\" value=\"");
        sb.append(Base64.encode(assertion.toXMLString(false, false).getBytes("UTF-8")));
        sb.append("\">");
        sb.append("<input type=\"hidden\" name=\"client_id\" value=\"");
        sb.append(hostedEntityID);
        sb.append("\">");
        sb.append("</form>");
        sb.append("<script language=\"Javascript\">");
        sb.append("document.postForm.submit();");
        sb.append("</script>");
        out.print(sb.toString());
    } catch (UnsupportedEncodingException e) {
        SAML2Utils.debug.error("OAuth2Saml2GrantSPAdapter.postSingleSignOnSuccess: Unsuppored Encoding Exception: " + e.getMessage());
    } catch (IOException e) {
        SAML2Utils.debug.error("OAuth2Saml2GrantSPAdapter.postSingleSignOnSuccess: IOException: " + e.getMessage());
    }
    return true;
}
Also used : AssertionImpl(com.sun.identity.saml2.assertion.impl.AssertionImpl) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException)

Example 88 with Assertion

use of com.sun.identity.saml2.assertion.Assertion in project OpenAM by OpenRock.

the class Saml2GrantTypeHandler method validAssertion.

private boolean validAssertion(Assertion assertion, String deploymentURL) throws SAML2Exception {
    //must contain issuer
    final Issuer issuer = assertion.getIssuer();
    if (issuer == null) {
        logger.error("Issuer does not exist");
        return false;
    }
    /**
         * The Assertion MUST contain <Conditions> element with an
         * <AudienceRestriction> element with an <Audience> element
         * containing a URI reference that identifies the authorization
         * server, or the service provider SAML entity of its controlling
         * domain, as an intended audience.  The token endpoint URL of the
         * authorization server MAY be used as an acceptable value for an
         *       <Audience> element.  The authorization server MUST verify that it
         * is an intended audience for the Assertion.
         *
         */
    final Conditions conditions = assertion.getConditions();
    if (conditions == null) {
        logger.error("Saml2BearerServerResource.validAssertion(): Conditions does not exist");
        return false;
    }
    final List<AudienceRestriction> audienceRestriction = conditions.getAudienceRestrictions();
    if (audienceRestriction == null || audienceRestriction.isEmpty()) {
        logger.error("Saml2BearerServerResource.validAssertion(): Audience Restriction does not exist");
        return false;
    }
    boolean found = false;
    logger.trace("Saml2BearerServerResource.validAssertion(): URL of authorization server: " + deploymentURL);
    for (final AudienceRestriction restriction : audienceRestriction) {
        final List<String> audiences = restriction.getAudience();
        if (audiences == null || audiences.isEmpty()) {
            continue;
        }
        for (final String audience : audiences) {
            String deployURL = deploymentURL;
            String aud = audience;
            //check for the url with and without trailing /
            if (deployURL.endsWith("/")) {
                deployURL = deploymentURL.substring(0, deployURL.length() - 1);
            }
            if (aud.endsWith("/")) {
                aud = aud.substring(0, aud.length() - 1);
            }
            if (aud.equalsIgnoreCase(deployURL)) {
                found = true;
            }
        }
    }
    if (found == false) {
        logger.error("Didn't find the oauth2 provider in audience restrictions");
        return false;
    }
    /**
         * The Assertion MUST contain a <Subject> element.  The subject MAY
         * identify the resource owner for whom the access token is being
         * requested.  For client authentication, the Subject MUST be the
         * "client_id" of the OAuth client.  When using an Assertion as an
         * authorization grant, the Subject SHOULD identify an authorized
         * accessor for whom the access token is being requested (typically
         * the resource owner, or an authorized delegate).  Additional
         * information identifying the subject/principal of the transaction
         * MAY be included in an <AttributeStatement>.
         */
    final Subject subject = assertion.getSubject();
    if (subject == null) {
        logger.error("Subject does not exist");
        return false;
    }
    final String resourceOwner = subject.getNameID().getValue();
    /**
         * The Assertion MUST have an expiry that limits the time window
         * during which it can be used.  The expiry can be expressed either
         * as the NotOnOrAfter attribute of the <Conditions> element or as
         * the NotOnOrAfter attribute of a suitable <SubjectConfirmationData>
         * element.
         */
    /**
         * The <Subject> element MUST contain at least one
         * <SubjectConfirmation> element that allows the authorization server
         * to confirm it as a Bearer Assertion.  Such a <SubjectConfirmation>
         * element MUST have a Method attribute with a value of
         * "urn:oasis:names:tc:SAML:2.0:cm:bearer".  The
         * <SubjectConfirmation> element MUST contain a
         * <SubjectConfirmationData> element, unless the Assertion has a
         * suitable NotOnOrAfter attribute on the <Conditions> element, in
         * which case the <SubjectConfirmationData> element MAY be omitted.
         * When present, the <SubjectConfirmationData> element MUST have a
         * Recipient attribute with a value indicating the token endpoint URL
         * of the authorization server (or an acceptable alias).  The
         * authorization server MUST verify that the value of the Recipient
         * attribute matches the token endpoint URL (or an acceptable alias)
         * to which the Assertion was delivered.  The
         * <SubjectConfirmationData> element MUST have a NotOnOrAfter
         * attribute that limits the window during which the Assertion can be
         * confirmed.  The <SubjectConfirmationData> element MAY also contain
         * an Address attribute limiting the client address from which the
         * Assertion can be delivered.  Verification of the Address is at the
         * discretion of the authorization server.
         */
    final List<SubjectConfirmation> subjectConfirmations = subject.getSubjectConfirmation();
    found = false;
    if (subjectConfirmations == null || subjectConfirmations.isEmpty()) {
        logger.error("Subject Confirmations does not exist");
        return false;
    }
    //if conditions is expired assertion is expired
    if (!assertion.isTimeValid()) {
        logger.error("Assertion expired");
        return false;
    } else {
        found = true;
    }
    for (final SubjectConfirmation subjectConfirmation : subjectConfirmations) {
        if (subjectConfirmation.getMethod() == null) {
            continue;
        }
        if (subjectConfirmation.getMethod().equalsIgnoreCase(OAuth2Constants.SAML20.SUBJECT_CONFIRMATION_METHOD)) {
            final SubjectConfirmationData subjectConfirmationData = subjectConfirmation.getSubjectConfirmationData();
            if (subjectConfirmationData == null) {
                continue;
            } else if (subjectConfirmationData.getNotOnOrAfter().before(new Date()) && subjectConfirmationData.getRecipient().equalsIgnoreCase(deploymentURL)) {
                found = true;
            }
        //TODO check Client Address
        }
    }
    if (!found) {
        logger.error("Assertion expired or subject expired");
        return false;
    }
    if (!assertion.isSigned()) {
        logger.error("Assertion must be signed");
        return false;
    }
    if (!SAMLUtils.checkSignatureValid(assertion.toXMLString(), "ID", issuer.getValue())) {
        logger.error("Assertion signature verification failed");
        return false;
    }
    return true;
}
Also used : AudienceRestriction(com.sun.identity.saml2.assertion.AudienceRestriction) SubjectConfirmation(com.sun.identity.saml2.assertion.SubjectConfirmation) Issuer(com.sun.identity.saml2.assertion.Issuer) SubjectConfirmationData(com.sun.identity.saml2.assertion.SubjectConfirmationData) Conditions(com.sun.identity.saml2.assertion.Conditions) Subject(com.sun.identity.saml2.assertion.Subject) Date(java.util.Date)

Example 89 with Assertion

use of com.sun.identity.saml2.assertion.Assertion in project OpenAM by OpenRock.

the class SAML2TokenGenerationImpl method encryptAttributeStatement.

@SuppressWarnings("unchecked")
private void encryptAttributeStatement(Assertion assertion, SAML2Config saml2Config, STSInstanceState stsInstanceState) throws TokenCreationException {
    final PublicKey keyEncryptionKey = stsInstanceState.getSAML2CryptoProvider().getSPX509Certificate(saml2Config.getEncryptionKeyAlias()).getPublicKey();
    final String encryptionAlgorithm = saml2Config.getEncryptionAlgorithm();
    final int algorithmStrength = saml2Config.getEncryptionAlgorithmStrength();
    final String spEntityID = saml2Config.getSpEntityId();
    try {
        List<AttributeStatement> originalAttributeStatements = assertion.getAttributeStatements();
        if ((originalAttributeStatements != null) && (originalAttributeStatements.size() > 0)) {
            List<AttributeStatement> encryptedAttributeStatements = new ArrayList<>(originalAttributeStatements.size());
            for (AttributeStatement originalStatement : originalAttributeStatements) {
                List<Attribute> originalAttributes = originalStatement.getAttribute();
                if ((originalAttributes == null) || (originalAttributes.size() == 0)) {
                    continue;
                }
                List<EncryptedAttribute> encryptedAttributes = new ArrayList<>(originalAttributes.size());
                for (Attribute originalAttribute : originalAttributes) {
                    EncryptedAttribute encryptedAttribute = originalAttribute.encrypt(keyEncryptionKey, encryptionAlgorithm, algorithmStrength, spEntityID);
                    if (encryptedAttribute == null) {
                        throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "In SAML2TokenGenerationImpl, " + "attribute encryption invocation returned null.");
                    }
                    encryptedAttributes.add(encryptedAttribute);
                }
                originalStatement.setEncryptedAttribute(encryptedAttributes);
                originalStatement.setAttribute(Collections.EMPTY_LIST);
                encryptedAttributeStatements.add(originalStatement);
            }
            assertion.setAttributeStatements(encryptedAttributeStatements);
        }
    } catch (SAML2Exception e) {
        throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "In SAML2TokenGenerationImpl, exception " + "caught encrypting assertion attributes: " + e, e);
    }
}
Also used : EncryptedAttribute(com.sun.identity.saml2.assertion.EncryptedAttribute) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Attribute(com.sun.identity.saml2.assertion.Attribute) EncryptedAttribute(com.sun.identity.saml2.assertion.EncryptedAttribute) PublicKey(java.security.PublicKey) AttributeStatement(com.sun.identity.saml2.assertion.AttributeStatement) ArrayList(java.util.ArrayList) TokenCreationException(org.forgerock.openam.sts.TokenCreationException)

Example 90 with Assertion

use of com.sun.identity.saml2.assertion.Assertion in project OpenAM by OpenRock.

the class SAML2TokenGenerationImpl method signAssertion.

private void signAssertion(Assertion assertion, STSInstanceState instanceState) throws TokenCreationException {
    final SAML2CryptoProvider saml2CryptoProvider = instanceState.getSAML2CryptoProvider();
    final SAML2Config saml2Config = instanceState.getConfig().getSaml2Config();
    String signatureKeyPassword;
    try {
        signatureKeyPassword = new String(saml2Config.getSignatureKeyPassword(), AMSTSConstants.UTF_8_CHARSET_ID);
    } catch (UnsupportedEncodingException e) {
        throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Could not obtain string representation of signature key password in SAML2TokenGenerationImpl: ");
    }
    /*
        Note: the cert alias and private-key alias are the same. If there is a key entry in the keystore, it seems like
        they are represented by the same alias.
         */
    PrivateKey privateKey = saml2CryptoProvider.getIDPPrivateKey(saml2Config.getSignatureKeyAlias(), signatureKeyPassword);
    try {
        assertion.sign(privateKey, saml2CryptoProvider.getIDPX509Certificate(saml2Config.getSignatureKeyAlias()));
    } catch (SAML2Exception e) {
        throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Exception caught signing assertion in SAML2TokenGenerationImpl: " + e, e);
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) SAML2Config(org.forgerock.openam.sts.config.user.SAML2Config) SAML2CryptoProvider(org.forgerock.openam.sts.tokengeneration.saml2.xmlsig.SAML2CryptoProvider) PrivateKey(java.security.PrivateKey) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TokenCreationException(org.forgerock.openam.sts.TokenCreationException)

Aggregations

SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)53 ArrayList (java.util.ArrayList)42 List (java.util.List)42 Assertion (com.sun.identity.saml2.assertion.Assertion)30 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)24 Date (java.util.Date)24 EncryptedAssertion (com.sun.identity.saml2.assertion.EncryptedAssertion)20 Issuer (com.sun.identity.saml2.assertion.Issuer)16 SPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement)16 Response (com.sun.identity.saml2.protocol.Response)16 Iterator (java.util.Iterator)15 HttpServletResponse (javax.servlet.http.HttpServletResponse)13 SessionException (com.sun.identity.plugin.session.SessionException)12 IOException (java.io.IOException)12 SAML2TokenRepositoryException (org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)11 NameID (com.sun.identity.saml2.assertion.NameID)10 PrivateKey (java.security.PrivateKey)10 AttributeStatement (com.sun.identity.saml2.assertion.AttributeStatement)8 Subject (com.sun.identity.saml2.assertion.Subject)8 SAML2MetaManager (com.sun.identity.saml2.meta.SAML2MetaManager)8