Search in sources :

Example 16 with Status

use of com.sun.identity.saml.protocol.Status in project OpenAM by OpenRock.

the class FSSSOAndFedHandler method processAuthnRequest.

/**
     * Processes authentication request.
     * @param authnRequest authentication request
     * @param bPostAuthn <code>true</code> indicates it's post authentication;
     *  <code>false</code> indicates it's pre authentication.
     */
public void processAuthnRequest(FSAuthnRequest authnRequest, boolean bPostAuthn) {
    FSUtils.debug.message("FSSSOAndFedHandler.processAuthnRequest: Called");
    this.authnRequest = authnRequest;
    String message = null;
    String inResponseTo = authnRequest.getRequestID();
    Status status = null;
    FSAuthnResponse errResponse = null;
    spEntityId = authnRequest.getProviderId();
    try {
        spDescriptor = metaManager.getSPDescriptor(realm, spEntityId);
        spConfig = metaManager.getSPDescriptorConfig(realm, spEntityId);
        if (!metaManager.isTrustedProvider(realm, hostedEntityId, spEntityId)) {
            FSUtils.debug.error("FSSSOAndFedHandler.processAuthnRequest: " + "RemoteProvider is not trusted");
            message = FSUtils.bundle.getString("AuthnRequestProcessingFailed");
            status = new Status(new StatusCode("samlp:Responder"), message, null);
            errResponse = new FSAuthnResponse(null, inResponseTo, status, null, relayState);
            errResponse.setMinorVersion(authnRequest.getMinorVersion());
            sendAuthnResponse(errResponse);
            return;
        }
        if (bPostAuthn) {
            if (processPostAuthnSSO(authnRequest)) {
                if (FSUtils.debug.messageEnabled()) {
                    FSUtils.debug.message("FSSSOAndFedHandler." + "processAuthnRequest: AuthnRequest Processing " + "successful");
                }
                return;
            } else {
                if (FSUtils.debug.warningEnabled()) {
                    FSUtils.debug.warning("FSSSOAndFedHandler.processAuthnRequest: " + "AuthnRequest Processing failed");
                }
                message = FSUtils.bundle.getString("AuthnRequestProcessingFailed");
                if (noFedStatus != null) {
                    status = noFedStatus;
                } else {
                    status = new Status(new StatusCode("samlp:Responder"), message, null);
                }
                errResponse = new FSAuthnResponse(null, inResponseTo, status, null, relayState);
                errResponse.setMinorVersion(authnRequest.getMinorVersion());
                sendAuthnResponse(errResponse);
                return;
            }
        } else {
            boolean authnRequestSigned = spDescriptor.isAuthnRequestsSigned();
            if (FSUtils.debug.messageEnabled()) {
                FSUtils.debug.message("FSSSOAndFedHandler.processAuthnRequest: " + "ProviderID : " + spEntityId + " AuthnRequestSigned :this is for testing " + authnRequestSigned);
            }
            if (FSServiceUtils.isSigningOn()) {
                if (authnRequestSigned) {
                    //verify request signature
                    if (!verifyRequestSignature(authnRequest)) {
                        FSUtils.debug.error("FSSSOAndFedHandler." + "processAuthnRequest: " + "AuthnRequest Signature Verification Failed");
                        message = FSUtils.bundle.getString("signatureVerificationFailed");
                        String[] data = { message };
                        LogUtil.error(Level.INFO, LogUtil.SIGNATURE_VERIFICATION_FAILED, data, ssoToken);
                        status = new Status(new StatusCode("samlp:Responder", new StatusCode("lib:UnsignedAuthnRequest", null)), message, null);
                        errResponse = new FSAuthnResponse(null, inResponseTo, status, null, relayState);
                        errResponse.setMinorVersion(authnRequest.getMinorVersion());
                        sendAuthnResponse(errResponse);
                        return;
                    } else {
                        if (FSUtils.debug.messageEnabled()) {
                            FSUtils.debug.message("FSSSOAndFedHandler. processAuthnRequest" + ": AuthnRequest Signature Verified");
                        }
                    }
                }
            }
            if (processPreAuthnSSO(authnRequest)) {
                if (FSUtils.debug.messageEnabled()) {
                    FSUtils.debug.message("FSSSOAndFedHandler.processAuthnRequest: " + "AuthnRequest Processing successful");
                }
                return;
            } else {
                if (FSUtils.debug.warningEnabled()) {
                    FSUtils.debug.warning("FSSSOAndFedHandler.processAuthnRequest: " + "AuthnRequest Processing failed");
                }
                String[] data = { FSUtils.bundle.getString("AuthnRequestProcessingFailed") };
                LogUtil.error(Level.INFO, LogUtil.AUTHN_REQUEST_PROCESSING_FAILED, data, ssoToken);
                message = FSUtils.bundle.getString("AuthnRequestProcessingFailed");
                status = new Status(new StatusCode("samlp:Responder"), message, null);
                if (noFedStatus != null) {
                    status = noFedStatus;
                }
                errResponse = new FSAuthnResponse(null, inResponseTo, status, null, relayState);
                errResponse.setMinorVersion(authnRequest.getMinorVersion());
                sendAuthnResponse(errResponse);
                return;
            }
        }
    } catch (Exception e) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        e.printStackTrace(new PrintStream(out));
        FSUtils.debug.error("FSSSOAndFedHandler.processAuthnRequest: " + "Exception Occured: " + e.getMessage() + "Stack trace is " + out.toString());
        message = FSUtils.bundle.getString("AuthnRequestProcessingFailed");
        try {
            status = new Status(new StatusCode("samlp:Responder"), message, null);
            errResponse = new FSAuthnResponse(null, inResponseTo, status, null, relayState);
            errResponse.setMinorVersion(authnRequest.getMinorVersion());
            sendAuthnResponse(errResponse);
        } catch (Exception ex) {
            if (FSUtils.debug.messageEnabled()) {
                FSUtils.debug.message("FSSSOAndFedHandler.processAuthnRequest: " + "Exception Occured: ", ex);
            }
        }
    }
}
Also used : Status(com.sun.identity.saml.protocol.Status) PrintStream(java.io.PrintStream) FSAuthnResponse(com.sun.identity.federation.message.FSAuthnResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) StatusCode(com.sun.identity.saml.protocol.StatusCode) SessionException(com.sun.identity.plugin.session.SessionException) IDFFMetaException(com.sun.identity.federation.meta.IDFFMetaException) FSAccountMgmtException(com.sun.identity.federation.accountmgmt.FSAccountMgmtException) SAMLException(com.sun.identity.saml.common.SAMLException) FSException(com.sun.identity.federation.common.FSException) IOException(java.io.IOException) FSRedirectException(com.sun.identity.federation.common.FSRedirectException)

