Search in sources :

Example 26 with Assertion

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

the class AssertionImpl method processElement.

private void processElement(Element element) throws SAML2Exception {
    if (element == null) {
        SAML2SDKUtils.debug.error("AssertionImpl.processElement(): invalid root element");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalid_element"));
    }
    String elemName = element.getLocalName();
    if (elemName == null) {
        SAML2SDKUtils.debug.error("AssertionImpl.processElement(): local name missing");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missing_local_name"));
    }
    if (!elemName.equals(ASSERTION_ELEMENT)) {
        SAML2SDKUtils.debug.error("AssertionImpl.processElement(): invalid local name " + elemName);
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalid_local_name"));
    }
    // starts processing attributes
    String attrValue = element.getAttribute(ASSERTION_VERSION_ATTR);
    if ((attrValue == null) || (attrValue.length() == 0)) {
        SAML2SDKUtils.debug.error("AssertionImpl.processElement(): version missing");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missing_assertion_version"));
    }
    version = attrValue;
    attrValue = element.getAttribute(ASSERTION_ID_ATTR);
    if ((attrValue == null) || (attrValue.length() == 0)) {
        SAML2SDKUtils.debug.error("AssertionImpl.processElement(): assertion id missing");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missing_assertion_id"));
    }
    id = attrValue;
    attrValue = element.getAttribute(ASSERTION_ISSUEINSTANT_ATTR);
    if ((attrValue == null) || (attrValue.length() == 0)) {
        SAML2SDKUtils.debug.error("AssertionImpl.processElement(): issue instant missing");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missing_issue_instant"));
    }
    try {
        issueInstant = DateUtils.stringToDate(attrValue);
    } catch (ParseException pe) {
        SAML2SDKUtils.debug.error("AssertionImpl.processElement(): invalid issue instant");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalid_date_format"));
    }
    // starts processing subelements
    NodeList nodes = element.getChildNodes();
    int numOfNodes = nodes.getLength();
    if (numOfNodes < 1) {
        SAML2SDKUtils.debug.error("AssertionImpl.processElement(): assertion has no subelements");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missing_subelements"));
    }
    AssertionFactory factory = AssertionFactory.getInstance();
    int nextElem = 0;
    Node child = (Node) nodes.item(nextElem);
    while (child.getNodeType() != Node.ELEMENT_NODE) {
        if (++nextElem >= numOfNodes) {
            SAML2SDKUtils.debug.error("AssertionImpl.processElement():" + " assertion has no subelements");
            throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missing_subelements"));
        }
        child = (Node) nodes.item(nextElem);
    }
    // The first subelement should be <Issuer>
    String childName = child.getLocalName();
    if ((childName == null) || (!childName.equals(ASSERTION_ISSUER))) {
        SAML2SDKUtils.debug.error("AssertionImpl.processElement():" + " the first element is not <Issuer>");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missing_subelement_issuer"));
    }
    issuer = factory.getInstance().createIssuer((Element) child);
    if (++nextElem >= numOfNodes) {
        return;
    }
    child = (Node) nodes.item(nextElem);
    while (child.getNodeType() != Node.ELEMENT_NODE) {
        if (++nextElem >= numOfNodes) {
            return;
        }
        child = (Node) nodes.item(nextElem);
    }
    // The next subelement may be <ds:Signature>
    childName = child.getLocalName();
    if ((childName != null) && childName.equals(ASSERTION_SIGNATURE)) {
        signature = XMLUtils.print((Element) child);
        if (++nextElem >= numOfNodes) {
            return;
        }
        child = (Node) nodes.item(nextElem);
        while (child.getNodeType() != Node.ELEMENT_NODE) {
            if (++nextElem >= numOfNodes) {
                return;
            }
            child = (Node) nodes.item(nextElem);
        }
        childName = child.getLocalName();
    } else {
        signature = null;
    }
    // The next subelement may be <Subject>
    if ((childName != null) && childName.equals(ASSERTION_SUBJECT)) {
        subject = factory.createSubject((Element) child);
        if (++nextElem >= numOfNodes) {
            return;
        }
        child = (Node) nodes.item(nextElem);
        while (child.getNodeType() != Node.ELEMENT_NODE) {
            if (++nextElem >= numOfNodes) {
                return;
            }
            child = (Node) nodes.item(nextElem);
        }
        childName = child.getLocalName();
    } else {
        subject = null;
    }
    // The next subelement may be <Conditions>
    if ((childName != null) && childName.equals(ASSERTION_CONDITIONS)) {
        conditions = factory.createConditions((Element) child);
        if (++nextElem >= numOfNodes) {
            return;
        }
        child = (Node) nodes.item(nextElem);
        while (child.getNodeType() != Node.ELEMENT_NODE) {
            if (++nextElem >= numOfNodes) {
                return;
            }
            child = (Node) nodes.item(nextElem);
        }
        childName = child.getLocalName();
    } else {
        conditions = null;
    }
    // The next subelement may be <Advice>
    if ((childName != null) && childName.equals(ASSERTION_ADVICE)) {
        advice = factory.createAdvice((Element) child);
        nextElem++;
    } else {
        advice = null;
    }
    // The next subelements are all statements    
    while (nextElem < numOfNodes) {
        child = (Node) nodes.item(nextElem);
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            childName = child.getLocalName();
            if (childName != null) {
                if (childName.equals(ASSERTION_AUTHNSTATEMENT)) {
                    authnStatements.add(factory.createAuthnStatement((Element) child));
                } else if (childName.equals(ASSERTION_AUTHZDECISIONSTATEMENT)) {
                    authzDecisionStatements.add(factory.createAuthzDecisionStatement((Element) child));
                } else if (childName.equals(ASSERTION_ATTRIBUTESTATEMENT)) {
                    attributeStatements.add(factory.createAttributeStatement((Element) child));
                } else if ((childName != null) && childName.equals(ASSERTION_SIGNATURE)) {
                    signature = XMLUtils.print((Element) child);
                } else {
                    String type = ((Element) child).getAttribute(XSI_TYPE_ATTR);
                    if (childName.equals(ASSERTION_STATEMENT) && (type != null && type.length() > 0)) {
                        statements.add(XMLUtils.print((Element) child));
                    } else {
                        SAML2SDKUtils.debug.error("AssertionImpl.processElement(): " + "unexpected subelement " + childName);
                        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("unexpected_subelement"));
                    }
                }
            }
        }
        nextElem++;
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) AssertionFactory(com.sun.identity.saml2.assertion.AssertionFactory) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) ParseException(java.text.ParseException)

