Search in sources :

Example 21 with Attribute

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

the class IDPArtifactResolution method onMessage.

/**
     * This method generates a <code>SOAPMessage</code> containing the
     * <code>ArtifactResponse</code> that is corresponding to the
     * <code>ArtifactResolve</code> contained in the 
     * <code>SOAPMessage</code> passed in.
     *
     * @param message <code>SOAPMessage</code> contains a
     *             <code>ArtifactResolve</code> 
     * @param request the <code>HttpServletRequest</code> object
     * @param realm the realm to where the identity provider belongs
     * @param idpEntityID the entity id of the identity provider 
     * 
     * @return <code>SOAPMessage</code> contains the 
     *             <code>ArtifactResponse</code>
     * @exception SAML2Exception if the operation is not successful
     */
public static SOAPMessage onMessage(SOAPMessage message, HttpServletRequest request, HttpServletResponse response, String realm, String idpEntityID) throws SAML2Exception {
    String classMethod = "IDPArtifactResolution.onMessage: ";
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message(classMethod + "Entering onMessage().");
    }
    Element reqElem = SOAPCommunicator.getInstance().getSamlpElement(message, "ArtifactResolve");
    ArtifactResolve artResolve = ProtocolFactory.getInstance().createArtifactResolve(reqElem);
    if (artResolve == null) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "no valid ArtifactResolve node found in SOAP body.");
        }
        return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, "noArtifactResolve", null);
    }
    String spEntityID = artResolve.getIssuer().getValue();
    if (!SAML2Utils.isSourceSiteValid(artResolve.getIssuer(), realm, idpEntityID)) {
        SAML2Utils.debug.error(classMethod + spEntityID + " is not trusted issuer.");
        String[] data = { idpEntityID, realm, artResolve.getID() };
        LogUtil.error(Level.INFO, LogUtil.INVALID_ISSUER_REQUEST, data, null);
        return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, "invalidIssuerInRequest", null);
    }
    SPSSODescriptorElement spSSODescriptor = null;
    try {
        spSSODescriptor = IDPSSOUtil.metaManager.getSPSSODescriptor(realm, spEntityID);
    } catch (SAML2MetaException sme) {
        SAML2Utils.debug.error(classMethod, sme);
        spSSODescriptor = null;
    }
    if (spSSODescriptor == null) {
        SAML2Utils.debug.error(classMethod + "Unable to get SP SSO Descriptor from meta.");
        return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.SERVER_FAULT, "metaDataError", null);
    }
    OrderedSet acsSet = SPSSOFederate.getACSUrl(spSSODescriptor, SAML2Constants.HTTP_ARTIFACT);
    String acsURL = (String) acsSet.get(0);
    //String protocolBinding = (String) acsSet.get(1);
    String isArtifactResolveSigned = SAML2Utils.getAttributeValueFromSSOConfig(realm, idpEntityID, SAML2Constants.IDP_ROLE, SAML2Constants.WANT_ARTIFACT_RESOLVE_SIGNED);
    if ((isArtifactResolveSigned != null) && (isArtifactResolveSigned.equals(SAML2Constants.TRUE))) {
        if (!artResolve.isSigned()) {
            SAML2Utils.debug.error(classMethod + "The artifact resolve is not signed " + "when it is expected to be signed.");
            return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, "ArtifactResolveNotSigned", null);
        }
        Set<X509Certificate> verificationCerts = KeyUtil.getVerificationCerts(spSSODescriptor, spEntityID, SAML2Constants.SP_ROLE);
        if (!artResolve.isSignatureValid(verificationCerts)) {
            SAML2Utils.debug.error(classMethod + "artifact resolve verification failed.");
            return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, "invalidArtifact", null);
        }
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "artifact resolve signature verification is successful.");
        }
    }
    Artifact art = artResolve.getArtifact();
    if (art == null) {
        SAML2Utils.debug.error(classMethod + "Unable to get an artifact from ArtifactResolve.");
        return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, "invalidArtifactSignature", null);
    }
    String artStr = art.getArtifactValue();
    Response res = (Response) IDPCache.responsesByArtifacts.remove(artStr);
    String remoteArtURL = null;
    boolean saml2FailoverEnabled = SAML2FailoverUtils.isSAML2FailoverEnabled();
    if (res == null) {
        // in LB case, artifact may reside on the other server.
        String targetServerID = SAML2Utils.extractServerId(art.getMessageHandle());
        if (targetServerID == null) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + "target serverID is null");
            }
            return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, "InvalidArtifactId", null);
        }
        String localServerID = SAML2Utils.getLocalServerID();
        boolean localTarget = localServerID.equals(targetServerID);
        if (!localTarget) {
            if (!SystemConfigurationUtil.isValidServerId(targetServerID)) {
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.message(classMethod + "target serverID is not valid: " + targetServerID);
                }
                return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, "InvalidArtifactId", null);
            }
            try {
                String remoteServiceURL = SystemConfigurationUtil.getServerFromID(targetServerID);
                remoteArtURL = remoteServiceURL + SAML2Utils.removeDeployUri(request.getRequestURI());
                SOAPConnection con = SOAPCommunicator.getInstance().openSOAPConnection();
                SOAPMessage resMsg = con.call(message, remoteArtURL);
                return resMsg;
            } catch (Exception ex) {
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.message(classMethod + "unable to forward request to remote server. " + "remote url = " + remoteArtURL, ex);
                }
                if (!saml2FailoverEnabled) {
                    return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.SERVER_FAULT, "RemoteArtifactResolutionFailed", null);
                }
            // when the target server is running but the remote call was
            // failed to this server (due to a network error)
            // and the saml2failover is enabled, we can still find the
            // artifact in the SAML2 repository.
            // However the cached entry in the target server will not be
            // deleted this way.
            }
        }
        if (saml2FailoverEnabled) {
            // Check the SAML2 Token Repository
            try {
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.message("Artifact=" + artStr);
                }
                String tmp = (String) SAML2FailoverUtils.retrieveSAML2Token(artStr);
                res = ProtocolFactory.getInstance().createResponse(tmp);
            } catch (SAML2Exception e) {
                SAML2Utils.debug.error(classMethod + " SAML2 ERROR!!!", e);
                return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, "UnableToFindResponseInRepo", null);
            } catch (SAML2TokenRepositoryException se) {
                SAML2Utils.debug.error(classMethod + " There was a problem reading the response " + "from the SAML2 Token Repository using artStr:" + artStr, se);
                return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, "UnableToFindResponseInRepo", null);
            }
        }
    }
    if (res == null) {
        return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, saml2FailoverEnabled ? "UnableToFindResponseInRepo" : "UnableToFindResponse", null);
    }
    // Remove Response from SAML2 Token Repository
    try {
        if (saml2FailoverEnabled) {
            SAML2FailoverUtils.deleteSAML2Token(artStr);
        }
    } catch (SAML2TokenRepositoryException e) {
        SAML2Utils.debug.error(classMethod + " Error deleting the response from the SAML2 Token Repository using artStr:" + artStr, e);
    }
    Map props = new HashMap();
    String nameIDString = SAML2Utils.getNameIDStringFromResponse(res);
    if (nameIDString != null) {
        props.put(LogUtil.NAME_ID, nameIDString);
    }
    // check if need to sign the assertion
    boolean signAssertion = spSSODescriptor.isWantAssertionsSigned();
    if (signAssertion) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "signing the assertion.");
        }
    }
    // encrypt the assertion or its NameID and/or Attribute based
    // on SP config setting and sign the assertion.
    IDPSSOUtil.signAndEncryptResponseComponents(realm, spEntityID, idpEntityID, res, signAssertion);
    ArtifactResponse artResponse = ProtocolFactory.getInstance().createArtifactResponse();
    Status status = ProtocolFactory.getInstance().createStatus();
    StatusCode statusCode = ProtocolFactory.getInstance().createStatusCode();
    statusCode.setValue(SAML2Constants.SUCCESS);
    status.setStatusCode(statusCode);
    // set the idp entity id as the response issuer
    Issuer issuer = AssertionFactory.getInstance().createIssuer();
    issuer.setValue(idpEntityID);
    artResponse.setStatus(status);
    artResponse.setID(SAML2Utils.generateID());
    artResponse.setInResponseTo(artResolve.getID());
    artResponse.setVersion(SAML2Constants.VERSION_2_0);
    artResponse.setIssueInstant(new Date());
    artResponse.setAny(res.toXMLString(true, true));
    artResponse.setIssuer(issuer);
    artResponse.setDestination(XMLUtils.escapeSpecialCharacters(acsURL));
    String wantArtifactResponseSigned = SAML2Utils.getAttributeValueFromSSOConfig(realm, spEntityID, SAML2Constants.SP_ROLE, SAML2Constants.WANT_ARTIFACT_RESPONSE_SIGNED);
    if ((wantArtifactResponseSigned != null) && (wantArtifactResponseSigned.equals(SAML2Constants.TRUE))) {
        KeyProvider kp = KeyUtil.getKeyProviderInstance();
        if (kp == null) {
            SAML2Utils.debug.error(classMethod + "Unable to get a key provider instance.");
            return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.SERVER_FAULT, "nullKeyProvider", null);
        }
        String idpSignCertAlias = SAML2Utils.getSigningCertAlias(realm, idpEntityID, SAML2Constants.IDP_ROLE);
        if (idpSignCertAlias == null) {
            SAML2Utils.debug.error(classMethod + "Unable to get the hosted IDP signing certificate alias.");
            return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.SERVER_FAULT, "missingSigningCertAlias", null);
        }
        String encryptedKeyPass = SAML2Utils.getSigningCertEncryptedKeyPass(realm, idpEntityID, SAML2Constants.IDP_ROLE);
        PrivateKey key;
        if (encryptedKeyPass == null || encryptedKeyPass.isEmpty()) {
            key = kp.getPrivateKey(idpSignCertAlias);
        } else {
            key = kp.getPrivateKey(idpSignCertAlias, encryptedKeyPass);
        }
        artResponse.sign(key, kp.getX509Certificate(idpSignCertAlias));
    }
    String str = artResponse.toXMLString(true, true);
    String[] logdata = { idpEntityID, artStr, str };
    LogUtil.access(Level.INFO, LogUtil.ARTIFACT_RESPONSE, logdata, null, props);
    if (str != null) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "ArtifactResponse message:\n" + str);
        }
    } else {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "Unable to print ArtifactResponse message.");
        }
    }
    SOAPMessage msg = null;
    try {
        msg = SOAPCommunicator.getInstance().createSOAPMessage(str, false);
    } catch (SOAPException se) {
        SAML2Utils.debug.error(classMethod + "Unable to create a SOAPMessage and add a document ", se);
        return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.SERVER_FAULT, "unableToCreateSOAPMessage", null);
    }
    return msg;
}
Also used : KeyProvider(com.sun.identity.saml.xmlsig.KeyProvider) PrivateKey(java.security.PrivateKey) HashMap(java.util.HashMap) Issuer(com.sun.identity.saml2.assertion.Issuer) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) Element(org.w3c.dom.Element) SOAPConnection(javax.xml.soap.SOAPConnection) SOAPMessage(javax.xml.soap.SOAPMessage) StatusCode(com.sun.identity.saml2.protocol.StatusCode) ArtifactResolve(com.sun.identity.saml2.protocol.ArtifactResolve) SOAPException(javax.xml.soap.SOAPException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) Status(com.sun.identity.saml2.protocol.Status) OrderedSet(com.sun.identity.shared.datastruct.OrderedSet) X509Certificate(java.security.cert.X509Certificate) Artifact(com.sun.identity.saml2.protocol.Artifact) SOAPException(javax.xml.soap.SOAPException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) IOException(java.io.IOException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Date(java.util.Date) Response(com.sun.identity.saml2.protocol.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) ArtifactResponse(com.sun.identity.saml2.protocol.ArtifactResponse) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) ArtifactResponse(com.sun.identity.saml2.protocol.ArtifactResponse) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 22 with Attribute

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