Example 17 with Status

use of com.sun.identity.saml.protocol.Status in project OpenAM by OpenRock.

the class SingleLogoutManager method sendLogoutResponse.

/**
     * Sends logout response, this is for the case of HTTP binding
     * There are two cases here:
     * 1. IDP initiated HTTP Logout, just redirect user browser to original
     *    relaystate.
     * 2. SP initiated HTTP logout, need to send LogoutResponse back to SP.
     */
void sendLogoutResponse(HttpServletRequest request, HttpServletResponse response, String relayState) throws IOException {
    if (debug.messageEnabled()) {
        debug.message("SingleLogoutManager.sendLogoutResponse: relaystate=" + relayState);
    }
    String logoutResponseXML = (String) sloResponseXMLMap.get(relayState);
    if (logoutResponseXML == null) {
        // first case, just redirect to original relayState
        String origRelayState = (String) relayStateMap.get(relayState);
        int logoutStatus = ((Integer) currentStatusMap.get(relayState)).intValue();
        String statusString = MultiProtocolUtils.getLogoutStatus(logoutStatus);
        if ((origRelayState == null) || (origRelayState.length() == 0)) {
            // TODO : get default single logout URL for each protocol
            response.getWriter().print("Logout DONE. Status = " + statusString);
        } else {
            // include logout status
            if (origRelayState.indexOf("?") == -1) {
                response.sendRedirect(origRelayState + "?" + SingleLogoutManager.STATUS_PARAM + "=" + statusString);
            } else {
                response.sendRedirect(origRelayState + "&" + SingleLogoutManager.STATUS_PARAM + "=" + statusString);
            }
        }
    } else {
        String protocol = (String) origProtocolMap.get(relayState);
        String spEntityID = (String) spEntityIDMap.get(relayState);
        String origRelayState = (String) relayStateMap.get(relayState);
        String realm = (String) realmMap.get(relayState);
        String idpEntityID = (String) idpEntityIDMap.get(relayState);
        int currentStatus = ((Integer) currentStatusMap.get(relayState)).intValue();
        if (protocol.equals(SingleLogoutManager.SAML2)) {
            try {
                LogoutResponse logResp = ProtocolFactory.getInstance().createLogoutResponse(logoutResponseXML);
                String location = logResp.getDestination();
                String statusVal = logResp.getStatus().getStatusCode().getValue();
                String newVal = getNewStatusCode(currentStatus, statusVal);
                if (!statusVal.equals(newVal)) {
                    logResp.getStatus().getStatusCode().setValue(statusVal);
                }
                if (debug.messageEnabled()) {
                    debug.message("SingleLogoutManager.sendLogoutRes:" + "(SAML2) location=" + location + " orig status=" + statusVal + ", new status=" + newVal + ", orig relay=" + origRelayState + ", realm=" + realm + ", idpEntityID=" + idpEntityID + ", spEntityID=" + spEntityID);
                }
                LogoutUtil.sendSLOResponse(response, logResp, location, origRelayState, realm, idpEntityID, SAML2Constants.IDP_ROLE, spEntityID);
            } catch (SAML2Exception ex) {
                debug.error("SingleLogoutManager.sendLogoutResponse:saml2", ex);
                throw new IOException(ex.getMessage());
            }
        } else if (protocol.equals(SingleLogoutManager.IDFF)) {
            boolean failed = false;
            String logoutDoneURL = null;
            try {
                debug.message("SingleLogoutManager.sendLogoutResp: IDFF");
                IDFFMetaManager metaManager = FSUtils.getIDFFMetaManager();
                ProviderDescriptorType descriptor = metaManager.getSPDescriptor(realm, spEntityID);
                String retURL = descriptor.getSingleLogoutServiceReturnURL();
                Element elem = XMLUtils.toDOMDocument(logoutResponseXML, SingleLogoutManager.debug).getDocumentElement();
                FSLogoutResponse responseLogout = new FSLogoutResponse(elem);
                BaseConfigType hostedConfig = metaManager.getIDPDescriptorConfig(realm, idpEntityID);
                logoutDoneURL = FSServiceUtils.getLogoutDonePageURL(request, hostedConfig, null);
                Status status = responseLogout.getStatus();
                String statusVal = status.getStatusCode().getValue();
                String newVal = getNewStatusCode(currentStatus, statusVal);
                if (!statusVal.equals(newVal)) {
                    com.sun.identity.saml.protocol.StatusCode statCode = new com.sun.identity.saml.protocol.StatusCode(newVal);
                    com.sun.identity.saml.protocol.Status stat = new com.sun.identity.saml.protocol.Status(statCode);
                    responseLogout.setStatus(stat);
                }
                if (debug.messageEnabled()) {
                    debug.message("SingleLogoutManager.sendLogoutRes:" + "(IDFF) orig status=" + statusVal + ", new status=" + newVal + ", orig relay=" + origRelayState + ", logout done URL=" + logoutDoneURL + ", realm=" + realm + ", idpEntityID=" + idpEntityID + ", spEntityID=" + spEntityID);
                }
                String urlEncodedResponse = responseLogout.toURLEncodedQueryString();
                // Sign the request querystring
                if (FSServiceUtils.isSigningOn()) {
                    String certAlias = IDFFMetaUtils.getFirstAttributeValueFromConfig(hostedConfig, IFSConstants.SIGNING_CERT_ALIAS);
                    if (certAlias == null || certAlias.length() == 0) {
                        if (debug.messageEnabled()) {
                            debug.message("SingleLogoutManager.sendLogoutRes:" + "signSAMLRequest couldn't obtain cert alias.");
                        }
                        throw new SAMLResponderException(FSUtils.bundle.getString(IFSConstants.NO_CERT_ALIAS));
                    } else {
                        urlEncodedResponse = FSSignatureUtil.signAndReturnQueryString(urlEncodedResponse, certAlias);
                    }
                }
                StringBuffer redirectURL = new StringBuffer();
                redirectURL.append(retURL);
                if (retURL.indexOf(IFSConstants.QUESTION_MARK) == -1) {
                    redirectURL.append(IFSConstants.QUESTION_MARK);
                } else {
                    redirectURL.append(IFSConstants.AMPERSAND);
                }
                redirectURL.append(urlEncodedResponse);
                if (debug.messageEnabled()) {
                    debug.message("SingleLogoutManager.sendResponse " + "for IDFF, url = " + redirectURL.toString());
                }
                response.sendRedirect(redirectURL.toString());
            } catch (FSMsgException ex) {
                debug.error("SingleLogoutManager.sendLogoutRes", ex);
                failed = true;
            } catch (SAMLException ex) {
                debug.error("SingleLogoutManager.sendLogoutRes", ex);
                failed = true;
                ;
            } catch (IDFFMetaException ex) {
                debug.error("SingleLogoutManager.sendLogoutRes", ex);
                failed = true;
            } catch (IOException ex) {
                debug.error("SingleLogoutManager.sendLogoutRes", ex);
                failed = true;
            }
            if (failed) {
                FSServiceUtils.returnLocallyAfterOperation(response, logoutDoneURL, false, IFSConstants.LOGOUT_SUCCESS, IFSConstants.LOGOUT_FAILURE);
            }
        } else if (protocol.equals(SingleLogoutManager.WS_FED)) {
            debug.message("SingleLogoutManager.sendLogoutResponse: WSFED");
            if (origRelayState != null) {
                response.sendRedirect(origRelayState);
            } else {
                response.getWriter().print("Logout DONE.");
            }
        } else {
            // should never come here
            debug.error("SingleLogoutManager.sendLogoutResponse: invalid" + " protocol : " + protocol);
        }
    }
    cleanupParameters(relayState);
    return;
}
Also used : Element(org.w3c.dom.Element) SAMLException(com.sun.identity.saml.common.SAMLException) BaseConfigType(com.sun.identity.federation.jaxb.entityconfig.BaseConfigType) Status(com.sun.identity.saml.protocol.Status) Status(com.sun.identity.saml.protocol.Status) FSMsgException(com.sun.identity.federation.message.common.FSMsgException) FSLogoutResponse(com.sun.identity.federation.message.FSLogoutResponse) LogoutResponse(com.sun.identity.saml2.protocol.LogoutResponse) IDFFMetaException(com.sun.identity.federation.meta.IDFFMetaException) ProviderDescriptorType(com.sun.identity.liberty.ws.meta.jaxb.ProviderDescriptorType) IOException(java.io.IOException) FSLogoutResponse(com.sun.identity.federation.message.FSLogoutResponse) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) IDFFMetaManager(com.sun.identity.federation.meta.IDFFMetaManager) SAMLResponderException(com.sun.identity.saml.common.SAMLResponderException)

