Search in sources :

Example 11 with SubjectConfirmation

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

the class SubjectImpl method toXMLString.

/**
    * Returns a String representation
    * @param includeNSPrefix Determines whether or not the namespace 
    *        qualifier is prepended to the Element when converted
    * @param declareNS Determines whether or not the namespace is 
    *        declared within the Element.
    * @return A String representation
    * @exception SAML2Exception if something is wrong during conversion
    */
public String toXMLString(boolean includeNSPrefix, boolean declareNS) throws SAML2Exception {
    StringBuffer sb = new StringBuffer(2000);
    String NS = "";
    String appendNS = "";
    if (declareNS) {
        NS = SAML2Constants.ASSERTION_DECLARE_STR;
    }
    if (includeNSPrefix) {
        appendNS = SAML2Constants.ASSERTION_PREFIX;
    }
    sb.append("<").append(appendNS).append(SUBJECT_ELEMENT).append(NS).append(">\n");
    boolean idFound = false;
    if (baseId != null) {
        sb.append(baseId.toXMLString(includeNSPrefix, false));
        idFound = true;
    }
    if (nameId != null) {
        if (idFound) {
            SAML2SDKUtils.debug.error("SubjectImpl.toXMLString(): " + "more than one types of id specified");
            throw new SAML2Exception(SAML2SDKUtils.bundle.getString("too_many_ids_specified"));
        } else {
            sb.append(nameId.toXMLString(includeNSPrefix, false));
            idFound = true;
        }
    }
    if (encryptedId != null) {
        if (idFound) {
            SAML2SDKUtils.debug.error("SubjectImpl.toXMLString(): " + "more than one types of id specified");
            throw new SAML2Exception(SAML2SDKUtils.bundle.getString("too_many_ids_specified"));
        } else {
            sb.append(encryptedId.toXMLString(includeNSPrefix, false));
            idFound = true;
        }
    }
    int length = subjectConfirmations.size();
    if (length == 0) {
        if (!idFound) {
            SAML2SDKUtils.debug.error("SubjectImpl.toXMLString(): Need at " + "least one id or one subject confirmation in a subject");
            throw new SAML2Exception(SAML2SDKUtils.bundle.getString("need_at_least_one_id_or_on_SubjectConfirmation"));
        }
    } else {
        for (int i = 0; i < length; i++) {
            SubjectConfirmation sc = (SubjectConfirmation) subjectConfirmations.get(i);
            sb.append(sc.toXMLString(includeNSPrefix, false));
        }
    }
    sb.append("</").append(appendNS).append(SUBJECT_ELEMENT).append(">");
    return sb.toString();
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) SubjectConfirmation(com.sun.identity.saml2.assertion.SubjectConfirmation)

Example 12 with SubjectConfirmation

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

the class SAML2Utils method isBearerSubjectConfirmation.

