Search in sources :

Example 1 with ArtifactResponse

use of com.sun.identity.saml2.protocol.ArtifactResponse 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 2 with ArtifactResponse

use of com.sun.identity.saml2.protocol.ArtifactResponse 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)

Example 3 with ArtifactResponse

use of com.sun.identity.saml2.protocol.ArtifactResponse in project OpenAM by OpenRock.

the class SPACSUtils method getResponseFromSOAP.

/**
     * Obtains <code>SAML Response</code> from <code>SOAPBody</code>.
     * Used by Artifact profile.
     */
private static Response getResponseFromSOAP(SOAPMessage resMsg, ArtifactResolve resolve, HttpServletRequest request, HttpServletResponse response, String idpEntityID, IDPSSODescriptorElement idp, String orgName, String hostEntityId, SAML2MetaManager sm) throws SAML2Exception, IOException {
    String method = "SPACSUtils.getResponseFromSOAP:";
    Element resElem = null;
    try {
        resElem = SOAPCommunicator.getInstance().getSamlpElement(resMsg, "ArtifactResponse");
    } catch (SAML2Exception se) {
        String[] data = { idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.SOAP_ERROR, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "soapError", se.getMessage());
        throw se;
    }
    ArtifactResponse artiResp = null;
    try {
        artiResp = ProtocolFactory.getInstance().createArtifactResponse(resElem);
    } catch (SAML2Exception se) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(method + "Couldn't create " + "ArtifactResponse:", se);
        }
        String[] data = { idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.CANNOT_INSTANTIATE_ARTIFACT_RESPONSE, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "failedToCreateArtifactResponse", se.getMessage());
        throw se;
    }
    if (artiResp == null) {
        String[] data = { idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.MISSING_ARTIFACT_RESPONSE, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "missingArtifactResponse", SAML2Utils.bundle.getString("missingArtifactResponse"));
        throw new SAML2Exception(SAML2Utils.bundle.getString("missingArtifactResponse"));
    } else {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(method + "Received ArtifactResponse:" + artiResp.toXMLString(true, true));
        }
    }
    // verify ArtifactResponse
    String wantArtiRespSigned = getAttributeValueFromSPSSOConfig(orgName, hostEntityId, sm, SAML2Constants.WANT_ARTIFACT_RESPONSE_SIGNED);
    if (wantArtiRespSigned != null && wantArtiRespSigned.equals("true")) {
        Set<X509Certificate> verificationCerts = KeyUtil.getVerificationCerts(idp, idpEntityID, SAML2Constants.IDP_ROLE);
        if (!artiResp.isSigned() || !artiResp.isSignatureValid(verificationCerts)) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(method + "ArtifactResponse's signature is invalid.");
            }
            String[] data = { idpEntityID };
            LogUtil.error(Level.INFO, LogUtil.ARTIFACT_RESPONSE_INVALID_SIGNATURE, data, null);
            SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "invalidSignature", SAML2Utils.bundle.getString("invalidSignature"));
            throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignature"));
        }
    }
    String inResponseTo = artiResp.getInResponseTo();
    if (inResponseTo == null || !inResponseTo.equals(resolve.getID())) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(method + "ArtifactResponse's InResponseTo is invalid.");
        }
        String[] data = { idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.ARTIFACT_RESPONSE_INVALID_INRESPONSETO, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "invalidInResponseTo", SAML2Utils.bundle.getString("invalidInResponseTo"));
        throw new SAML2Exception(SAML2Utils.bundle.getString("invalidInResponseTo"));
    }
    Issuer idpIssuer = artiResp.getIssuer();
    if (idpIssuer == null || !idpIssuer.getValue().equals(idpEntityID)) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(method + "ArtifactResponse's Issuer is invalid.");
        }
        String[] data = { idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.ARTIFACT_RESPONSE_INVALID_ISSUER, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "invalidIssuer", SAML2Utils.bundle.getString("invalidIssuer"));
        throw new SAML2Exception(SAML2Utils.bundle.getString("invalidIssuer"));
    }
    // check time?
    Status status = artiResp.getStatus();
    if (status == null || !status.getStatusCode().getValue().equals(SAML2Constants.SUCCESS)) {
        String statusCode = (status == null) ? "" : status.getStatusCode().getValue();
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(method + "ArtifactResponse's status code is not success." + statusCode);
        }
        String[] data = { idpEntityID, "" };
        if (LogUtil.isErrorLoggable(Level.FINE)) {
            data[1] = statusCode;
        }
        LogUtil.error(Level.INFO, LogUtil.ARTIFACT_RESPONSE_INVALID_STATUS_CODE, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "invalidStatusCode", SAML2Utils.bundle.getString("invalidStatusCode"));
        throw new SAML2Exception(SAML2Utils.bundle.getString("invalidStatusCode"));
    }
    try {
        return ProtocolFactory.getInstance().createResponse(artiResp.getAny());
    } catch (SAML2Exception se) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(method + "couldn't instantiate Response:", se);
        }
        String[] data = { idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.CANNOT_INSTANTIATE_RESPONSE_ARTIFACT, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "failedToCreateResponse", se.getMessage());
        throw se;
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Status(com.sun.identity.saml2.protocol.Status) Issuer(com.sun.identity.saml2.assertion.Issuer) ArtifactResponse(com.sun.identity.saml2.protocol.ArtifactResponse) SPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.SPSSOConfigElement) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) IDPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.IDPSSOConfigElement) ArtifactResolutionServiceElement(com.sun.identity.saml2.jaxb.metadata.ArtifactResolutionServiceElement) Element(org.w3c.dom.Element) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement) X509Certificate(java.security.cert.X509Certificate)