the class IDPSSOUtil method getResponse.

/**
     * Returns a <code>SAML Response</code> object.
     *
     * @param request The HTTP request.
     * @param session The user's session object.
     * @param authnReq The <code>AuthnRequest</code> object.
     * @param recipientEntityID The entity ID of the response recipient.
     * @param idpEntityID The entity ID of the identity provider.
     * @param realm The realm name.
     * @param nameIDFormat The <code>NameIDFormat</code>.
     * @param acsURL The <code>ACS</code> service <code>url</code>.
     * @param affiliationID AffiliationID for IDP initiated SSO.
     * @param matchingAuthnContext the <code>AuthnContext</code> used to find authentication type and scheme.
     * @return the <code>SAML Response</code> object.
     * @throws SAML2Exception if the operation is not successful.
     */
public static Response getResponse(HttpServletRequest request, Object session, AuthnRequest authnReq, String recipientEntityID, String idpEntityID, String idpMetaAlias, String realm, String nameIDFormat, String acsURL, String affiliationID, AuthnContext matchingAuthnContext) throws SAML2Exception {
    String classMethod = "IDPSSOUtil.getResponse: ";
    Response res = ProtocolFactory.getInstance().createResponse();
    Status status = ProtocolFactory.getInstance().createStatus();
    if (status == null) {
        return null;
    }
    StatusCode statusCode = ProtocolFactory.getInstance().createStatusCode();
    if (statusCode == null) {
        return null;
    }
    try {
        List assertionList = new ArrayList();
        Assertion assertion = getAssertion(request, session, authnReq, recipientEntityID, idpEntityID, idpMetaAlias, realm, nameIDFormat, acsURL, affiliationID, matchingAuthnContext);
        if (assertion == null) {
            SAML2Utils.debug.error(classMethod + "Unable to get Assertion.");
            return null;
        }
        assertionList.add(assertion);
        res.setAssertion(assertionList);
        statusCode.setValue(SAML2Constants.SUCCESS);
    } catch (SAML2InvalidNameIDPolicyException se) {
        statusCode.setValue(SAML2Constants.REQUESTER);
        StatusCode subStatusCode = ProtocolFactory.getInstance().createStatusCode();
        subStatusCode.setValue(SAML2Constants.INVALID_NAME_ID_POLICY);
        statusCode.setStatusCode(subStatusCode);
        status.setStatusMessage(se.getMessage());
    }
    status.setStatusCode(statusCode);
    res.setStatus(status);
    if (authnReq != null) {
        // sp initiated case, need to set InResponseTo attribute
        res.setInResponseTo(authnReq.getID());
    }
    res.setVersion(SAML2Constants.VERSION_2_0);
    res.setIssueInstant(new Date());
    res.setID(SAML2Utils.generateID());
    // set the idp entity id as the response issuer
    Issuer issuer = AssertionFactory.getInstance().createIssuer();
    issuer.setValue(idpEntityID);
    res.setIssuer(issuer);
    res.setDestination(XMLUtils.escapeSpecialCharacters(acsURL));
    return res;
}
Also used : ECPResponse(com.sun.identity.saml2.ecp.ECPResponse) Response(com.sun.identity.saml2.protocol.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) Status(com.sun.identity.saml2.protocol.Status) Issuer(com.sun.identity.saml2.assertion.Issuer) ArrayList(java.util.ArrayList) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) Assertion(com.sun.identity.saml2.assertion.Assertion) List(java.util.List) ArrayList(java.util.ArrayList) SAML2InvalidNameIDPolicyException(com.sun.identity.saml2.common.SAML2InvalidNameIDPolicyException) StatusCode(com.sun.identity.saml2.protocol.StatusCode) Date(java.util.Date)