Example 18 with Status

use of com.sun.identity.saml.protocol.Status in project OpenAM by OpenRock.

the class SAMLSOAPReceiver method extractProcessRequest.

/**
     * Extracts the Request object from the SOAPMessage return corresponding
     * response.
     */
private Response extractProcessRequest(HttpServletRequest servletReq, org.w3c.dom.Element body, Set partnerSourceID) {
    Response retResponse = null;
    String respID = SAMLUtils.generateID();
    String inResponseTo = null;
    List contents = new ArrayList();
    String message = null;
    Status status;
    String remoteAddr = ClientUtils.getClientIPAddress(servletReq);
    String recipient = remoteAddr;
    String invalidRespPrefix = SAMLUtils.bundle.getString("invalidRequestLogMessage") + " " + remoteAddr + ": ";
    String respPrefix = SAMLUtils.bundle.getString("responseLogMessage") + " " + remoteAddr + ": ";
    NodeList nl = body.getElementsByTagNameNS(sc.PROTOCOL_NAMESPACE_URI, "Request");
    int length = nl.getLength();
    if (length == 0) {
        SAMLUtils.debug.error("SOAPReceiver: Body does not have a Request");
        message = SAMLUtils.bundle.getString("missingRequest");
        try {
            status = new Status(new StatusCode("samlp:Requester"), message, null);
            retResponse = new Response(respID, inResponseTo, status, recipient, contents);
        } catch (SAMLException se) {
            SAMLUtils.debug.error("SOAPReceiver:Fatal error, cannot " + "create status or response:" + se.getMessage());
        }
        String[] data = { invalidRespPrefix, retResponse.toString() };
        LogUtils.error(java.util.logging.Level.INFO, LogUtils.INVALID_REQUEST, data);
        return retResponse;
    }
    boolean foundRequest = false;
    Request req = null;
    for (int i = 0; i < length; i++) {
        Node child = (Node) nl.item(i);
        if (child.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }
        if (child.getLocalName().equals("Request")) {
            try {
                req = new Request((Element) child);
                SAMLUtils.debug.message("found request ");
                if (SAMLUtils.debug.messageEnabled()) {
                    SAMLUtils.debug.message(" Received Request:" + req.toString());
                }
                String[] data = { SAMLUtils.bundle.getString("requestLogMessage") + " " + remoteAddr, req.toString() };
                LogUtils.access(java.util.logging.Level.FINE, LogUtils.SOAP_REQUEST_MESSAGE, data);
                inResponseTo = req.getRequestID();
                foundRequest = true;
                break;
            } catch (SAMLRequesterException ss) {
                if (SAMLUtils.debug.messageEnabled()) {
                    SAMLUtils.debug.message("SOAPReceiver:setting " + "status to samlp:Requester" + " " + ss.getMessage());
                }
                message = new String(ss.getMessage());
                try {
                    status = new Status(new StatusCode("samlp:Requester"), message, null);
                    retResponse = new Response(respID, inResponseTo, status, recipient, contents);
                } catch (SAMLException se) {
                    SAMLUtils.debug.error("SOAPReceiver:Fatal error, " + "cannot create status or response:" + se.getMessage());
                }
                String[] data = { invalidRespPrefix, retResponse.toString() };
                LogUtils.error(java.util.logging.Level.INFO, LogUtils.INVALID_REQUEST, data);
                return retResponse;
            } catch (SAMLRequestVersionTooHighException sv) {
                String mesg = new String(sv.getMessage());
                StringTokenizer tok1 = new StringTokenizer(mesg, "|");
                inResponseTo = tok1.nextToken();
                message = tok1.nextToken();
                if (SAMLUtils.debug.messageEnabled()) {
                    SAMLUtils.debug.message("SOAPReceiver:setting " + "status to samlp:VersionMismatch" + " " + message);
                }
                try {
                    status = new Status(new StatusCode("samlp:RequestVersionTooHigh"), message, null);
                    retResponse = new Response(respID, inResponseTo, status, recipient, contents);
                } catch (SAMLException se) {
                    SAMLUtils.debug.error("SOAPReceiver:Fatal error, " + "cannot create status or response:" + se.getMessage());
                }
                String[] data = { invalidRespPrefix, retResponse.toString() };
                LogUtils.error(java.util.logging.Level.INFO, LogUtils.INVALID_REQUEST, data);
                return retResponse;
            } catch (SAMLRequestVersionTooLowException sv) {
                String mesg = new String(sv.getMessage());
                StringTokenizer tok1 = new StringTokenizer(mesg, "|");
                inResponseTo = tok1.nextToken();
                message = tok1.nextToken();
                if (SAMLUtils.debug.messageEnabled()) {
                    SAMLUtils.debug.message("SOAPReceiver:setting " + "status to samlp:VersionMismatch" + " " + message);
                }
                try {
                    status = new Status(new StatusCode("samlp:RequestVersionTooLow"), message, null);
                    retResponse = new Response(respID, inResponseTo, status, recipient, contents);
                } catch (SAMLException se) {
                    SAMLUtils.debug.error("SOAPReceiver:Fatal error, " + "cannot create status or response:" + se.getMessage());
                }
                String[] data = { invalidRespPrefix, retResponse.toString() };
                LogUtils.error(java.util.logging.Level.INFO, LogUtils.INVALID_REQUEST, data);
                return retResponse;
            } catch (Exception e) {
                if (SAMLUtils.debug.messageEnabled()) {
                    SAMLUtils.debug.message("SOAPReceiver:setting " + "status to samlp:Responder" + " " + e.getMessage());
                }
                message = new String(e.getMessage());
                try {
                    status = new Status(new StatusCode("samlp:Responder"), message, null);
                    retResponse = new Response(respID, inResponseTo, status, recipient, contents);
                } catch (SAMLException se) {
                    SAMLUtils.debug.error("SOAPReceiver:Fatal error, " + "cannot create status or response:" + se.getMessage());
                }
                String[] data = { invalidRespPrefix, retResponse.toString() };
                LogUtils.error(java.util.logging.Level.INFO, LogUtils.INVALID_REQUEST, data);
                return retResponse;
            }
        }
    }
    if (!(foundRequest)) {
        SAMLUtils.debug.error("SOAPReceiver: Body does not have a Request");
        message = SAMLUtils.bundle.getString("missingRequest");
        try {
            status = new Status(new StatusCode("samlp:Requester"), message, null);
            retResponse = new Response(respID, inResponseTo, status, recipient, contents);
        } catch (SAMLException se) {
            SAMLUtils.debug.error("SOAPReceiver:Fatal error, " + "cannot create status or response:" + se.getMessage());
        }
        String[] data = { invalidRespPrefix, retResponse.toString() };
        LogUtils.error(java.util.logging.Level.INFO, LogUtils.INVALID_REQUEST, data);
        return retResponse;
    } else {
        // found request now process it
        if (!req.isSignatureValid()) {
            if (SAMLUtils.debug.messageEnabled()) {
                SAMLUtils.debug.message("SOAPReceiver: couldn't verify " + "the signature on Request.");
            }
            message = SAMLUtils.bundle.getString("cannotVerifyRequest");
            try {
                status = new Status(new StatusCode("samlp:Requester"), message, null);
                retResponse = new Response(respID, inResponseTo, status, recipient, contents);
                retResponse.setMajorVersion(req.getMajorVersion());
                retResponse.setMinorVersion(req.getMinorVersion());
            } catch (SAMLException se) {
                SAMLUtils.debug.error("SOAPReceiver:Fatal error, " + "cannot create status or response", se);
                String[] data = { SAMLUtils.bundle.getString("cannotBuildResponse") };
                LogUtils.error(java.util.logging.Level.INFO, LogUtils.BUILD_RESPONSE_ERROR, data);
            }
            String[] data = { respPrefix, retResponse.toString() };
            LogUtils.access(java.util.logging.Level.INFO, LogUtils.SENDING_RESPONSE, data);
            return retResponse;
        }
        int reqType = req.getContentType();
        if (reqType == Request.NOT_SUPPORTED) {
            if (SAMLUtils.debug.messageEnabled()) {
                SAMLUtils.debug.message("SOAPReceiver:Found " + "element in the request which are not supported");
            }
            message = SAMLUtils.bundle.getString("unsupportedElement");
            try {
                status = new Status(new StatusCode("samlp:Responder"), message, null);
                retResponse = new Response(respID, inResponseTo, status, recipient, contents);
                retResponse.setMajorVersion(req.getMajorVersion());
                retResponse.setMinorVersion(req.getMinorVersion());
            } catch (SAMLException se) {
                SAMLUtils.debug.error("SOAPReceiver:Fatal error, " + "cannot create status or response", se);
                String[] data = { SAMLUtils.bundle.getString("cannotBuildResponse") };
                LogUtils.error(java.util.logging.Level.INFO, LogUtils.BUILD_RESPONSE_ERROR, data);
            }
            String[] data = { respPrefix, retResponse.toString() };
            LogUtils.access(java.util.logging.Level.INFO, LogUtils.SENDING_RESPONSE, data);
            return retResponse;
        }
        List respondWith = req.getRespondWith();
        if (!parseRespondWith(respondWith)) {
            SAMLUtils.debug.error("SOAPReceiver:Supported statements " + "are not present in the RespondWith element.");
            message = SAMLUtils.bundle.getString("unsupportedStatement");
            try {
                status = new Status(new StatusCode("samlp:Responder"), message, null);
                retResponse = new Response(respID, inResponseTo, status, recipient, contents);
                retResponse.setMajorVersion(req.getMajorVersion());
                retResponse.setMinorVersion(req.getMinorVersion());
            } catch (SAMLException se) {
                SAMLUtils.debug.error("SOAPReceiver:Fatal error, " + "cannot create status or response", se);
                String[] data = { SAMLUtils.bundle.getString("cannotBuildResponse") };
                LogUtils.error(java.util.logging.Level.INFO, LogUtils.BUILD_RESPONSE_ERROR, data);
            }
            String[] data = { respPrefix, retResponse.toString() };
            LogUtils.access(java.util.logging.Level.INFO, LogUtils.SENDING_RESPONSE, data);
            return retResponse;
        }
        AssertionManager am = null;
        try {
            am = AssertionManager.getInstance();
        } catch (SAMLException se) {
            if (SAMLUtils.debug.messageEnabled()) {
                SAMLUtils.debug.message("SOAPReceiver: Cannot" + " instantiate AssertionManager");
            }
            message = se.getMessage();
            try {
                status = new Status(new StatusCode("samlp:Responder"), message, null);
                retResponse = new Response(respID, inResponseTo, status, recipient, contents);
                retResponse.setMajorVersion(req.getMajorVersion());
                retResponse.setMinorVersion(req.getMinorVersion());
            } catch (SAMLException sse) {
                SAMLUtils.debug.error("SOAPReceiver:Fatal error, " + "cannot create status or response", sse);
                String[] data = { SAMLUtils.bundle.getString("cannotBuildResponse") };
                LogUtils.error(java.util.logging.Level.INFO, LogUtils.BUILD_RESPONSE_ERROR, data);
            }
            String[] data = { respPrefix, retResponse.toString() };
            LogUtils.access(java.util.logging.Level.INFO, LogUtils.SENDING_RESPONSE, data);
            return retResponse;
        }
        List artifacts = null;
        List assertions = new ArrayList();
        if (reqType == Request.ASSERTION_ARTIFACT) {
            artifacts = req.getAssertionArtifact();
            length = artifacts.size();
            // ensure that all the artifacts have this site's sourceID
            for (int j = 0; j < length; j++) {
                AssertionArtifact art = (AssertionArtifact) artifacts.get(j);
                if (!isThisSiteID(art.getSourceID())) {
                    if (SAMLUtils.debug.messageEnabled()) {
                        SAMLUtils.debug.message("SOAPReceiver:Artifact" + " has invalid SourceID");
                    }
                    message = SAMLUtils.bundle.getString("mismatchSourceID");
                    try {
                        status = new Status(new StatusCode("samlp:Requester"), message, null);
                        retResponse = new Response(respID, inResponseTo, status, recipient, contents);
                        retResponse.setMajorVersion(req.getMajorVersion());
                        retResponse.setMinorVersion(req.getMinorVersion());
                    } catch (SAMLException ex) {
                        SAMLUtils.debug.error("SOAPReceiver:" + "Fatal error, " + "cannot create status or response", ex);
                        String[] data = { SAMLUtils.bundle.getString("cannotBuildResponse") };
                        LogUtils.error(java.util.logging.Level.INFO, LogUtils.BUILD_RESPONSE_ERROR, data);
                    }
                    String[] data = { respPrefix, retResponse.toString() };
                    LogUtils.access(java.util.logging.Level.INFO, LogUtils.SENDING_RESPONSE, data);
                    return retResponse;
                }
            }
            // for loop to go through artifacts to check for sourceID
            for (int i = 0; i < length; i++) {
                AssertionArtifact artifact = (AssertionArtifact) artifacts.get(i);
                Assertion assertion = null;
                try {
                    assertion = am.getAssertion(artifact, partnerSourceID);
                } catch (SAMLException se) {
                    if (SAMLUtils.debug.messageEnabled()) {
                        SAMLUtils.debug.message("SOAPReceiver:" + " could not find matching assertion");
                    }
                    message = se.getMessage();
                    try {
                        status = new Status(new StatusCode("samlp:Success"), message, null);
                        retResponse = new Response(respID, inResponseTo, status, recipient, contents);
                        retResponse.setMajorVersion(req.getMajorVersion());
                        retResponse.setMinorVersion(req.getMinorVersion());
                    } catch (SAMLException sse) {
                        SAMLUtils.debug.error("SOAPReceiver:Fatal error, " + "cannot create status or response", sse);
                        String[] data = { SAMLUtils.bundle.getString("cannotBuildResponse") };
                        LogUtils.error(java.util.logging.Level.INFO, LogUtils.BUILD_RESPONSE_ERROR, data);
                    }
                    String[] data = { respPrefix, retResponse.toString() };
                    LogUtils.access(java.util.logging.Level.INFO, LogUtils.SENDING_RESPONSE, data);
                    return retResponse;
                }
                if (assertion != null) {
                    assertions.add(i, assertion);
                }
            }
        } else if (reqType == Request.ASSERTION_ID_REFERENCE) {
            List assertionIdRefs = req.getAssertionIDReference();
            length = assertionIdRefs.size();
            for (int i = 0; i < length; i++) {
                AssertionIDReference aidRef = (AssertionIDReference) assertionIdRefs.get(i);
                Assertion assertion = null;
                try {
                    assertion = am.getAssertion(aidRef, partnerSourceID);
                } catch (SAMLException se) {
                    if (SAMLUtils.debug.messageEnabled()) {
                        SAMLUtils.debug.message("SOAPReceiver:" + " could not find matching assertion");
                    }
                    message = se.getMessage();
                    try {
                        status = new Status(new StatusCode("samlp:Success"), message, null);
                        retResponse = new Response(respID, inResponseTo, status, recipient, contents);
                        retResponse.setMajorVersion(req.getMajorVersion());
                        retResponse.setMinorVersion(req.getMinorVersion());
                    } catch (SAMLException sse) {
                        SAMLUtils.debug.error("SOAPReceiver:Fatal error, " + "cannot create status or response", sse);
                        String[] data = { SAMLUtils.bundle.getString("cannotBuildResponse") };
                        LogUtils.error(java.util.logging.Level.INFO, LogUtils.BUILD_RESPONSE_ERROR, data);
                    }
                    String[] data = { respPrefix, retResponse.toString() };
                    LogUtils.access(java.util.logging.Level.INFO, LogUtils.SENDING_RESPONSE, data);
                    return retResponse;
                }
                if (assertion != null) {
                    assertions.add(i, assertion);
                }
            }
        } else if ((reqType == Request.AUTHENTICATION_QUERY) || (reqType == Request.AUTHORIZATION_DECISION_QUERY) || (reqType == Request.ATTRIBUTE_QUERY)) {
            Query query = req.getQuery();
            if (query != null) {
                Assertion assertion = null;
                try {
                    // if we come here, partnerSourceID is not empty
                    // always pass the first matching sourceID in
                    // need to find solution to handle multiple matches:TBD
                    assertion = am.getAssertion(query, (String) ((Iterator) partnerSourceID.iterator()).next());
                } catch (SAMLException se) {
                    if (SAMLUtils.debug.messageEnabled()) {
                        SAMLUtils.debug.message("SOAPReceiver:" + " could not find matching assertion");
                    }
                    message = se.getMessage();
                    try {
                        status = new Status(new StatusCode("samlp:Success"), message, null);
                        retResponse = new Response(respID, inResponseTo, status, recipient, contents);
                        retResponse.setMajorVersion(req.getMajorVersion());
                        retResponse.setMinorVersion(req.getMinorVersion());
                    } catch (SAMLException sse) {
                        SAMLUtils.debug.error("SOAPReceiver:Fatal " + " error, cannot create status or " + " response", sse);
                        String[] data = { SAMLUtils.bundle.getString("cannotBuildResponse") };
                        LogUtils.error(java.util.logging.Level.INFO, LogUtils.BUILD_RESPONSE_ERROR, data);
                    }
                    String[] data = { respPrefix, retResponse.toString() };
                    LogUtils.access(java.util.logging.Level.INFO, LogUtils.SENDING_RESPONSE, data);
                    return retResponse;
                }
                if (assertion != null) {
                    assertions.add(assertion);
                }
            }
        } else {
            //
            if (SAMLUtils.debug.messageEnabled()) {
                SAMLUtils.debug.message("SOAPReceiver:Request " + "contents has element which is not supported at this" + " time");
            }
            message = SAMLUtils.bundle.getString("unsupportedElement");
            try {
                status = new Status(new StatusCode("samlp:Responder"), message, null);
                retResponse = new Response(respID, inResponseTo, status, recipient, contents);
                retResponse.setMajorVersion(req.getMajorVersion());
                retResponse.setMinorVersion(req.getMinorVersion());
            } catch (SAMLException se) {
                SAMLUtils.debug.error("SOAPReceiver:Fatal error, " + "cannot create status or response", se);
                String[] data = { SAMLUtils.bundle.getString("cannotBuildResponse") };
                LogUtils.error(java.util.logging.Level.INFO, LogUtils.BUILD_RESPONSE_ERROR, data);
            }
            String[] data = { respPrefix, retResponse.toString() };
            LogUtils.access(java.util.logging.Level.INFO, LogUtils.SENDING_RESPONSE, data);
            return retResponse;
        }
        int assertionSize = assertions.size();
        if (SAMLUtils.debug.messageEnabled()) {
            SAMLUtils.debug.message("found " + assertionSize + " assertions.");
        }
        // Request received. 
        for (int i = 0; i < assertionSize; i++) {
            Response resp = validateStatements((Assertion) assertions.get(i), respondWith, contents, i, respID, inResponseTo, recipient);
            if (resp != null) {
                String[] data = { respPrefix, retResponse.toString() };
                LogUtils.access(java.util.logging.Level.INFO, LogUtils.SENDING_RESPONSE, data);
                retResponse.setMajorVersion(req.getMajorVersion());
                retResponse.setMinorVersion(req.getMinorVersion());
                return resp;
            }
        // else there was no mismatch with respondWith element
        }
        if (reqType == Request.ASSERTION_ARTIFACT) {
            if (contents.size() == artifacts.size()) {
                message = null;
                if (SAMLUtils.debug.messageEnabled()) {
                    SAMLUtils.debug.message("SOAPReceiver: Matching " + "Assertion found");
                }
                try {
                    status = new Status(new StatusCode("samlp:Success"), message, null);
                    retResponse = new Response(respID, inResponseTo, status, recipient, contents);
                    retResponse.setMajorVersion(req.getMajorVersion());
                    retResponse.setMinorVersion(req.getMinorVersion());
                } catch (SAMLException se) {
                    SAMLUtils.debug.error("SOAPReceiver:Fatal error, " + "cannot create status or response", se);
                    String[] data = { SAMLUtils.bundle.getString("cannotBuildResponse") };
                    LogUtils.error(java.util.logging.Level.INFO, LogUtils.BUILD_RESPONSE_ERROR, data);
                }
                String[] data = { respPrefix, retResponse.toString() };
                LogUtils.access(java.util.logging.Level.FINE, LogUtils.SENDING_RESPONSE, data);
                return retResponse;
            } else {
                message = SAMLUtils.bundle.getString("unequalMatch");
                try {
                    status = new Status(new StatusCode("samlp:Success"), message, null);
                    //contents = null;
                    retResponse = new Response(respID, inResponseTo, status, recipient, contents);
                    retResponse.setMajorVersion(req.getMajorVersion());
                    retResponse.setMinorVersion(req.getMinorVersion());
                } catch (SAMLException se) {
                    SAMLUtils.debug.error("SOAPReceiver:Fatal error, " + "cannot create status or response", se);
                    String[] data = { SAMLUtils.bundle.getString("cannotBuildResponse") };
                    LogUtils.error(java.util.logging.Level.INFO, LogUtils.BUILD_RESPONSE_ERROR, data);
                }
                String[] data = { respPrefix, retResponse.toString() };
                LogUtils.access(java.util.logging.Level.INFO, LogUtils.SENDING_RESPONSE, data);
                return retResponse;
            }
        } else {
            // build response for all the other type of request
            try {
                status = new Status(new StatusCode("samlp:Success"), message, null);
                retResponse = new Response(respID, inResponseTo, status, recipient, contents);
                retResponse.setMajorVersion(req.getMajorVersion());
                retResponse.setMinorVersion(req.getMinorVersion());
            } catch (SAMLException se) {
                SAMLUtils.debug.error("SOAPReceiver:Fatal error, " + "cannot create status or response", se);
                String[] data = { SAMLUtils.bundle.getString("cannotBuildResponse") };
                LogUtils.error(java.util.logging.Level.INFO, LogUtils.BUILD_RESPONSE_ERROR, data);
            }
        }
    }
    // end of else found request
    if (LogUtils.isAccessLoggable(java.util.logging.Level.FINER)) {
        String[] data = { respPrefix, retResponse.toString() };
        LogUtils.access(java.util.logging.Level.FINER, LogUtils.SENDING_RESPONSE, data);
    } else {
        String[] data = { respPrefix, retResponse.getResponseID() };
        LogUtils.access(java.util.logging.Level.INFO, LogUtils.SENDING_RESPONSE, data);
    }
    return retResponse;
}
Also used : Status(com.sun.identity.saml.protocol.Status) Query(com.sun.identity.saml.protocol.Query) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) SOAPElement(javax.xml.soap.SOAPElement) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) Request(com.sun.identity.saml.protocol.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) Assertion(com.sun.identity.saml.assertion.Assertion) SAMLRequesterException(com.sun.identity.saml.common.SAMLRequesterException) StatusCode(com.sun.identity.saml.protocol.StatusCode) SAMLException(com.sun.identity.saml.common.SAMLException) ServletException(javax.servlet.ServletException) SOAPException(javax.xml.soap.SOAPException) SAMLRequestVersionTooHighException(com.sun.identity.saml.common.SAMLRequestVersionTooHighException) SAMLRequesterException(com.sun.identity.saml.common.SAMLRequesterException) SAMLRequestVersionTooLowException(com.sun.identity.saml.common.SAMLRequestVersionTooLowException) SAMLException(com.sun.identity.saml.common.SAMLException) AssertionArtifact(com.sun.identity.saml.protocol.AssertionArtifact) Response(com.sun.identity.saml.protocol.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) StringTokenizer(java.util.StringTokenizer) AssertionManager(com.sun.identity.saml.AssertionManager) SAMLRequestVersionTooLowException(com.sun.identity.saml.common.SAMLRequestVersionTooLowException) SAMLRequestVersionTooHighException(com.sun.identity.saml.common.SAMLRequestVersionTooHighException) List(java.util.List) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) AssertionIDReference(com.sun.identity.saml.assertion.AssertionIDReference)