Example 27 with Assertion

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

the class WSFederationUtils method isSignatureValid.

/**
     * Determine the validity of the signature on the <code>Assertion</code>
     * @param assertion SAML 1.1 Assertion
     * @param realm Realm for the issuer
     * @param issuer Assertion issuer - used to retrieve certificate for 
     * signature validation.
     * @return true if the signature on the object is valid; false otherwise.
     */
public static boolean isSignatureValid(Assertion assertion, String realm, String issuer) {
    boolean valid = false;
    String signedXMLString = assertion.toString(true, true);
    String id = assertion.getAssertionID();
    try {
        FederationElement idp = metaManager.getEntityDescriptor(realm, issuer);
        X509Certificate cert = KeyUtil.getVerificationCert(idp, issuer, true);
        XMLSignatureManager manager = XMLSignatureManager.getInstance();
        valid = SigManager.getSigInstance().verify(signedXMLString, id, Collections.singleton(cert));
    } catch (WSFederationMetaException ex) {
        valid = false;
    } catch (SAML2Exception ex) {
        valid = false;
    }
    if (!valid) {
        String[] data = { LogUtil.isErrorLoggable(Level.FINER) ? signedXMLString : id, realm, issuer };
        LogUtil.error(Level.INFO, LogUtil.INVALID_SIGNATURE_ASSERTION, data, null);
    }
    return valid;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) XMLSignatureManager(com.sun.identity.saml.xmlsig.XMLSignatureManager) WSFederationMetaException(com.sun.identity.wsfederation.meta.WSFederationMetaException) FederationElement(com.sun.identity.wsfederation.jaxb.wsfederation.FederationElement) X509Certificate(java.security.cert.X509Certificate)

