Search in sources :

Example 16 with SAML2Exception

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

the class SAML2TokenGenerationImpl method generate.

public String generate(SSOToken subjectToken, STSInstanceState stsInstanceState, TokenGenerationServiceInvocationState invocationState) throws TokenCreationException {
    final SAML2Config saml2Config = stsInstanceState.getConfig().getSaml2Config();
    if (saml2Config == null) {
        throw new TokenCreationException(ResourceException.BAD_REQUEST, "Invocation targets a SAML2 token, but no SAML2Config was specified in the published sts!");
    }
    final String subjectId = ssoTokenIdentity.validateAndGetTokenPrincipal(subjectToken);
    final Assertion assertion = AssertionFactory.getInstance().createAssertion();
    setVersionAndId(assertion);
    setIssuer(assertion, saml2Config);
    final Date issueInstant = new Date();
    setIssueInstant(assertion, issueInstant);
    final SAML2TokenGenerationState tokenGenerationState = invocationState.getSaml2TokenGenerationState();
    setConditions(assertion, saml2Config, issueInstant, tokenGenerationState.getSaml2SubjectConfirmation());
    setSubject(assertion, subjectId, saml2Config.getSpAcsUrl(), saml2Config, invocationState.getSaml2TokenGenerationState().getSaml2SubjectConfirmation(), issueInstant, tokenGenerationState.getProofTokenState());
    setAuthenticationStatements(assertion, saml2Config, tokenGenerationState.getAuthnContextClassRef());
    setAttributeStatements(assertion, subjectToken, saml2Config);
    setAuthzDecisionStatements(assertion, subjectToken, saml2Config);
    /*
        entering this branch handles both encryption and signing, as the encryption of the entire assertion must be
        proceeded by signing.
         */
    String assertionString;
    if (saml2Config.encryptAssertion()) {
        EncryptedAssertion encryptedAssertion = handleSingingAndEncryptionOfEntireAssertion(assertion, saml2Config, stsInstanceState);
        try {
            assertionString = encryptedAssertion.toXMLString(ASSERTION_TO_STRING_INCLUDE_NAMESPACE_PREFIX, ASSERTION_TO_STRING_DECLARE_NAMESPACE_PREFIX);
        } catch (SAML2Exception e) {
            throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Exception caught calling Assertion.toXMLString: " + e, e);
        }
    } else {
        if (saml2Config.encryptAttributes()) {
            encryptAttributeStatement(assertion, saml2Config, stsInstanceState);
        }
        if (saml2Config.encryptNameID()) {
            encryptNameID(assertion, saml2Config, stsInstanceState);
        }
        if (saml2Config.signAssertion()) {
            signAssertion(assertion, stsInstanceState);
        }
        try {
            assertionString = assertion.toXMLString(ASSERTION_TO_STRING_INCLUDE_NAMESPACE_PREFIX, ASSERTION_TO_STRING_DECLARE_NAMESPACE_PREFIX);
        } catch (SAML2Exception e) {
            throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Exception caught calling Assertion.toXMLString: " + e, e);
        }
    }
    if (stsInstanceState.getConfig().persistIssuedTokensInCTS()) {
        try {
            ctsTokenPersistence.persistToken(invocationState.getStsInstanceId(), TokenType.SAML2, assertionString, subjectId, issueInstant.getTime(), saml2Config.getTokenLifetimeInSeconds());
        } catch (CTSTokenPersistenceException e) {
            throw new TokenCreationException(e.getCode(), e.getMessage(), e);
        }
    }
    return assertionString;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) SAML2Config(org.forgerock.openam.sts.config.user.SAML2Config) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) Assertion(com.sun.identity.saml2.assertion.Assertion) TokenCreationException(org.forgerock.openam.sts.TokenCreationException) CTSTokenPersistenceException(org.forgerock.openam.sts.CTSTokenPersistenceException) Date(java.util.Date) SAML2TokenGenerationState(org.forgerock.openam.sts.service.invocation.SAML2TokenGenerationState)

Example 17 with SAML2Exception

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

the class SAML2TokenGenerationImpl method encryptNameID.

private void encryptNameID(Assertion assertion, SAML2Config saml2Config, STSInstanceState stsInstanceState) throws TokenCreationException {
    /*
        The null checks below model IDPSSOUtil#signAndEncryptResponseComponents. The Subject and NameID will
        never be null when generated by the DefaultSubjectProvider, but when generated by a custom provider, this
        invariant is not assured.
         */
    Subject subject = assertion.getSubject();
    if (subject == null) {
        throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "In SAML2TokenGenerationImpl, saml2Config specifies encryption of NameID, but " + "encapsulating subject is null.");
    }
    NameID nameID = subject.getNameID();
    if (nameID == null) {
        throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "In SAML2TokenGenerationImpl, saml2Config specifies encryption of NameID, but " + "NameID in subject is null.");
    }
    try {
        EncryptedID encryptedNameID = nameID.encrypt(stsInstanceState.getSAML2CryptoProvider().getSPX509Certificate(saml2Config.getEncryptionKeyAlias()).getPublicKey(), saml2Config.getEncryptionAlgorithm(), saml2Config.getEncryptionAlgorithmStrength(), saml2Config.getSpEntityId());
        if (encryptedNameID == null) {
            throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "In SAML2TokenGenerationImpl, the EncryptedID returned from NameID#encrypt is null.");
        }
        subject.setEncryptedID(encryptedNameID);
        // reset NameID
        subject.setNameID(null);
        assertion.setSubject(subject);
    } catch (SAML2Exception e) {
        throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Exception thrown encrypting NameID in SAML2TokenGenerationImpl: " + e, e);
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) NameID(com.sun.identity.saml2.assertion.NameID) TokenCreationException(org.forgerock.openam.sts.TokenCreationException) EncryptedID(com.sun.identity.saml2.assertion.EncryptedID) Subject(com.sun.identity.saml2.assertion.Subject)