private static Map isBearerSubjectConfirmation(final List subjectConfirms, final String inRespToResponse, final SPSSODescriptorElement spDesc, final SPSSOConfigElement spConfig, final String assertionID) throws SAML2Exception {
    String method = "SAML2Utils.isBearerSubjectConfirmation:";
    Map retMap = new HashMap();
    boolean hasBearer = false;
    for (Iterator it = subjectConfirms.iterator(); it.hasNext(); ) {
        SubjectConfirmation subjectConfirm = (SubjectConfirmation) it.next();
        if (subjectConfirm == null || subjectConfirm.getMethod() == null || !subjectConfirm.getMethod().equals(SAML2Constants.SUBJECT_CONFIRMATION_METHOD_BEARER)) {
            continue;
        }
        // since this is bearer SC, all below must be true
        SubjectConfirmationData subjectConfData = subjectConfirm.getSubjectConfirmationData();
        if (subjectConfData == null) {
            if (debug.messageEnabled()) {
                debug.message(method + "missing SubjectConfirmationData.");
            }
            String[] data = { assertionID };
            LogUtil.error(Level.INFO, LogUtil.MISSING_SUBJECT_COMFIRMATION_DATA, data, null);
            throw new SAML2Exception(bundle.getString("missingSubjectConfirmationData"));
        }
        String recipient = subjectConfData.getRecipient();
        if (recipient == null || recipient.length() == 0) {
            if (debug.messageEnabled()) {
                debug.message(method + "missing Recipient in Assertion.");
            }
            String[] data = { assertionID };
            LogUtil.error(Level.INFO, LogUtil.MISSING_RECIPIENT, data, null);
            throw new SAML2Exception(bundle.getString("missingRecipient"));
        }
        boolean foundMatch = false;
        Iterator acsIter = spDesc.getAssertionConsumerService().iterator();
        while (acsIter.hasNext()) {
            AssertionConsumerServiceElement acs = (AssertionConsumerServiceElement) acsIter.next();
            if (recipient.equals(acs.getLocation())) {
                foundMatch = true;
                break;
            }
        }
        if (!foundMatch) {
            if (debug.messageEnabled()) {
                debug.message(method + "this sp is not the intended " + "recipient.");
            }
            String[] data = { assertionID, recipient };
            LogUtil.error(Level.INFO, LogUtil.WRONG_RECIPIENT, data, null);
            throw new SAML2Exception(bundle.getString("wrongRecipient"));
        }
        // in seconds
        int timeskew = SAML2Constants.ASSERTION_TIME_SKEW_DEFAULT;
        String timeskewStr = getAttributeValueFromSPSSOConfig(spConfig, SAML2Constants.ASSERTION_TIME_SKEW);
        if (timeskewStr != null && timeskewStr.trim().length() > 0) {
            timeskew = Integer.parseInt(timeskewStr);
            if (timeskew < 0) {
                timeskew = SAML2Constants.ASSERTION_TIME_SKEW_DEFAULT;
            }
        }
        if (debug.messageEnabled()) {
            debug.message(method + "timeskew = " + timeskew);
        }
        Date notOnOrAfter = subjectConfData.getNotOnOrAfter();
        if (notOnOrAfter == null || ((notOnOrAfter.getTime() + timeskew * 1000) < System.currentTimeMillis())) {
            if (debug.messageEnabled()) {
                debug.message(method + "Time in SubjectConfirmationData of " + "Assertion:" + assertionID + " is invalid.");
            }
            String[] data = { assertionID };
            LogUtil.error(Level.INFO, LogUtil.INVALID_TIME_SUBJECT_CONFIRMATION_DATA, data, null);
            throw new SAML2Exception(bundle.getString("invalidTimeOnSubjectConfirmationData"));
        }
        retMap.put(SAML2Constants.NOTONORAFTER, notOnOrAfter);
        Date notBefore = subjectConfData.getNotBefore();
        if (notBefore != null) {
            if ((notBefore.getTime() + timeskew * 1000) > System.currentTimeMillis()) {
                if (debug.messageEnabled()) {
                    debug.message(method + "SubjectConfirmationData included " + "NotBefore.");
                }
                String[] data = { assertionID };
                LogUtil.error(Level.INFO, LogUtil.CONTAINED_NOT_BEFORE, data, null);
                throw new SAML2Exception(bundle.getString("containedNotBefore"));
            }
        }
        retMap.put(SAML2Constants.NOTBEFORE, notBefore);
        String inRespTo = subjectConfData.getInResponseTo();
        if (inRespTo != null && inRespTo.length() != 0) {
            if (!inRespTo.equals(inRespToResponse)) {
                if (debug.messageEnabled()) {
                    debug.message(method + "InResponseTo in Assertion is " + "different from the one in Response.");
                }
                String[] data = { assertionID };
                LogUtil.error(Level.INFO, LogUtil.WRONG_INRESPONSETO_ASSERTION, data, null);
                throw new SAML2Exception(bundle.getString("wrongInResponseToInAssertion"));
            }
        } else {
            if (inRespToResponse != null && inRespToResponse.length() != 0) {
                if (debug.messageEnabled()) {
                    debug.message(method + "Assertion doesn't contain " + "InResponseTo, but Response does.");
                }
                String[] data = { assertionID };
                LogUtil.error(Level.INFO, LogUtil.WRONG_INRESPONSETO_ASSERTION, data, null);
                throw new SAML2Exception(bundle.getString("wrongInResponseToInAssertion"));
            }
        }
        hasBearer = true;
        break;
    }
    retMap.put(SAML2Constants.IS_BEARER, Boolean.valueOf(hasBearer));
    return retMap;
}
Also used : SubjectConfirmation(com.sun.identity.saml2.assertion.SubjectConfirmation) HashMap(java.util.HashMap) Iterator(java.util.Iterator) AssertionConsumerServiceElement(com.sun.identity.saml2.jaxb.metadata.AssertionConsumerServiceElement) SubjectConfirmationData(com.sun.identity.saml2.assertion.SubjectConfirmationData) Map(java.util.Map) HashMap(java.util.HashMap) Date(java.util.Date)