Example 23 with Attribute

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

the class IDPSSOUtil method getIDPAttributeMapper.

/**
     * Returns an <code>IDPAttributeMapper</code>
     *
     * @param realm       the realm name
     * @param idpEntityID the entity id of the identity provider
     * @return the <code>IDPAttributeMapper</code>
     * @throws SAML2Exception if the operation is not successful
     */
static IDPAttributeMapper getIDPAttributeMapper(String realm, String idpEntityID) throws SAML2Exception {
    String classMethod = "IDPSSOUtil.getIDPAttributeMapper: ";
    String idpAttributeMapperName = null;
    IDPAttributeMapper idpAttributeMapper = null;
    try {
        idpAttributeMapperName = getAttributeValueFromIDPSSOConfig(realm, idpEntityID, SAML2Constants.IDP_ATTRIBUTE_MAPPER);
        if (idpAttributeMapperName == null) {
            idpAttributeMapperName = SAML2Constants.DEFAULT_IDP_ATTRIBUTE_MAPPER_CLASS;
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + "use " + SAML2Constants.DEFAULT_IDP_ATTRIBUTE_MAPPER_CLASS);
            }
        }
        idpAttributeMapper = (IDPAttributeMapper) IDPCache.idpAttributeMapperCache.get(idpAttributeMapperName);
        if (idpAttributeMapper == null) {
            idpAttributeMapper = (IDPAttributeMapper) Class.forName(idpAttributeMapperName).newInstance();
            IDPCache.idpAttributeMapperCache.put(idpAttributeMapperName, idpAttributeMapper);
        } else {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + "got the IDPAttributeMapper from cache");
            }
        }
    } catch (Exception ex) {
        SAML2Utils.debug.error(classMethod + "Unable to get IDP Attribute Mapper.", ex);
        throw new SAML2Exception(ex);
    }
    return idpAttributeMapper;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) IDPAttributeMapper(com.sun.identity.saml2.plugins.IDPAttributeMapper) SAML2InvalidNameIDPolicyException(com.sun.identity.saml2.common.SAML2InvalidNameIDPolicyException) SessionException(com.sun.identity.plugin.session.SessionException) COTException(com.sun.identity.cot.COTException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) IOException(java.io.IOException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception)