Example 28 with Assertion

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

the class QueryHandlerServlet method processXACMLResponse.

/**
     * Returns the received Response to the Requester.
     * Validates the message signature if signed and invokes the
     * Request Handler to pass the request for futher processing.
     *
     * @param realm realm of the entity.
     * @param pdpEntityID entity identifier of Policy Decision Point (PDP).
     * @param samlRequest the <code>RequestAbstract</code> object.
     * @param request the <code>HttpServletRequest</code> object.
     * @param soapMsg the <code>SOAPMessage</code> object.
     * @exception <code>SAML2Exception</code> if there is an error processing
     *            the request and returning a  response.
     */
Response processXACMLResponse(String realm, String pdpEntityID, RequestAbstract samlRequest, HttpServletRequest request, SOAPMessage soapMsg) throws SAML2Exception {
    String classMethod = "QueryHandlerServlet:processXACMLResponse";
    Response samlResponse = null;
    String path = request.getPathInfo();
    String key = path.substring(path.indexOf(METAALIAS_KEY) + 10);
    String pepEntityID = samlRequest.getIssuer().getValue();
    if (debug.messageEnabled()) {
        debug.message(classMethod + "SOAPMessage KEY . :" + key);
        debug.message(classMethod + "pepEntityID is :" + pepEntityID);
    }
    //Retreive metadata
    boolean pdpWantAuthzQuerySigned = SAML2Utils.getWantXACMLAuthzDecisionQuerySigned(realm, pdpEntityID, SAML2Constants.PDP_ROLE);
    if (debug.messageEnabled()) {
        debug.message(classMethod + "PDP wantAuthzQuerySigned:" + pdpWantAuthzQuerySigned);
    }
    if (pdpWantAuthzQuerySigned) {
        if (samlRequest.isSigned()) {
            XACMLAuthzDecisionQueryDescriptorElement pep = SAML2Utils.getSAML2MetaManager().getPolicyEnforcementPointDescriptor(realm, pepEntityID);
            Set<X509Certificate> verificationCerts = KeyUtil.getPEPVerificationCerts(pep, pepEntityID);
            if (verificationCerts.isEmpty() || !samlRequest.isSignatureValid(verificationCerts)) {
                // error
                debug.error(classMethod + "Invalid signature in message");
                throw new SAML2Exception("invalidQuerySignature");
            } else {
                debug.message(classMethod + "Valid signature found");
            }
        } else {
            debug.error("Request not signed");
            throw new SAML2Exception("nullSig");
        }
    }
    //getRequestHandlerClass
    RequestHandler handler = (RequestHandler) SOAPBindingService.handlers.get(key);
    if (handler != null) {
        if (debug.messageEnabled()) {
            debug.message(classMethod + "Found handler");
        }
        samlResponse = handler.handleQuery(pdpEntityID, pepEntityID, samlRequest, soapMsg);
        // set response attributes
        samlResponse.setID(SAML2Utils.generateID());
        samlResponse.setVersion(SAML2Constants.VERSION_2_0);
        samlResponse.setIssueInstant(new Date());
        Issuer issuer = AssertionFactory.getInstance().createIssuer();
        issuer.setValue(pdpEntityID);
        samlResponse.setIssuer(issuer);
        // end set Response Attributes
        //set Assertion attributes
        List assertionList = samlResponse.getAssertion();
        Assertion assertion = (Assertion) assertionList.get(0);
        assertion.setID(SAML2Utils.generateID());
        assertion.setVersion(SAML2Constants.VERSION_2_0);
        assertion.setIssueInstant(new Date());
        assertion.setIssuer(issuer);
        // end assertion set attributes
        // check if assertion needs to be encrypted,signed.
        String wantAssertionEncrypted = SAML2Utils.getAttributeValueFromXACMLConfig(realm, SAML2Constants.PEP_ROLE, pepEntityID, SAML2Constants.WANT_ASSERTION_ENCRYPTED);
        XACMLAuthzDecisionQueryDescriptorElement pepDescriptor = SAML2Utils.getSAML2MetaManager().getPolicyEnforcementPointDescriptor(realm, pepEntityID);
        EncInfo encInfo = null;
        boolean wantAssertionSigned = pepDescriptor.isWantAssertionsSigned();
        if (debug.messageEnabled()) {
            debug.message(classMethod + " wantAssertionSigned :" + wantAssertionSigned);
        }
        if (wantAssertionSigned) {
            signAssertion(realm, pdpEntityID, assertion);
        }
        if (wantAssertionEncrypted != null && wantAssertionEncrypted.equalsIgnoreCase(SAML2Constants.TRUE)) {
            encInfo = KeyUtil.getPEPEncInfo(pepDescriptor, pepEntityID);
            // encrypt the Assertion
            EncryptedAssertion encryptedAssertion = assertion.encrypt(encInfo.getWrappingKey(), encInfo.getDataEncAlgorithm(), encInfo.getDataEncStrength(), pepEntityID);
            if (encryptedAssertion == null) {
                debug.error(classMethod + "Assertion encryption failed.");
                throw new SAML2Exception("FailedToEncryptAssertion");
            }
            assertionList = new ArrayList();
            assertionList.add(encryptedAssertion);
            samlResponse.setEncryptedAssertion(assertionList);
            //reset Assertion list
            samlResponse.setAssertion(new ArrayList());
            if (debug.messageEnabled()) {
                debug.message(classMethod + "Assertion encrypted.");
            }
        } else {
            List assertionsList = new ArrayList();
            assertionsList.add(assertion);
            samlResponse.setAssertion(assertionsList);
        }
        signResponse(samlResponse, realm, pepEntityID, pdpEntityID);
    } else {
        // error -  missing request handler.
        debug.error(classMethod + "RequestHandler not found");
        throw new SAML2Exception("missingRequestHandler");
    }
    return samlResponse;
}
Also used : Issuer(com.sun.identity.saml2.assertion.Issuer) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) Assertion(com.sun.identity.saml2.assertion.Assertion) ArrayList(java.util.ArrayList) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) Response(com.sun.identity.saml2.protocol.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) EncInfo(com.sun.identity.saml2.key.EncInfo) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) ArrayList(java.util.ArrayList) List(java.util.List) XACMLAuthzDecisionQueryDescriptorElement(com.sun.identity.saml2.jaxb.metadata.XACMLAuthzDecisionQueryDescriptorElement)