Example 18 with SAML2Exception

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

the class SAML2TokenGenerationImpl method setVersionAndId.

private void setVersionAndId(Assertion assertion) throws TokenCreationException {
    try {
        assertion.setVersion("2.0");
        assertion.setID(SAML2SDKUtils.generateID());
    } catch (SAML2Exception e) {
        throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Exception caught setting version and/or id in SAML2TokenGenerationImpl: " + e, e);
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) TokenCreationException(org.forgerock.openam.sts.TokenCreationException)

Example 19 with SAML2Exception

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

the class SPACSUtils method getSAMLAttributes.

/**
     * Gets the attributes from an assert's AttributeStates.
     *
     * @param assertion The assertion from which to pull the AttributeStates.
     * @param needAttributeEncrypted Whether attributes must be encrypted (or else rejected).
     * @param privateKeys Private keys used to decrypt those encrypted attributes.
     * @return a list of attributes pulled from the provided assertion.
     */
public static List<Attribute> getSAMLAttributes(Assertion assertion, boolean needAttributeEncrypted, Set<PrivateKey> privateKeys) {
    List<Attribute> attrList = null;
    if (assertion != null) {
        List<AttributeStatement> statements = assertion.getAttributeStatements();
        if (CollectionUtils.isNotEmpty(statements)) {
            for (AttributeStatement statement : statements) {
                List<Attribute> attributes = statement.getAttribute();
                if (needAttributeEncrypted && attributes != null && !attributes.isEmpty()) {
                    SAML2Utils.debug.error("Attribute not encrypted.");
                    return null;
                }
                if (attributes != null) {
                    if (attrList == null) {
                        attrList = new ArrayList<>();
                    }
                    attrList.addAll(attributes);
                }
                List<EncryptedAttribute> encAttrs = statement.getEncryptedAttribute();
                if (encAttrs != null) {
                    for (EncryptedAttribute encAttr : encAttrs) {
                        if (attrList == null) {
                            attrList = new ArrayList<>();
                        }
                        try {
                            attrList.add((encAttr).decrypt(privateKeys));
                        } catch (SAML2Exception se) {
                            SAML2Utils.debug.error("Decryption error:", se);
                            return null;
                        }
                    }
                }
            }
        }
    }
    return attrList;
}
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) AttributeStatement(com.sun.identity.saml2.assertion.AttributeStatement)

Example 20 with SAML2Exception

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

the class SPACSUtils method getResponseFromArtifact.