Example 24 with Attribute

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

the class IDPSSOUtil method signAndEncryptResponseComponents.

/**
     * Signs and encrypts the components of a <code>SAML Response</code>
     * based on the service provider meta data. If the flag of
     * encrypting <code>Assertion</code> is on, then the embedded
     * <code>Assertion</code> object will be encrypted; if the flag
     * of encrypting <code>Assertion</code> is off and the flag of
     * encrypting <code>NameID</code> is on, then the <code>NameID</code>
     * embedded in the <code>Assertion</code> will be encrypted; if the
     * flag of encrypting <code>Assertion</code> is off and the flag of
     * encrypting <code>Attribute</code> is on, then the
     * <code>Attribute</code> embedded in the <code>Assertion</code>
     * will be encrypted. If the flag signAssertion is on, then the
     * <code>Assertion</code> will be signed. It will be signed before
     * it is encrypted and after its embedded <code>NameID</code> or
     * <code>Attribute</code> is encrypted.
     *
     * @param realm         the realm name of the identity provider
     * @param spEntityID    the entity id of the service provider
     * @param idpEntityID   the entity id of the identity provider
     * @param res           The <code>Response</code> whose components may be
     *                      encrypted based on the service provider meta data setting
     * @param signAssertion A flag to indicate if <code>Assertion</code>
     *                      signing is required
     */
