Search in sources :

Example 1 with Response

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

the class SAMLPOSTProfileServlet method doGet.

/**
     * Initiates <code>SAML</code> web browser POST profile.
     * This method takes in a TARGET in the request, creates a SAMLResponse,
     * then redirects user to the destination site.
     *
     * @param request <code>HttpServletRequest</code> instance
     * @param response <code>HttpServletResponse</code> instance
     * @throws ServletException if there is an error.
     * @throws IOException if there is an error.
     */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if ((request == null) || (response == null)) {
        String[] data = { SAMLUtils.bundle.getString("nullInputParameter") };
        LogUtils.error(java.util.logging.Level.INFO, LogUtils.NULL_PARAMETER, data);
        SAMLUtils.sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "nullInputParameter", SAMLUtils.bundle.getString("nullInputParameter"));
        return;
    }
    SAMLUtils.checkHTTPContentLength(request);
    // get Session
    Object token = getSession(request);
    if (token == null) {
        response.sendRedirect(SAMLUtils.getLoginRedirectURL(request));
        return;
    }
    // obtain TARGET
    String target = request.getParameter(SAMLConstants.POST_TARGET_PARAM);
    if (target == null || target.length() == 0) {
        String[] data = { SAMLUtils.bundle.getString("missingTargetSite") };
        LogUtils.error(java.util.logging.Level.INFO, LogUtils.MISSING_TARGET, data, token);
        SAMLUtils.sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, "missingTargetSite", SAMLUtils.bundle.getString("missingTargetSite"));
        return;
    }
    // Get the Destination site Entry
    // find the destSite POST URL, which is the Receipient
    SAMLServiceManager.SiteEntry destSite = getDestSite(target);
    String destSiteUrl = null;
    if ((destSite == null) || ((destSiteUrl = destSite.getPOSTUrl()) == null)) {
        String[] data = { SAMLUtils.bundle.getString("targetForbidden"), target };
        LogUtils.error(java.util.logging.Level.INFO, LogUtils.TARGET_FORBIDDEN, data, token);
        SAMLUtils.sendError(request, response, response.SC_BAD_REQUEST, "targetForbidden", SAMLUtils.bundle.getString("targetForbidden") + " " + target);
        return;
    }
    Response samlResponse = null;
    try {
        String version = destSite.getVersion();
        int majorVersion = SAMLConstants.PROTOCOL_MAJOR_VERSION;
        int minorVersion = SAMLConstants.PROTOCOL_MINOR_VERSION;
        if (version != null) {
            StringTokenizer st = new StringTokenizer(version, ".");
            if (st.countTokens() == 2) {
                majorVersion = Integer.parseInt(st.nextToken().trim());
                minorVersion = Integer.parseInt(st.nextToken().trim());
            }
        }
        // create assertion
        AssertionManager am = AssertionManager.getInstance();
        SessionProvider sessionProvider = SessionManager.getProvider();
        Assertion assertion = am.createSSOAssertion(sessionProvider.getSessionID(token), null, request, response, destSite.getSourceID(), target, majorVersion + "." + minorVersion);
        // create SAMLResponse
        StatusCode statusCode = new StatusCode(SAMLConstants.STATUS_CODE_SUCCESS);
        Status status = new Status(statusCode);
        List contents = new ArrayList();
        contents.add(assertion);
        samlResponse = new Response(null, status, destSiteUrl, contents);
        samlResponse.setMajorVersion(majorVersion);
        samlResponse.setMinorVersion(minorVersion);
    } catch (SessionException sse) {
        SAMLUtils.debug.error("SAMLPOSTProfileServlet.doGet: Exception " + "Couldn't get SessionProvider:", sse);
        SAMLUtils.sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "couldNotCreateResponse", sse.getMessage());
        return;
    } catch (NumberFormatException ne) {
        SAMLUtils.debug.error("SAMLPOSTProfileServlet.doGet: Exception " + "when creating Response: ", ne);
        SAMLUtils.sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "couldNotCreateResponse", ne.getMessage());
        return;
    } catch (SAMLException se) {
        SAMLUtils.debug.error("SAMLPOSTProfileServlet.doGet: Exception " + "when creating Response: ", se);
        SAMLUtils.sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "couldNotCreateResponse", se.getMessage());
        return;
    }
    // sign the samlResponse
    byte[] signedBytes = null;
    try {
        samlResponse.signXML();
        if (SAMLUtils.debug.messageEnabled()) {
            SAMLUtils.debug.message("SAMLPOSTProfileServlet.doGet: " + "signed samlResponse is" + samlResponse.toString(true, true, true));
        }
        signedBytes = SAMLUtils.getResponseBytes(samlResponse);
    } catch (Exception e) {
        SAMLUtils.debug.error("SAMLPOSTProfileServlet.doGet: Exception " + "when signing the response:", e);
        SAMLUtils.sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "errorSigningResponse", SAMLUtils.bundle.getString("errorSigningResponse"));
        return;
    }
    // base64 encode the signed samlResponse
    String encodedResponse = null;
    try {
        encodedResponse = Base64.encode(signedBytes, true).trim();
    } catch (Exception e) {
        SAMLUtils.debug.error("SAMLPOSTProfileServlet.doGet: Exception " + "when encoding the response:", e);
        SAMLUtils.sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "errorEncodeResponse", SAMLUtils.bundle.getString("errorEncodeResponse"));
        return;
    }
    if (LogUtils.isAccessLoggable(java.util.logging.Level.FINE)) {
        String[] data = { SAMLUtils.bundle.getString("redirectTo"), target, destSiteUrl, new String(signedBytes, "UTF-8") };
        LogUtils.access(java.util.logging.Level.FINE, LogUtils.REDIRECT_TO_URL, data, token);
    } else {
        String[] data = { SAMLUtils.bundle.getString("redirectTo"), target, destSiteUrl };
        LogUtils.access(java.util.logging.Level.INFO, LogUtils.REDIRECT_TO_URL, data, token);
    }
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("<HTML>");
    out.println("<BODY Onload=\"document.forms[0].submit()\">");
    out.println("<FORM METHOD=\"POST\" ACTION=\"" + destSiteUrl + "\">");
    out.println("<INPUT TYPE=\"HIDDEN\" NAME=\"" + SAMLConstants.POST_SAML_RESPONSE_PARAM + "\" ");
    out.println("VALUE=\"" + encodedResponse + "\">");
    out.println("<INPUT TYPE=\"HIDDEN\" NAME=\"" + SAMLConstants.POST_TARGET_PARAM + "\" VALUE=\"" + target + "\"> </FORM>");
    out.println("</BODY></HTML>");
    out.close();
}
Also used : Status(com.sun.identity.saml.protocol.Status) Assertion(com.sun.identity.saml.assertion.Assertion) ArrayList(java.util.ArrayList) SessionException(com.sun.identity.plugin.session.SessionException) StatusCode(com.sun.identity.saml.protocol.StatusCode) SAMLException(com.sun.identity.saml.common.SAMLException) ServletException(javax.servlet.ServletException) SessionException(com.sun.identity.plugin.session.SessionException) SAMLException(com.sun.identity.saml.common.SAMLException) IOException(java.io.IOException) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(com.sun.identity.saml.protocol.Response) StringTokenizer(java.util.StringTokenizer) AssertionManager(com.sun.identity.saml.AssertionManager) SAMLServiceManager(com.sun.identity.saml.common.SAMLServiceManager) ArrayList(java.util.ArrayList) List(java.util.List) SessionProvider(com.sun.identity.plugin.session.SessionProvider) PrintWriter(java.io.PrintWriter)