Example 29 with Assertion

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

the class Saml2GrantTypeHandler method handle.

public AccessToken handle(OAuth2Request request) throws InvalidGrantException, InvalidClientException, InvalidRequestException, ServerException, InvalidScopeException, NotFoundException {
    String clientId = request.getParameter(OAuth2Constants.Params.CLIENT_ID);
    Reject.ifTrue(isEmpty(clientId), "Missing parameter, 'client_id'");
    final ClientRegistration clientRegistration = clientRegistrationStore.get(clientId, request);
    Reject.ifTrue(isEmpty(request.<String>getParameter("assertion")), "Missing parameter, 'assertion'");
    final String assertion = request.getParameter(OAuth2Constants.SAML20.ASSERTION);
    logger.trace("Assertion:\n" + assertion);
    final byte[] decodedAssertion = Base64.decode(assertion.replace(" ", "+"));
    if (decodedAssertion == null) {
        logger.error("Decoding assertion failed\nassertion:" + assertion);
    }
    final String finalAssertion = new String(decodedAssertion);
    logger.trace("Decoded assertion:\n" + finalAssertion);
    final Assertion assertionObject;
    final boolean valid;
    try {
        final AssertionFactory factory = AssertionFactory.getInstance();
        assertionObject = factory.createAssertion(finalAssertion);
        valid = validAssertion(assertionObject, getDeploymentUrl(request));
    } catch (SAML2Exception e) {
        logger.error("Error parsing assertion", e);
        throw new InvalidGrantException("Assertion is invalid");
    }
    if (!valid) {
        logger.error("Error parsing assertion");
        throw new InvalidGrantException("Assertion is invalid.");
    }
    logger.trace("Assertion is valid");
    final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    final String validatedClaims = providerSettings.validateRequestedClaims((String) request.getParameter(OAuth2Constants.Custom.CLAIMS));
    final String grantType = request.getParameter(OAuth2Constants.Params.GRANT_TYPE);
    final Set<String> scope = splitScope(request.<String>getParameter(OAuth2Constants.Params.SCOPE));
    final Set<String> validatedScope = providerSettings.validateAccessTokenScope(clientRegistration, scope, request);
    logger.trace("Granting scope: " + validatedScope.toString());
    logger.trace("Creating token with data: " + clientRegistration.getAccessTokenType() + "\n" + validatedScope.toString() + "\n" + normaliseRealm(request.<String>getParameter(OAuth2Constants.Params.REALM)) + "\n" + assertionObject.getSubject().getNameID().getValue() + "\n" + clientRegistration.getClientId());
    final AccessToken accessToken = tokenStore.createAccessToken(grantType, BEARER, null, assertionObject.getSubject().getNameID().getValue(), clientRegistration.getClientId(), null, validatedScope, null, null, validatedClaims, request);
    logger.trace("Token created: " + accessToken.toString());
    providerSettings.additionalDataToReturnFromTokenEndpoint(accessToken, request);
    if (validatedScope != null && !validatedScope.isEmpty()) {
        accessToken.put(SCOPE, joinScope(validatedScope));
    }
    tokenStore.updateAccessToken(accessToken);
    return accessToken;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) AssertionFactory(com.sun.identity.saml2.assertion.AssertionFactory) ClientRegistration(org.forgerock.oauth2.core.ClientRegistration) AccessToken(org.forgerock.oauth2.core.AccessToken) Assertion(com.sun.identity.saml2.assertion.Assertion) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings) InvalidGrantException(org.forgerock.oauth2.core.exceptions.InvalidGrantException)