static void signAndEncryptResponseComponents(String realm, String spEntityID, String idpEntityID, Response res, boolean signAssertion) throws SAML2Exception {
    String classMethod = "IDPSSOUtil.signAndEncryptResponseComponents: ";
    boolean toEncryptAssertion = false;
    boolean toEncryptNameID = false;
    boolean toEncryptAttribute = false;
    if (res == null) {
        return;
    }
    List assertions = res.getAssertion();
    if ((assertions == null) || (assertions.size() == 0)) {
        return;
    }
    Assertion assertion = (Assertion) assertions.get(0);
    // get the encryption related flags from the SP Entity Config
    String wantAssertionEncrypted = SAML2Utils.getAttributeValueFromSSOConfig(realm, spEntityID, SAML2Constants.SP_ROLE, SAML2Constants.WANT_ASSERTION_ENCRYPTED);
    toEncryptAssertion = (wantAssertionEncrypted != null) && (wantAssertionEncrypted.equals(SAML2Constants.TRUE));
    if (!toEncryptAssertion) {
        String wantNameIDEncrypted = SAML2Utils.getAttributeValueFromSSOConfig(realm, spEntityID, SAML2Constants.SP_ROLE, SAML2Constants.WANT_NAMEID_ENCRYPTED);
        toEncryptNameID = (wantNameIDEncrypted != null) && (wantNameIDEncrypted.equals(SAML2Constants.TRUE));
        String wantAttributeEncrypted = SAML2Utils.getAttributeValueFromSSOConfig(realm, spEntityID, SAML2Constants.SP_ROLE, SAML2Constants.WANT_ATTRIBUTE_ENCRYPTED);
        toEncryptAttribute = (wantAttributeEncrypted != null) && (wantAttributeEncrypted.equals(SAML2Constants.TRUE));
    }
    if ((!toEncryptAssertion) && (!toEncryptNameID) && (!toEncryptAttribute)) {
        // all encryption flags are off, no encryption needed
        if (signAssertion) {
            signAssertion(realm, idpEntityID, assertion);
            List assertionList = new ArrayList();
            assertionList.add(assertion);
            res.setAssertion(assertionList);
        }
        return;
    }
    SPSSODescriptorElement spSSODescriptorElement = getSPSSODescriptor(realm, spEntityID, classMethod);
    // get the encryption information
    EncInfo encInfo = KeyUtil.getEncInfo(spSSODescriptorElement, spEntityID, SAML2Constants.SP_ROLE);
    if (encInfo == null) {
        SAML2Utils.debug.error(classMethod + "failed to get service provider encryption key info.");
        throw new SAML2Exception(SAML2Utils.bundle.getString("UnableToFindEncryptKeyInfo"));
    }
    if (toEncryptAssertion) {
        // sign assertion first, then encrypt the assertion
        if (signAssertion) {
            signAssertion(realm, idpEntityID, assertion);
        }
        // we only encrypt the Assertion
        EncryptedAssertion encryptedAssertion = assertion.encrypt(encInfo.getWrappingKey(), encInfo.getDataEncAlgorithm(), encInfo.getDataEncStrength(), spEntityID);
        if (encryptedAssertion == null) {
            SAML2Utils.debug.error(classMethod + "failed to encrypt the assertion.");
            throw new SAML2Exception(SAML2Utils.bundle.getString("FailedToEncryptAssertion"));
        }
        List assertionList = new ArrayList();
        assertionList.add(encryptedAssertion);
        res.setEncryptedAssertion(assertionList);
        // reset assertion list
        res.setAssertion(new ArrayList());
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "Assertion encrypted.");
        }
    } else {
        // assertion if applicable
        if (toEncryptNameID) {
            // we need to encrypt the NameID            
            Subject subject = assertion.getSubject();
            if (subject == null) {
                return;
            }
            NameID nameID = subject.getNameID();
            if (nameID == null) {
                return;
            }
            EncryptedID encryptedNameID = nameID.encrypt(encInfo.getWrappingKey(), encInfo.getDataEncAlgorithm(), encInfo.getDataEncStrength(), spEntityID);
            if (encryptedNameID == null) {
                SAML2Utils.debug.error(classMethod + "failed to encrypt the NameID.");
                throw new SAML2Exception(SAML2Utils.bundle.getString("FailedToEncryptNameID"));
            }
            subject.setEncryptedID(encryptedNameID);
            // reset NameID
            subject.setNameID(null);
            assertion.setSubject(subject);
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + "NameID encrypted.");
            }
        }
        if (toEncryptAttribute) {
            // we need to encrypt the Attribute
            List attributeStatements = assertion.getAttributeStatements();
            if ((attributeStatements != null) && (attributeStatements.size() > 0)) {
                int asSize = attributeStatements.size();
                // to hold all the AttributeStatements
                List stmts = new ArrayList();
                for (int i = 0; i < asSize; i++) {
                    AttributeStatement attributeStatement = (AttributeStatement) attributeStatements.get(i);
                    List attributes = attributeStatement.getAttribute();
                    if ((attributes == null) || (attributes.size() == 0)) {
                        continue;
                    }
                    int aSize = attributes.size();
                    // holds all the encrypted Attributes in this statement
                    List eaList = new ArrayList();
                    for (int j = 0; j < aSize; j++) {
                        Attribute attribute = (Attribute) attributes.get(j);
                        EncryptedAttribute encryptedAttribute = attribute.encrypt(encInfo.getWrappingKey(), encInfo.getDataEncAlgorithm(), encInfo.getDataEncStrength(), spEntityID);
                        if (encryptedAttribute == null) {
                            SAML2Utils.debug.error(classMethod + "failed to encrypt the Attribute.");
                            throw new SAML2Exception(SAML2Utils.bundle.getString("FailedToEncryptAttribute"));
                        }
                        eaList.add(encryptedAttribute);
                    }
                    attributeStatement.setEncryptedAttribute(eaList);
                    attributeStatement.setAttribute(new ArrayList());
                    stmts.add(attributeStatement);
                }
                assertion.setAttributeStatements(stmts);
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.message(classMethod + "Attribute encrypted.");
                }
            }
        }
        if (signAssertion) {
            signAssertion(realm, idpEntityID, assertion);
        }
        List assertionList = new ArrayList();
        assertionList.add(assertion);
        res.setAssertion(assertionList);
    }
}
Also used : EncryptedAttribute(com.sun.identity.saml2.assertion.EncryptedAttribute) NameID(com.sun.identity.saml2.assertion.NameID) Attribute(com.sun.identity.saml2.assertion.Attribute) EncryptedAttribute(com.sun.identity.saml2.assertion.EncryptedAttribute) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) Assertion(com.sun.identity.saml2.assertion.Assertion) ArrayList(java.util.ArrayList) EncryptedID(com.sun.identity.saml2.assertion.EncryptedID) Subject(com.sun.identity.saml2.assertion.Subject) EncInfo(com.sun.identity.saml2.key.EncInfo) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) AttributeStatement(com.sun.identity.saml2.assertion.AttributeStatement) List(java.util.List) ArrayList(java.util.ArrayList)