Example 2 with Response

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

the class SAMLPOSTProfileServlet method doPost.

/**
     * This method processes TARGET and SAMLResponse info from the request,
     * validates the response/assertion(s), then redirects user to the
     * TARGET resource if all are valid.
     *
     * @param request <code>HttpServletRequest</code> instance
     * @param response <code>HttpServletResponse</code> instance
     * @throws  ServletException if there is an error.
     * @throws  IOException if there is an error.
     */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html; charset=UTF-8");
    if ((request == null) || (response == null)) {
        String[] data = { SAMLUtils.bundle.getString("nullInputParameter") };
        LogUtils.error(java.util.logging.Level.INFO, LogUtils.NULL_PARAMETER, data);
        SAMLUtils.sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, "nullInputParameter", SAMLUtils.bundle.getString("nullInputParameter"));
        return;
    }
    SAMLUtils.checkHTTPContentLength(request);
    // obtain TARGET
    String target = request.getParameter(SAMLConstants.POST_TARGET_PARAM);
    if (target == null || target.length() == 0) {
        String[] data = { SAMLUtils.bundle.getString("missingTargetSite") };
        LogUtils.error(java.util.logging.Level.INFO, LogUtils.MISSING_TARGET, data);
        SAMLUtils.sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, "missingTargetSite", SAMLUtils.bundle.getString("missingTargetSite"));
        return;
    }
    // obtain SAMLResponse
    String samlResponse = request.getParameter(SAMLConstants.POST_SAML_RESPONSE_PARAM);
    if (samlResponse == null) {
        String[] data = { SAMLUtils.bundle.getString("missingSAMLResponse") };
        LogUtils.error(java.util.logging.Level.INFO, LogUtils.MISSING_RESPONSE, data);
        SAMLUtils.sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, "missingSAMLResponse", SAMLUtils.bundle.getString("missingSAMLResponse"));
        return;
    }
    // decode the Response
    byte[] raw = null;
    try {
        raw = Base64.decode(samlResponse);
    } catch (Exception e) {
        SAMLUtils.debug.error("SAMLPOSTProfileServlet.doPost: Exception " + "when decoding SAMLResponse:", e);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "errorDecodeResponse", SAMLUtils.bundle.getString("errorDecodeResponse"));
        return;
    }
    // Get Response back
    Response sResponse = SAMLUtils.getResponse(raw);
    if (sResponse == null) {
        String[] data = { SAMLUtils.bundle.getString("errorObtainResponse") };
        LogUtils.error(java.util.logging.Level.INFO, LogUtils.RESPONSE_MESSAGE_ERROR, data);
        SAMLUtils.sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, "errorObtainResponse", SAMLUtils.bundle.getString("errorObtainResponse"));
        return;
    }
    if (SAMLUtils.debug.messageEnabled()) {
        SAMLUtils.debug.message("SAMLPOSTProfileServlet.doPost: Received " + sResponse.toString());
    }
    // verify that Response is correct
    StringBuffer requestUrl = request.getRequestURL();
    if (SAMLUtils.debug.messageEnabled()) {
        SAMLUtils.debug.message("SAMLPOSTProfileServlet.doPost: " + "requestUrl=" + requestUrl);
    }
    boolean valid = SAMLUtils.verifyResponse(sResponse, requestUrl.toString(), request);
    if (!valid) {
        String[] data = { SAMLUtils.bundle.getString("invalidResponse") };
        LogUtils.error(java.util.logging.Level.INFO, LogUtils.INVALID_RESPONSE, data);
        SAMLUtils.sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, "invalidResponse", SAMLUtils.bundle.getString("invalidResponse"));
        return;
    }
    Map attrMap = null;
    List assertions = null;
    javax.security.auth.Subject authSubject = null;
    try {
        Map sessionAttr = SAMLUtils.processResponse(sResponse, target);
        Object token = SAMLUtils.generateSession(request, response, sessionAttr);
    } catch (Exception ex) {
        SAMLUtils.debug.error("generateSession: ", ex);
        String[] data = { SAMLUtils.bundle.getString("failedCreateSSOToken") };
        LogUtils.error(java.util.logging.Level.INFO, LogUtils.FAILED_TO_CREATE_SSO_TOKEN, data);
        SAMLUtils.sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "failedCreateSSOToken", ex.getMessage());
        ;
        return;
    }
    if (LogUtils.isAccessLoggable(java.util.logging.Level.FINE)) {
        String[] data = { SAMLUtils.bundle.getString("accessGranted"), new String(raw, "UTF-8") };
        LogUtils.access(java.util.logging.Level.FINE, LogUtils.ACCESS_GRANTED, data);
    } else {
        String[] data = { SAMLUtils.bundle.getString("accessGranted") };
        LogUtils.access(java.util.logging.Level.INFO, LogUtils.ACCESS_GRANTED, data);
    }
    if (SAMLUtils.postYN(target)) {
        if (SAMLUtils.debug.messageEnabled()) {
            SAMLUtils.debug.message("POST to target:" + target);
        }
        SAMLUtils.postToTarget(response, response.getWriter(), assertions, target, attrMap);
    } else {
        response.setHeader("Location", target);
        response.sendRedirect(target);
    }
}
Also used : ServletException(javax.servlet.ServletException) SessionException(com.sun.identity.plugin.session.SessionException) SAMLException(com.sun.identity.saml.common.SAMLException) IOException(java.io.IOException) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(com.sun.identity.saml.protocol.Response) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map)