Example 30 with Assertion

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

the class AttributeQueryUtil method encryptAssertion.

private static EncryptedAssertion encryptAssertion(Assertion assertion, EncryptedID encryptedID, String attrAuthorityEntityID, String requesterEntityID, String realm, String attrQueryProfileAlias) throws SAML2Exception {
    SecretKey secretKey = EncManager.getEncInstance().getSecretKey(encryptedID.toXMLString(true, true), KeyUtil.getDecryptionKeys(realm, attrAuthorityEntityID, SAML2Constants.ATTR_AUTH_ROLE));
    AttributeQueryDescriptorElement aqd = metaManager.getAttributeQueryDescriptor(realm, requesterEntityID);
    EncInfo encInfo = KeyUtil.getEncInfo(aqd, requesterEntityID, SAML2Constants.ATTR_QUERY_ROLE);
    Element el = EncManager.getEncInstance().encrypt(assertion.toXMLString(true, true), encInfo.getWrappingKey(), secretKey, encInfo.getDataEncAlgorithm(), encInfo.getDataEncStrength(), requesterEntityID, "EncryptedAssertion");
    return AssertionFactory.getInstance().createEncryptedAssertion(el);
}
Also used : EncInfo(com.sun.identity.saml2.key.EncInfo) SecretKey(javax.crypto.SecretKey) AttributeServiceElement(com.sun.identity.saml2.jaxb.metadata.AttributeServiceElement) AttributeValueElement(com.sun.identity.saml2.jaxb.assertion.AttributeValueElement) AttributeElement(com.sun.identity.saml2.jaxb.assertion.AttributeElement) IDPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.IDPSSOConfigElement) AttributeAuthorityConfigElement(com.sun.identity.saml2.jaxb.entityconfig.AttributeAuthorityConfigElement) AttributeQueryDescriptorElement(com.sun.identity.saml2.jaxb.metadataextquery.AttributeQueryDescriptorElement) AttributeAuthorityDescriptorElement(com.sun.identity.saml2.jaxb.metadata.AttributeAuthorityDescriptorElement) Element(org.w3c.dom.Element) AttributeQueryConfigElement(com.sun.identity.saml2.jaxb.entityconfig.AttributeQueryConfigElement) AttributeQueryDescriptorElement(com.sun.identity.saml2.jaxb.metadataextquery.AttributeQueryDescriptorElement)

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