Example 19 with Status

use of com.sun.identity.saml.protocol.Status in project OpenAM by OpenRock.

the class FSNameRegistrationResponse method parseURLEncodedRequest.

/**
     * Returns <code>FSNameRegistrationLogoutResponse</code> object. The
     * object is creating by parsing the <code>HttpServletRequest</code>
     * object.
     *
     * @param request the <code>HttpServletRequest</code> object.
     * @throws FSMsgException if there is an error
     *         creating this object.
     */
public static FSNameRegistrationResponse parseURLEncodedRequest(HttpServletRequest request) throws FSMsgException, SAMLException {
    FSNameRegistrationResponse retNameRegistrationResponse = new FSNameRegistrationResponse();
    try {
        FSUtils.debug.message("checking minor version");
        retNameRegistrationResponse.majorVersion = Integer.parseInt(request.getParameter("MajorVersion"));
        retNameRegistrationResponse.minorVersion = Integer.parseInt(request.getParameter("MinorVersion"));
    } catch (NumberFormatException ex) {
        FSUtils.debug.error("FSNameRegistrationResponse.parseURL" + "EncodedRequest: version parsing error:" + ex);
        throw new FSMsgException("invalidNumber", null);
    }
    if (request.getParameter("ResponseID") != null) {
        retNameRegistrationResponse.responseID = request.getParameter("ResponseID");
    } else {
        FSUtils.debug.error("FSNameRegistrationResponse.parseURL" + "EncodedRequest: Response ID is null");
        String[] args = { IFSConstants.RESPONSE_ID };
        throw new FSMsgException("missingAttribute", args);
    }
    String instantString = request.getParameter("IssueInstant");
    if (instantString == null || instantString.length() == 0) {
        FSUtils.debug.error("FSNameRegistrationResponse.parseURL" + "EncodedRequest: Issue Instant is null");
        String[] args = { IFSConstants.ISSUE_INSTANT };
        throw new FSMsgException("missingAttribute", args);
    }
    try {
        retNameRegistrationResponse.issueInstant = DateUtils.stringToDate(instantString);
    } catch (ParseException e) {
        FSUtils.debug.error("FSNameRegistrationResponse.parseURL" + "EncodedRequest: Can not parse Issue Instant", e);
        throw new FSMsgException("parseError", null);
    }
    if (request.getParameter("ProviderID") != null) {
        retNameRegistrationResponse.providerId = request.getParameter("ProviderID");
    } else {
        FSUtils.debug.error("FSNameRegistrationResponse.parseURL" + "EncodedRequest: Provider ID is null ");
        throw new FSMsgException("missingElement", null);
    }
    if (request.getParameter("RelayState") != null) {
        retNameRegistrationResponse.relayState = request.getParameter("RelayState");
    }
    if (request.getParameter("InResponseTo") != null) {
        retNameRegistrationResponse.inResponseTo = request.getParameter("InResponseTo");
    }
    if (request.getParameter("Value") != null) {
        FSUtils.debug.message("Status : " + request.getParameter("Value"));
        StatusCode statusCode = new StatusCode(request.getParameter("Value"));
        retNameRegistrationResponse.status = new Status(statusCode);
    } else {
        FSUtils.debug.error("FSNameRegistrationResponse.parseURL" + "EncodedRequest: Status Value is  null ");
        throw new FSMsgException("missingElement", null);
    }
    FSUtils.debug.message("Returning registration response Object");
    return retNameRegistrationResponse;
}
Also used : Status(com.sun.identity.saml.protocol.Status) FSMsgException(com.sun.identity.federation.message.common.FSMsgException) ParseException(java.text.ParseException) StatusCode(com.sun.identity.saml.protocol.StatusCode)