Example 4 with ArtifactResponse

use of com.sun.identity.saml2.protocol.ArtifactResponse in project OpenAM by OpenRock.

the class ArtifactResponseImpl method parseElement.

private void parseElement(Element element) throws SAML2Exception {
    // make sure that the input xml block is not null
    if (element == null) {
        if (SAML2SDKUtils.debug.messageEnabled()) {
            SAML2SDKUtils.debug.message("ArtifactResponseImpl.parseElement: " + "element input is null.");
        }
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullInput"));
    }
    // Make sure this is an ArtifactResponse.
    String tag = null;
    tag = element.getLocalName();
    if ((tag == null) || (!tag.equals("ArtifactResponse"))) {
        if (SAML2SDKUtils.debug.messageEnabled()) {
            SAML2SDKUtils.debug.message("ArtifactResponseImpl.parseElement: " + "not ArtifactResponse.");
        }
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("wrongInput"));
    }
    // handle the attributes of <ArtifactResponse> element
    NamedNodeMap atts = ((Node) element).getAttributes();
    if (atts != null) {
        int length = atts.getLength();
        for (int i = 0; i < length; i++) {
            Attr attr = (Attr) atts.item(i);
            String attrName = attr.getName();
            String attrValue = attr.getValue().trim();
            if (attrName.equals("ID")) {
                responseId = attrValue;
            } else if (attrName.equals("InResponseTo")) {
                inResponseTo = attrValue;
            } else if (attrName.equals("Version")) {
                version = attrValue;
            } else if (attrName.equals("IssueInstant")) {
                try {
                    issueInstant = DateUtils.stringToDate(attrValue);
                } catch (ParseException pe) {
                    throw new SAML2Exception(pe.getMessage());
                }
            } else if (attrName.equals("Destination")) {
                destination = attrValue;
            } else if (attrName.equals("Consent")) {
                consent = attrValue;
            }
        }
    }
    // handle child elements
    NodeList nl = element.getChildNodes();
    Node child;
    String childName;
    int length = nl.getLength();
    for (int i = 0; i < length; i++) {
        child = nl.item(i);
        if ((childName = child.getLocalName()) != null) {
            if (childName.equals("Issuer")) {
                if (issuer != null) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("ArtifactResponseImpl." + "parseElement: included more than one " + "Issuer.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
                }
                if (signatureString != null || extensions != null || status != null || anyString != null) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("ArtifactResponseImpl." + "parseElement:wrong sequence.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("schemaViolation"));
                }
                issuer = AssertionFactory.getInstance().createIssuer((Element) child);
            } else if (childName.equals("Signature")) {
                if (signatureString != null) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("ArtifactResponseImpl." + "parseElement:included more than one " + "Signature.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
                }
                if (extensions != null || status != null || anyString != null) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("ArtifactResponseImpl." + "parseElement:wrong sequence.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("schemaViolation"));
                }
                signatureString = XMLUtils.print((Element) child);
                isSigned = true;
            } else if (childName.equals("Extensions")) {
                if (extensions != null) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("ArtifactResponseImpl." + "parseElement:included more than one " + "Extensions.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
                }
                if (status != null || anyString != null) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("ArtifactResponseImpl." + "parseElement:wrong sequence.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("schemaViolation"));
                }
                extensions = ProtocolFactory.getInstance().createExtensions((Element) child);
            } else if (childName.equals("Status")) {
                if (status != null) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("ArtifactResponseImpl." + "parseElement: included more than one " + "Status.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
                }
                if (anyString != null) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element:wrong sequence.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("schemaViolation"));
                }
                status = ProtocolFactory.getInstance().createStatus((Element) child);
            } else {
                if (anyString != null) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("ArtifactResponseImpl." + "parseElement: included more than one " + "any element.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
                }
                anyString = XMLUtils.print((Element) child);
            }
        }
    }
    super.validateData();
    isMutable = false;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) NamedNodeMap(org.w3c.dom.NamedNodeMap) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) ParseException(java.text.ParseException) Attr(org.w3c.dom.Attr)

Aggregations

SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)4 Issuer (com.sun.identity.saml2.assertion.Issuer)3 ArtifactResponse (com.sun.identity.saml2.protocol.ArtifactResponse)3 Element (org.w3c.dom.Element)3 KeyProvider (com.sun.identity.saml.xmlsig.KeyProvider)2 IDPSSOConfigElement (com.sun.identity.saml2.jaxb.entityconfig.IDPSSOConfigElement)2 IDPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)2 SPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement)2 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)2 Artifact (com.sun.identity.saml2.protocol.Artifact)2 ArtifactResolve (com.sun.identity.saml2.protocol.ArtifactResolve)2 Response (com.sun.identity.saml2.protocol.Response)2 Status (com.sun.identity.saml2.protocol.Status)2 X509Certificate (java.security.cert.X509Certificate)2 Date (java.util.Date)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 SOAPConnection (javax.xml.soap.SOAPConnection)2 SOAPException (javax.xml.soap.SOAPException)2 SOAPMessage (javax.xml.soap.SOAPMessage)2 SPSSOConfigElement (com.sun.identity.saml2.jaxb.entityconfig.SPSSOConfigElement)1