Example 3 with Response

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

the class SAMLSOAPReceiver method validateStatements.

/**
     * This method validates the assertion to see that the statements it 
     * contains are what is present in the RespondWith element of the
     * corresponsing Request.  If valid adds the passed assertion in the
     * passed contents, which is a List, at the specified index.
     */
private Response validateStatements(Assertion assertion, List respondWith, List contents, int index, String respID, String inResponseTo, String recipient) {
    String message = null;
    Set statements = assertion.getStatement();
    int length = statements.size();
    Response retResponse = null;
    Status status = null;
    if ((statements.isEmpty()) || (length == 0)) {
        SAMLUtils.debug.error("SOAPReceiver: Assertion found does not have" + " any statements in it");
        message = SAMLUtils.bundle.getString("missingStatement");
        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);
            String[] data = { SAMLUtils.bundle.getString("cannotBuildResponse") };
            LogUtils.error(java.util.logging.Level.INFO, LogUtils.BUILD_RESPONSE_ERROR, data);
        }
        return retResponse;
    } else {
        // statements not empty
        // would be true if there is any
        boolean mismatchError = false;
        // mismatch with RespondWith contents.
        if (respondWith.size() == 0) {
            contents.add(index, assertion);
        } else {
            mismatchError = !checkAgainstRespondWith(respondWith, statements);
            if (!mismatchError) {
                contents.add(index, assertion);
            }
        }
        // end of else respondWith size > 0
        if (mismatchError) {
            SAMLUtils.debug.error("SOAPReceiver: Assertion does not " + " meet respondWith criteria in the received Request");
            message = SAMLUtils.bundle.getString("mismatchRespondWith");
            try {
                //contents = null;
                status = new Status(new StatusCode("samlp:Success"), message, null);
                return new Response(respID, inResponseTo, status, recipient, contents);
            } 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);
            }
        }
    }
    // reached here, so there was no error in validation
    return null;
}
Also used : Response(com.sun.identity.saml.protocol.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) Status(com.sun.identity.saml.protocol.Status) Set(java.util.Set) HashSet(java.util.HashSet) StatusCode(com.sun.identity.saml.protocol.StatusCode) SAMLException(com.sun.identity.saml.common.SAMLException)