Example 20 with Status

use of com.sun.identity.saml.protocol.Status in project OpenAM by OpenRock.

the class FSLogoutResponse method parseURLEncodedRequest.

/**
         * Returns <code>FSLogoutResponse</code> object. The
         * object is creating by parsing the <code>HttpServletRequest</code>
         * object.
         *
         * @param request the <code>HttpServletRequest</code> object.
         * @throws FSMsgException if there is an error creating this object.
         * @throws SAMLException if there is an error.
         */
public static FSLogoutResponse parseURLEncodedRequest(HttpServletRequest request) throws FSMsgException, SAMLException {
    FSLogoutResponse retLogoutResponse = new FSLogoutResponse();
    try {
        FSUtils.debug.message("checking minor version");
        retLogoutResponse.majorVersion = Integer.parseInt(request.getParameter(IFSConstants.MAJOR_VERSION));
        retLogoutResponse.minorVersion = Integer.parseInt(request.getParameter(IFSConstants.MINOR_VERSION));
    } catch (NumberFormatException ex) {
        throw new FSMsgException("invalidNumber", null);
    }
    String requestID = request.getParameter(IFSConstants.RESPONSE_ID);
    if (requestID != null) {
        retLogoutResponse.responseID = requestID;
    } else {
        String[] args = { IFSConstants.RESPONSE_ID };
        throw new FSMsgException("missingAttribute", args);
    }
    retLogoutResponse.inResponseTo = request.getParameter(IFSConstants.IN_RESPONSE_TO);
    String instantString = request.getParameter(IFSConstants.ISSUE_INSTANT);
    if (instantString == null || instantString.length() == 0) {
        String[] args = { IFSConstants.ISSUE_INSTANT };
        throw new FSMsgException("missingAttribute", args);
    }
    try {
        retLogoutResponse.issueInstant = DateUtils.stringToDate(instantString);
    } catch (ParseException e) {
        throw new FSMsgException("parseError", null);
    }
    FSUtils.debug.message(" get provider Id");
    String providerID = request.getParameter(IFSConstants.PROVIDER_ID);
    if (providerID != null) {
        retLogoutResponse.providerId = providerID;
        if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message("ProviderID : " + retLogoutResponse.providerId);
        }
    } else {
        if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message("ProviderID : " + retLogoutResponse.providerId);
        }
        throw new FSMsgException("missingElement", null);
    }
    String relayState = request.getParameter(IFSConstants.RELAY_STATE);
    if (relayState != null) {
        retLogoutResponse.relayState = relayState;
        if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message("RelayState:" + retLogoutResponse.relayState);
        }
    }
    String value = request.getParameter(IFSConstants.VALUE);
    if (value != null) {
        if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message("Status : " + value);
        }
        StatusCode statusCode = new StatusCode(value);
        retLogoutResponse.status = new Status(statusCode);
    } else {
        if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message("Status : " + value);
        }
        throw new FSMsgException("missingElement", null);
    }
    FSUtils.debug.message("Returning Logout response Object");
    return retLogoutResponse;
}
Also used : Status(com.sun.identity.saml.protocol.Status) FSMsgException(com.sun.identity.federation.message.common.FSMsgException) ParseException(java.text.ParseException) StatusCode(com.sun.identity.saml.protocol.StatusCode)