// Retrieves response using artifact profile.
private static Response getResponseFromArtifact(String samlArt, String hostEntityId, HttpServletRequest request, HttpServletResponse response, String orgName, SAML2MetaManager sm) throws SAML2Exception, IOException {
    // decide which IDP and which artifact resolution service
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message("SPACSUtils.getResponseFromArtifact: " + "samlArt = " + samlArt);
    }
    Artifact art = null;
    try {
        art = ProtocolFactory.getInstance().createArtifact(samlArt.trim());
        String[] data = { samlArt.trim() };
        LogUtil.access(Level.INFO, LogUtil.RECEIVED_ARTIFACT, data, null);
    } catch (SAML2Exception se) {
        SAML2Utils.debug.error("SPACSUtils.getResponseFromArtifact: " + "Unable to decode and parse artifact string:" + samlArt);
        SAMLUtils.sendError(request, response, response.SC_BAD_REQUEST, "errorObtainArtifact", SAML2Utils.bundle.getString("errorObtainArtifact"));
        throw se;
    }
    String idpEntityID = getIDPEntityID(art, request, response, orgName, sm);
    IDPSSODescriptorElement idp = null;
    try {
        idp = sm.getIDPSSODescriptor(orgName, idpEntityID);
    } catch (SAML2MetaException se) {
        String[] data = { orgName, idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.IDP_META_NOT_FOUND, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "failedToGetIDPSSODescriptor", se.getMessage());
        throw se;
    }
    String location = getIDPArtifactResolutionServiceUrl(art.getEndpointIndex(), idpEntityID, idp, request, response);
    // create ArtifactResolve message
    ArtifactResolve resolve = null;
    SOAPMessage resMsg = null;
    try {
        resolve = ProtocolFactory.getInstance().createArtifactResolve();
        resolve.setID(SAML2Utils.generateID());
        resolve.setVersion(SAML2Constants.VERSION_2_0);
        resolve.setIssueInstant(new Date());
        resolve.setArtifact(art);
        resolve.setDestination(XMLUtils.escapeSpecialCharacters(location));
        Issuer issuer = AssertionFactory.getInstance().createIssuer();
        issuer.setValue(hostEntityId);
        resolve.setIssuer(issuer);
        String needArtiResolveSigned = SAML2Utils.getAttributeValueFromSSOConfig(orgName, idpEntityID, SAML2Constants.IDP_ROLE, SAML2Constants.WANT_ARTIFACT_RESOLVE_SIGNED);
        if (needArtiResolveSigned != null && needArtiResolveSigned.equals("true")) {
            // or save it somewhere?
            String signAlias = getAttributeValueFromSPSSOConfig(orgName, hostEntityId, sm, SAML2Constants.SIGNING_CERT_ALIAS);
            if (signAlias == null) {
                throw new SAML2Exception(SAML2Utils.bundle.getString("missingSigningCertAlias"));
            }
            KeyProvider kp = KeyUtil.getKeyProviderInstance();
            if (kp == null) {
                throw new SAML2Exception(SAML2Utils.bundle.getString("nullKeyProvider"));
            }
            resolve.sign(kp.getPrivateKey(signAlias), kp.getX509Certificate(signAlias));
        }
        String resolveString = resolve.toXMLString(true, true);
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message("SPACSUtils.getResponseFromArtifact: " + "ArtifactResolve=" + resolveString);
        }
        SOAPConnection con = SOAPCommunicator.getInstance().openSOAPConnection();
        SOAPMessage msg = SOAPCommunicator.getInstance().createSOAPMessage(resolveString, true);
        IDPSSOConfigElement config = null;
        config = sm.getIDPSSOConfig(orgName, idpEntityID);
        location = SAML2Utils.fillInBasicAuthInfo(config, location);
        resMsg = con.call(msg, location);
    } catch (SAML2Exception s2e) {
        SAML2Utils.debug.error("SPACSUtils.getResponseFromArtifact: " + "couldn't create ArtifactResolve:", s2e);
        String[] data = { hostEntityId, art.getArtifactValue() };
        LogUtil.error(Level.INFO, LogUtil.CANNOT_CREATE_ARTIFACT_RESOLVE, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "errorCreateArtifactResolve", SAML2Utils.bundle.getString("errorCreateArtifactResolve"));
        throw s2e;
    } catch (SOAPException se) {
        SAML2Utils.debug.error("SPACSUtils.getResponseFromGet: " + "couldn't get ArtifactResponse. SOAP error:", se);
        String[] data = { hostEntityId, location };
        LogUtil.error(Level.INFO, LogUtil.CANNOT_GET_SOAP_RESPONSE, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "errorInSOAPCommunication", SAML2Utils.bundle.getString("errorInSOAPCommunication"));
        throw new SAML2Exception(se.getMessage());
    }
    Response result = getResponseFromSOAP(resMsg, resolve, request, response, idpEntityID, idp, orgName, hostEntityId, sm);
    String[] data = { hostEntityId, idpEntityID, art.getArtifactValue(), "" };
    if (LogUtil.isAccessLoggable(Level.FINE)) {
        data[3] = result.toXMLString();
    }
    LogUtil.access(Level.INFO, LogUtil.GOT_RESPONSE_FROM_ARTIFACT, data, null);
    return result;
}
Also used : KeyProvider(com.sun.identity.saml.xmlsig.KeyProvider) Issuer(com.sun.identity.saml2.assertion.Issuer) SOAPConnection(javax.xml.soap.SOAPConnection) IDPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.IDPSSOConfigElement) SOAPMessage(javax.xml.soap.SOAPMessage) Artifact(com.sun.identity.saml2.protocol.Artifact) Date(java.util.Date) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Response(com.sun.identity.saml2.protocol.Response) ArtifactResponse(com.sun.identity.saml2.protocol.ArtifactResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) ArtifactResolve(com.sun.identity.saml2.protocol.ArtifactResolve) SOAPException(javax.xml.soap.SOAPException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Aggregations

SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)275 ArrayList (java.util.ArrayList)92 List (java.util.List)86 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)72 Element (org.w3c.dom.Element)64 SessionException (com.sun.identity.plugin.session.SessionException)56 IOException (java.io.IOException)51 SPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement)44 Map (java.util.Map)44 HashMap (java.util.HashMap)43 Iterator (java.util.Iterator)43 Issuer (com.sun.identity.saml2.assertion.Issuer)42 Date (java.util.Date)40 SOAPException (javax.xml.soap.SOAPException)39 SAML2TokenRepositoryException (org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)39 X509Certificate (java.security.cert.X509Certificate)36 NodeList (org.w3c.dom.NodeList)36 IDPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)35 Node (org.w3c.dom.Node)34 Response (com.sun.identity.saml2.protocol.Response)30