Example 4 with Response

use of com.sun.identity.saml.protocol.Response 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 5 with Response

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

the class SAMLSOAPReceiver method onMessage.

/**
     * Retrieves the SAML <code>Request</code> from the
     * <code>SOAPMessage</code>, calls internal methods to parse the 
     * <code>Request</code> generate SAML <code>Response</code> and send it 
     * back to the requestor again using SOAP binding over HTTP.
     */
private SOAPMessage onMessage(HttpServletRequest req, HttpServletResponse servletResp, SOAPMessage message, Set partnerSourceID) {
    // first check if there was any soap error during verifyHost()
    try {
        if (SAMLUtils.debug.messageEnabled()) {
            SAMLUtils.debug.message("OnMessage called in receiving " + "servlet");
        }
        // check the SOAP message for any SOAP
        // related errros before passing control to SAML processor
        ByteArrayOutputStream bop = new ByteArrayOutputStream();
        message.writeTo(bop);
        ByteArrayInputStream bin = new ByteArrayInputStream(bop.toByteArray());
        Document doc = XMLUtils.toDOMDocument(bin, SAMLUtils.debug);
        Element root = doc.getDocumentElement();
        String rootName = doc.getDocumentElement().getLocalName();
        if ((rootName == null) || (rootName.length() == 0)) {
            SAMLUtils.debug.error("Local name of the SOAPElement in  the" + " SOAPMessage passed seems to be missing");
            return FormSOAPError(servletResp, "Client", "nullInput", "LocalNameMissing");
        }
        if (!(rootName.equals("Envelope")) || (!(root.getNamespaceURI().equals(sc.SOAP_URI)))) {
            SAMLUtils.debug.error("SOAPReceiver: Could not parse " + "SOAPMessage, either root element is not Envelope" + " or invalid name space or prefix");
            return FormSOAPError(servletResp, "Client", "invalidElement", "envelopeInvalid");
        }
        NodeList nl = doc.getChildNodes();
        int length = nl.getLength();
        if (length <= 0) {
            SAMLUtils.debug.error("SOAPReceiver: Message does not have " + "body");
            return FormSOAPError(servletResp, "Client", "missingBody", null);
        }
        Node child = null;
        for (int i = 0; i < length; i++) {
            child = (Node) nl.item(i);
            if (child.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }
            String childName = child.getLocalName();
            if (childName.equals("Body")) {
                // found the message body
                break;
            }
        }
        Element body = (Element) child;
        Response resp = extractProcessRequest(req, body, partnerSourceID);
        if (((Boolean) SAMLServiceManager.getAttribute(SAMLConstants.SIGN_RESPONSE)).booleanValue()) {
            resp.signXML();
        }
        return FormMessageResponse(servletResp, resp);
    } catch (Exception e) {
        SAMLUtils.debug.error("Error in processing Request", e);
        return FormSOAPError(servletResp, "Server", "cannotProcessRequest", null);
    }
}
Also used : Response(com.sun.identity.saml.protocol.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) SOAPElement(javax.xml.soap.SOAPElement) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(org.w3c.dom.Document) 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)

Aggregations

SAMLException (com.sun.identity.saml.common.SAMLException)5 Response (com.sun.identity.saml.protocol.Response)5 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 ServletException (javax.servlet.ServletException)4 Status (com.sun.identity.saml.protocol.Status)3 StatusCode (com.sun.identity.saml.protocol.StatusCode)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 SessionException (com.sun.identity.plugin.session.SessionException)2 AssertionManager (com.sun.identity.saml.AssertionManager)2 Assertion (com.sun.identity.saml.assertion.Assertion)2 SAMLRequestVersionTooHighException (com.sun.identity.saml.common.SAMLRequestVersionTooHighException)2 SAMLRequestVersionTooLowException (com.sun.identity.saml.common.SAMLRequestVersionTooLowException)2 SAMLRequesterException (com.sun.identity.saml.common.SAMLRequesterException)2 IOException (java.io.IOException)2 StringTokenizer (java.util.StringTokenizer)2 SOAPElement (javax.xml.soap.SOAPElement)2 SOAPException (javax.xml.soap.SOAPException)2 Element (org.w3c.dom.Element)2 Node (org.w3c.dom.Node)2