Aggregations

Status (com.sun.identity.saml.protocol.Status)21 SAMLException (com.sun.identity.saml.common.SAMLException)16 StatusCode (com.sun.identity.saml.protocol.StatusCode)16 FSException (com.sun.identity.federation.common.FSException)10 FSMsgException (com.sun.identity.federation.message.common.FSMsgException)10 SessionException (com.sun.identity.plugin.session.SessionException)8 IOException (java.io.IOException)8 IDFFMetaException (com.sun.identity.federation.meta.IDFFMetaException)6 SessionProvider (com.sun.identity.plugin.session.SessionProvider)5 ArrayList (java.util.ArrayList)5 List (java.util.List)5 Assertion (com.sun.identity.saml.assertion.Assertion)4 SAMLResponderException (com.sun.identity.saml.common.SAMLResponderException)4 ParseException (java.text.ParseException)4 FSAccountMgmtException (com.sun.identity.federation.accountmgmt.FSAccountMgmtException)3 FSRedirectException (com.sun.identity.federation.common.FSRedirectException)3 FSAssertion (com.sun.identity.federation.message.FSAssertion)3 FSAuthnResponse (com.sun.identity.federation.message.FSAuthnResponse)3 FSLogoutResponse (com.sun.identity.federation.message.FSLogoutResponse)3 AssertionArtifact (com.sun.identity.saml.protocol.AssertionArtifact)3