Example 13 with SubjectConfirmation

use of com.sun.identity.saml2.assertion.SubjectConfirmation 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 14 with SubjectConfirmation

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

the class AssertionGen method getSubject.

/**
 *Add subject to the SAML assertion
 *
 */
private Subject getSubject(String SPEntityID, String SPBaseUrl, String IDPEntutyID) {
    Subject subject = AssertionFactory.getInstance().createSubject();
    try {
        NameID nameID = AssertionFactory.getInstance().createNameID();
        SubjectConfirmation sc = AssertionFactory.getInstance().createSubjectConfirmation();
        List SubjectConformationList = new ArrayList();
        nameID.setFormat(SAML2Constants.NAMEID_TRANSIENT_FORMAT);
        nameID.setNameQualifier(IDPEntutyID);
        nameID.setSPNameQualifier(SPEntityID);
        nameID.setValue("nameidvalue");
        subject.setNameID(nameID);
        sc.setMethod(SAML2Constants.SUBJECT_CONFIRMATION_METHOD_BEARER);
        int effectiveTime = SAML2Constants.ASSERTION_EFFECTIVE_TIME;
        Date date = new Date();
        date.setTime(date.getTime() + effectiveTime * 1000);
        SubjectConfirmationData scd = AssertionFactory.getInstance().createSubjectConfirmationData();
        scd.setRecipient(SPBaseUrl);
        scd.setNotOnOrAfter(date);
        sc.setSubjectConfirmationData(scd);
        SubjectConformationList.add(sc);
        subject.setSubjectConfirmation(SubjectConformationList);
        return subject;
    } catch (SAML2Exception ex) {
        Logger.getLogger(AssertionGen.class.getName()).log(Level.SEVERE, null, ex);
    }
    return subject;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) Date(java.util.Date)

Aggregations

SubjectConfirmation (com.sun.identity.saml2.assertion.SubjectConfirmation)10 SubjectConfirmationData (com.sun.identity.saml2.assertion.SubjectConfirmationData)8 Date (java.util.Date)8 SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)7 ArrayList (java.util.ArrayList)6 Subject (com.sun.identity.saml2.assertion.Subject)5 List (java.util.List)3 TokenCreationException (org.forgerock.openam.sts.TokenCreationException)3 SAML2SubjectConfirmation (org.forgerock.openam.sts.token.SAML2SubjectConfirmation)3 AudienceRestriction (com.sun.identity.saml2.assertion.AudienceRestriction)2 Conditions (com.sun.identity.saml2.assertion.Conditions)2 KeyInfoFactory (org.forgerock.openam.sts.tokengeneration.saml2.xmlsig.KeyInfoFactory)2 Test (org.testng.annotations.Test)2 Element (org.w3c.dom.Element)2 SessionException (com.sun.identity.plugin.session.SessionException)1 Issuer (com.sun.identity.saml2.assertion.Issuer)1 NameID (com.sun.identity.saml2.assertion.NameID)1 NameIDInfo (com.sun.identity.saml2.common.NameIDInfo)1 SAML2InvalidNameIDPolicyException (com.sun.identity.saml2.common.SAML2InvalidNameIDPolicyException)1 AffiliationDescriptorType (com.sun.identity.saml2.jaxb.metadata.AffiliationDescriptorType)1