Example 25 with Attribute

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

the class SAML2Utils method getAttributeValueFromXACMLConfig.

/**
     * Returns the value of attribute from entity configuration.
     *
     * @param realm      the realm of the entity.
     * @param entityRole role of the entity (PEP or PDP).
     * @param entityID   identity of the entity.
     * @param attrName   name of attribute whose value is to be retreived.
     * @return value of the attribute.
     */
public static String getAttributeValueFromXACMLConfig(String realm, String entityRole, String entityID, String attrName) {
    String method = "SAML2Utils:getAttributeValueFromXACMLConfig : ";
    if (debug.messageEnabled()) {
        debug.message(method + "realm - " + realm);
        debug.message(method + "entityRole - " + entityRole);
        debug.message(method + "EntityId - " + entityID);
        debug.message(method + "attrName - " + attrName);
    }
    String result = null;
    try {
        XACMLAuthzDecisionQueryConfigElement pepConfig = null;
        XACMLPDPConfigElement pdpConfig = null;
        Map attrs = null;
        if (entityRole.equalsIgnoreCase(SAML2Constants.PEP_ROLE)) {
            pepConfig = saml2MetaManager.getPolicyEnforcementPointConfig(realm, entityID);
            if (pepConfig != null) {
                attrs = SAML2MetaUtils.getAttributes(pepConfig);
            }
        } else {
            pdpConfig = saml2MetaManager.getPolicyDecisionPointConfig(realm, entityID);
            if (pdpConfig != null) {
                attrs = SAML2MetaUtils.getAttributes(pdpConfig);
            }
        }
        if (attrs != null) {
            List value = (List) attrs.get(attrName);
            if (value != null && value.size() != 0) {
                result = (String) value.get(0);
            }
        }
    } catch (SAML2MetaException e) {
        debug.message("Retreiving XACML Config failed:", e);
    }
    if (debug.messageEnabled()) {
        debug.message("Attribute value is : " + result);
    }
    return result;
}
Also used : XACMLPDPConfigElement(com.sun.identity.saml2.jaxb.entityconfig.XACMLPDPConfigElement) XACMLAuthzDecisionQueryConfigElement(com.sun.identity.saml2.jaxb.entityconfig.XACMLAuthzDecisionQueryConfigElement) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map) HashMap(java.util.HashMap) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException)

Aggregations

ArrayList (java.util.ArrayList)57 List (java.util.List)46 SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)40 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)37 Iterator (java.util.Iterator)24 Attribute (com.sun.identity.saml2.assertion.Attribute)22 SAML2MetaManager (com.sun.identity.saml2.meta.SAML2MetaManager)22 AMConsoleException (com.sun.identity.console.base.model.AMConsoleException)21 HashMap (java.util.HashMap)21 Map (java.util.Map)18 JAXBException (javax.xml.bind.JAXBException)13 EntityConfigElement (com.sun.identity.saml2.jaxb.entityconfig.EntityConfigElement)12 EntityDescriptorElement (com.sun.identity.saml2.jaxb.metadata.EntityDescriptorElement)12 Set (java.util.Set)11 BaseConfigType (com.sun.identity.saml2.jaxb.entityconfig.BaseConfigType)9 HashSet (java.util.HashSet)9 Issuer (com.sun.identity.saml2.assertion.Issuer)8 Date (java.util.Date)8 Node (org.w3c.dom.Node)8 DataStoreProviderException (com.sun.identity.plugin.datastore.DataStoreProviderException)7