Search in sources :

Example 1 with Response

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

the class XACMLAuthzDecisionQueryHandler method handleQuery.

/**
     * Processes an XACMLAuthzDecisionQuery and retruns a SAML2 Response.
     *
     * @param pdpEntityId EntityID of PDP
     * @param pepEntityId EntityID of PEP
     * @param samlpRequest SAML2 Request, an XAMLAuthzDecisionQuery
     * @param soapMessage SOAPMessage that carried the SAML2 Request
     * @return SAML2 Response with an XAMLAuthzDecisionStatement
     * @exception SAML2Exception if the query can not be handled
     */
public com.sun.identity.saml2.protocol.Response handleQuery(String pdpEntityId, String pepEntityId, RequestAbstract samlpRequest, SOAPMessage soapMessage) throws SAML2Exception {
    //TODO: logging, i18n
    //TODO: long term, allow different mapper impls for  different
    //combination of pdp, pep
    SubjectMapper subjectMapper = new FMSubjectMapper();
    subjectMapper.initialize(pdpEntityId, pepEntityId, null);
    ResourceMapper resourceMapper = new FMResourceMapper();
    resourceMapper.initialize(pdpEntityId, pepEntityId, null);
    ActionMapper actionMapper = new FMActionMapper();
    actionMapper.initialize(pdpEntityId, pepEntityId, null);
    EnvironmentMapper environmentMapper = new FMEnvironmentMapper();
    environmentMapper.initialize(pdpEntityId, pepEntityId, null);
    ResultMapper resultMapper = new FMResultMapper();
    resultMapper.initialize(pdpEntityId, pepEntityId, null);
    boolean evaluationFailed = false;
    String statusCodeValue = null;
    if (XACMLSDKUtils.debug.messageEnabled()) {
        XACMLSDKUtils.debug.message("XACMLAuthzDecisionQueryHandler.handleQuery(), entering" + ":pdpEntityId=" + pdpEntityId + ":pepEntityId=" + pepEntityId + ":samlpRequest=\n" + samlpRequest.toXMLString(true, true) + ":soapMessage=\n" + soapMessage);
    }
    Request xacmlRequest = ((XACMLAuthzDecisionQuery) samlpRequest).getRequest();
    boolean returnContext = ((XACMLAuthzDecisionQuery) samlpRequest).getReturnContext();
    SSOToken ssoToken = null;
    String resourceName = null;
    String serviceName = null;
    String actionName = null;
    Map environment = null;
    boolean booleanDecision = false;
    try {
        //get native sso token
        ssoToken = (SSOToken) subjectMapper.mapToNativeSubject(xacmlRequest.getSubjects());
        if (ssoToken == null) {
            //TODO: log message and fill missing attribute details 
            statusCodeValue = XACMLConstants.STATUS_CODE_MISSING_ATTRIBUTE;
            evaluationFailed = true;
        } else {
            if (XACMLSDKUtils.debug.messageEnabled()) {
                XACMLSDKUtils.debug.message("XACMLAuthzDecisionQueryHandler.handleQuery()," + "created ssoToken");
            }
        }
        if (ssoToken != null) {
            //get native service name, resource name 
            List resources = xacmlRequest.getResources();
            Resource resource = null;
            if (!resources.isEmpty()) {
                //We deal with only one resource for now
                resource = (Resource) resources.get(0);
            }
            if (resource != null) {
                String[] resourceService = resourceMapper.mapToNativeResource(resource);
                if (resourceService != null) {
                    if (resourceService.length > 0) {
                        resourceName = resourceService[0];
                    }
                    if (resourceService.length > 1) {
                        serviceName = resourceService[1];
                    }
                }
            }
            if (resourceName == null) {
                //TODO: log message and fill missing attribute details 
                statusCodeValue = XACMLConstants.STATUS_CODE_MISSING_ATTRIBUTE;
                evaluationFailed = true;
            }
            if (serviceName == null) {
                //TODO: log message and fill missing attribute details
                throw new SAML2Exception(XACMLSDKUtils.xacmlResourceBundle.getString("missing_attribute"));
            }
        }
        if (serviceName != null) {
            //get native action name
            if (serviceName != null) {
                actionName = actionMapper.mapToNativeAction(xacmlRequest.getAction(), serviceName);
            }
            if (actionName == null) {
                //TODO: log message and fill missing attribute details
                statusCodeValue = XACMLConstants.STATUS_CODE_MISSING_ATTRIBUTE;
                evaluationFailed = true;
            }
        }
    //get environment map
    /*
            environment = environmentMapper.mapToNativeEnvironment(
                    xacmlRequest.getEnvironment(), 
                    xacmlRequest.getSubjects());
            */
    } catch (XACMLException xe) {
        statusCodeValue = XACMLConstants.STATUS_CODE_MISSING_ATTRIBUTE;
        evaluationFailed = true;
        if (XACMLSDKUtils.debug.warningEnabled()) {
            XACMLSDKUtils.debug.warning("XACMLAuthzDecisionQueryHandler.handleQuery()," + "caught exception", xe);
        }
    }
    //get native policy deicison using native policy evaluator
    if (!evaluationFailed) {
        try {
            PolicyEvaluator pe = new PolicyEvaluator(serviceName);
            booleanDecision = pe.isAllowed(ssoToken, resourceName, actionName, environment);
        } catch (SSOException ssoe) {
            if (XACMLSDKUtils.debug.warningEnabled()) {
                XACMLSDKUtils.debug.warning("XACMLAuthzDecisionQueryHandler.handleQuery()," + "caught exception", ssoe);
            }
            evaluationFailed = true;
        } catch (PolicyException pe) {
            if (XACMLSDKUtils.debug.warningEnabled()) {
                XACMLSDKUtils.debug.warning("XACMLAuthzDecisionQueryHandler.handleQuery()," + "caught exception", pe);
            }
            evaluationFailed = true;
        }
    }
    //decision: Indeterminate, Deny, Permit, NotApplicable
    //status code: missing_attribute, syntax_error, processing_error, ok
    Decision decision = ContextFactory.getInstance().createDecision();
    Status status = ContextFactory.getInstance().createStatus();
    StatusCode code = ContextFactory.getInstance().createStatusCode();
    StatusMessage message = ContextFactory.getInstance().createStatusMessage();
    StatusDetail detail = ContextFactory.getInstance().createStatusDetail();
    detail.getElement().insertBefore(detail.getElement().cloneNode(true), null);
    if (evaluationFailed) {
        decision.setValue(XACMLConstants.INDETERMINATE);
        if (statusCodeValue == null) {
            statusCodeValue = XACMLConstants.STATUS_CODE_PROCESSING_ERROR;
        }
        code.setValue(statusCodeValue);
        //TODO: i18n
        message.setValue("processing_error");
    } else if (booleanDecision) {
        decision.setValue(XACMLConstants.PERMIT);
        code.setValue(XACMLConstants.STATUS_CODE_OK);
        //TODO: i18n
        message.setValue("ok");
    } else {
        decision.setValue(XACMLConstants.DENY);
        code.setValue(XACMLConstants.STATUS_CODE_OK);
        //TODO: i18n
        message.setValue("ok");
    }
    Result result = ContextFactory.getInstance().createResult();
    String resourceId = resourceName;
    List resources = xacmlRequest.getResources();
    Resource resource = null;
    if (!resources.isEmpty()) {
        //We deal with only one resource for now
        resource = (Resource) resources.get(0);
        if (resource != null) {
            List attributes = resource.getAttributes();
            if (attributes != null) {
                for (int count = 0; count < attributes.size(); count++) {
                    Attribute attr = (Attribute) attributes.get(count);
                    if (attr != null) {
                        URI tmpURI = attr.getAttributeId();
                        if (tmpURI.toString().equals(XACMLConstants.RESOURCE_ID)) {
                            Element element = (Element) attr.getAttributeValues().get(0);
                            resourceId = XMLUtils.getElementValue(element);
                            break;
                        }
                    }
                }
            }
        }
    }
    result.setResourceId(resourceId);
    result.setDecision(decision);
    status.setStatusCode(code);
    status.setStatusMessage(message);
    status.setStatusDetail(detail);
    result.setStatus(status);
    Response response = ContextFactory.getInstance().createResponse();
    response.addResult(result);
    XACMLAuthzDecisionStatement statement = ContextFactory.getInstance().createXACMLAuthzDecisionStatement();
    statement.setResponse(response);
    if (returnContext) {
        statement.setRequest(xacmlRequest);
    }
    com.sun.identity.saml2.protocol.Response samlpResponse = createSamlpResponse(statement, status.getStatusCode().getValue());
    if (XACMLSDKUtils.debug.messageEnabled()) {
        XACMLSDKUtils.debug.message("XACMLAuthzDecisionQueryHandler.handleQuery(), returning" + ":samlResponse=\n" + samlpResponse.toXMLString(true, true));
    }
    return samlpResponse;
}
Also used : SSOToken(com.iplanet.sso.SSOToken) Attribute(com.sun.identity.xacml.context.Attribute) Element(org.w3c.dom.Element) SSOException(com.iplanet.sso.SSOException) StatusCode(com.sun.identity.xacml.context.StatusCode) URI(java.net.URI) Result(com.sun.identity.xacml.context.Result) ResourceResult(com.sun.identity.policy.ResourceResult) ActionMapper(com.sun.identity.xacml.spi.ActionMapper) XACMLAuthzDecisionStatement(com.sun.identity.xacml.saml2.XACMLAuthzDecisionStatement) PolicyEvaluator(com.sun.identity.policy.PolicyEvaluator) SubjectMapper(com.sun.identity.xacml.spi.SubjectMapper) PolicyException(com.sun.identity.policy.PolicyException) ResourceMapper(com.sun.identity.xacml.spi.ResourceMapper) ArrayList(java.util.ArrayList) List(java.util.List) Status(com.sun.identity.xacml.context.Status) Request(com.sun.identity.xacml.context.Request) Resource(com.sun.identity.xacml.context.Resource) EnvironmentMapper(com.sun.identity.xacml.spi.EnvironmentMapper) Decision(com.sun.identity.xacml.context.Decision) XACMLException(com.sun.identity.xacml.common.XACMLException) StatusMessage(com.sun.identity.xacml.context.StatusMessage) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Response(com.sun.identity.xacml.context.Response) ResultMapper(com.sun.identity.xacml.spi.ResultMapper) StatusDetail(com.sun.identity.xacml.context.StatusDetail) XACMLAuthzDecisionQuery(com.sun.identity.xacml.saml2.XACMLAuthzDecisionQuery) Map(java.util.Map)

Example 2 with Response

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

the class DefaultFedletAdapter method onFedletSLOSuccessOrFailure.

private void onFedletSLOSuccessOrFailure(HttpServletRequest request, HttpServletResponse response, LogoutRequest logoutReq, LogoutResponse logoutRes, String hostedEntityID, String idpEntityID, String binding, boolean isSuccess) throws SAML2Exception {
    String method = "DefaultFedletAdapter:onFedletSLOSuccessOrFailure:";
    try {
        if (logoutUrl == null) {
            BaseConfigType spConfig = SAML2Utils.getSAML2MetaManager().getSPSSOConfig("/", hostedEntityID);
            List appLogoutURL = (List) SAML2MetaUtils.getAttributes(spConfig).get(SAML2Constants.APP_LOGOUT_URL);
            if ((appLogoutURL != null) && !appLogoutURL.isEmpty()) {
                logoutUrl = (String) appLogoutURL.get(0);
            }
        }
        if (logoutUrl == null) {
            String deployuri = request.getRequestURI();
            int slashLoc = deployuri.indexOf("/", 1);
            if (slashLoc != -1) {
                deployuri = deployuri.substring(0, slashLoc);
            }
            if (deployuri != null) {
                String url = request.getRequestURL().toString();
                int loc = url.indexOf(deployuri + "/");
                if (loc != -1) {
                    logoutUrl = url.substring(0, loc + deployuri.length()) + "/logout";
                }
            }
        }
        if (logoutUrl == null) {
            return;
        }
        URL url = new URL(logoutUrl);
        HttpURLConnection conn = HttpURLConnectionManager.getConnection(url);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setFollowRedirects(false);
        conn.setInstanceFollowRedirects(false);
        // replay cookies
        String strCookies = SAML2Utils.getCookiesString(request);
        if (strCookies != null) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(method + "Sending cookies : " + strCookies);
            }
            conn.setRequestProperty("Cookie", strCookies);
        }
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("IDP", URLEncDec.encode(idpEntityID));
        conn.setRequestProperty("SP", URLEncDec.encode(hostedEntityID));
        if (logoutReq != null) {
            NameID nameID = logoutReq.getNameID();
            if (nameID != null) {
                conn.setRequestProperty("NameIDValue", URLEncDec.encode(nameID.getValue()));
            }
            List siList = logoutReq.getSessionIndex();
            if ((siList != null) && (!siList.isEmpty())) {
                conn.setRequestProperty("SessionIndex", URLEncDec.encode((String) siList.get(0)));
            }
        }
        conn.setRequestProperty("Binding", binding);
        if (isSuccess) {
            conn.setRequestProperty("SLOStatus", "Success");
        } else {
            conn.setRequestProperty("SLOStatus", "Failure");
        }
        OutputStream outputStream = conn.getOutputStream();
        // Write the request to the HTTP server.
        outputStream.write("".getBytes());
        outputStream.flush();
        outputStream.close();
        // Check response code
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(method + "Response code OK");
            }
        } else {
            SAML2Utils.debug.error(method + "Response code NOT OK: " + conn.getResponseCode());
        }
    } catch (Exception e) {
    }
    return;
}
Also used : BaseConfigType(com.sun.identity.saml2.jaxb.entityconfig.BaseConfigType) HttpURLConnection(java.net.HttpURLConnection) NameID(com.sun.identity.saml2.assertion.NameID) OutputStream(java.io.OutputStream) List(java.util.List) URL(java.net.URL) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception)

Example 3 with Response

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

the class DefaultFedletAdapter method doFedletSLO.

/**
     * Invokes after Fedlet receives SLO request from IDP. It does the work
     * of logout the user.
     * @param request servlet request
     * @param response servlet response
     * @param hostedEntityID entity ID for the fedlet
     * @param idpEntityID entity id for the IDP to which the request is
     *          received from.
     * @param siList List of SessionIndex whose session to be logged out
     * @param nameIDValue nameID value whose session to be logged out
     * @param binding Single Logout binding used,
     *      one of following values:
     *          <code>SAML2Constants.SOAP</code>,
     *          <code>SAML2Constants.HTTP_POST</code>,
     *          <code>SAML2Constants.HTTP_REDIRECT</code>
     * @return <code>true</code> if user is logged out successfully;
     *          <code>false</code> otherwise.
     * @exception SAML2Exception if user want to fail the process.
     */
public boolean doFedletSLO(HttpServletRequest request, HttpServletResponse response, LogoutRequest logoutReq, String hostedEntityID, String idpEntityID, List siList, String nameIDValue, String binding) throws SAML2Exception {
    boolean status = true;
    String method = "DefaultFedletAdapter:doFedletSLO:";
    try {
        if (logoutUrl == null) {
            BaseConfigType spConfig = SAML2Utils.getSAML2MetaManager().getSPSSOConfig("/", hostedEntityID);
            List appLogoutURL = (List) SAML2MetaUtils.getAttributes(spConfig).get(SAML2Constants.APP_LOGOUT_URL);
            if ((appLogoutURL != null) && !appLogoutURL.isEmpty()) {
                logoutUrl = (String) appLogoutURL.get(0);
            }
        }
        if (logoutUrl == null) {
            String deployuri = request.getRequestURI();
            int slashLoc = deployuri.indexOf("/", 1);
            if (slashLoc != -1) {
                deployuri = deployuri.substring(0, slashLoc);
            }
            if (deployuri != null) {
                String url = request.getRequestURL().toString();
                int loc = url.indexOf(deployuri + "/");
                if (loc != -1) {
                    logoutUrl = url.substring(0, loc + deployuri.length()) + "/logout";
                }
            }
        }
        if (logoutUrl == null) {
            return status;
        }
        URL url = new URL(logoutUrl);
        HttpURLConnection conn = HttpURLConnectionManager.getConnection(url);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setFollowRedirects(false);
        conn.setInstanceFollowRedirects(false);
        // replay cookies
        String strCookies = SAML2Utils.getCookiesString(request);
        if (strCookies != null) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(method + "Sending cookies : " + strCookies);
            }
            conn.setRequestProperty("Cookie", strCookies);
        }
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("IDP", URLEncDec.encode(idpEntityID));
        conn.setRequestProperty("SP", URLEncDec.encode(hostedEntityID));
        conn.setRequestProperty("NameIDValue", URLEncDec.encode(nameIDValue));
        if (siList != null && !siList.isEmpty()) {
            Iterator iter = siList.iterator();
            StringBuffer siValue = new StringBuffer();
            siValue.append((String) iter.next());
            while (iter.hasNext()) {
                siValue.append(",").append((String) iter.next());
            }
            conn.setRequestProperty("SessionIndex", URLEncDec.encode(siValue.toString()));
        }
        conn.setRequestProperty("Binding", binding);
        OutputStream outputStream = conn.getOutputStream();
        // Write the request to the HTTP server.
        outputStream.write("".getBytes());
        outputStream.flush();
        outputStream.close();
        // Check response code
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(method + "Response code OK");
            }
            status = true;
        } else {
            SAML2Utils.debug.error(method + "Response code NOT OK: " + conn.getResponseCode());
            status = false;
        }
    } catch (Exception e) {
        status = false;
    }
    return status;
}
Also used : BaseConfigType(com.sun.identity.saml2.jaxb.entityconfig.BaseConfigType) HttpURLConnection(java.net.HttpURLConnection) OutputStream(java.io.OutputStream) Iterator(java.util.Iterator) List(java.util.List) URL(java.net.URL) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception)

Example 4 with Response

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

the class UtilProxySAMLAuthenticator method authenticate.

@Override
public void authenticate() throws FederatedSSOException, IOException {
    final String classMethod = "UtilProxySAMLAuthenticator.authenticate: ";
    SPSSODescriptorElement spSSODescriptor = null;
    String preferredIDP;
    // There is no reqID, this is the first time that we pass here.
    String binding = SAML2Constants.HTTP_REDIRECT;
    if (request.getMethod().equals("POST")) {
        binding = SAML2Constants.HTTP_POST;
    }
    data.setAuthnRequest(getAuthnRequest(request, isFromECP, binding));
    if (data.getAuthnRequest() == null) {
        throw new ClientFaultException(data.getIdpAdapter(), INVALID_SAML_REQUEST);
    }
    data.getEventAuditor().setRequestId(data.getRequestID());
    data.setSpEntityID(data.getAuthnRequest().getIssuer().getValue());
    try {
        logAccess(isFromECP ? LogUtil.RECEIVED_AUTHN_REQUEST_ECP : LogUtil.RECEIVED_AUTHN_REQUEST, Level.INFO, data.getSpEntityID(), data.getIdpMetaAlias(), data.getAuthnRequest().toXMLString());
    } catch (SAML2Exception saml2ex) {
        SAML2Utils.debug.error(classMethod, saml2ex);
        throw new ClientFaultException(data.getIdpAdapter(), INVALID_SAML_REQUEST, saml2ex.getMessage());
    }
    if (!SAML2Utils.isSourceSiteValid(data.getAuthnRequest().getIssuer(), data.getRealm(), data.getIdpEntityID())) {
        SAML2Utils.debug.warning("{} Issuer in Request is not valid.", classMethod);
        throw new ClientFaultException(data.getIdpAdapter(), INVALID_SAML_REQUEST);
    }
    // verify the signature of the query string if applicable
    IDPSSODescriptorElement idpSSODescriptor;
    try {
        idpSSODescriptor = IDPSSOUtil.metaManager.getIDPSSODescriptor(data.getRealm(), data.getIdpEntityID());
    } catch (SAML2MetaException sme) {
        SAML2Utils.debug.error(classMethod + "Unable to get IDP SSO Descriptor from meta.");
        throw new ServerFaultException(data.getIdpAdapter(), METADATA_ERROR);
    }
    try {
        spSSODescriptor = IDPSSOUtil.metaManager.getSPSSODescriptor(data.getRealm(), data.getSpEntityID());
    } catch (SAML2MetaException sme) {
        SAML2Utils.debug.error(classMethod + "Unable to get SP SSO Descriptor from meta.");
        SAML2Utils.debug.error(classMethod, sme);
    }
    if (isFromECP || idpSSODescriptor.isWantAuthnRequestsSigned() || (spSSODescriptor != null && spSSODescriptor.isAuthnRequestsSigned())) {
        // need to verify the query string containing authnRequest
        if (StringUtils.isBlank(data.getSpEntityID())) {
            throw new ClientFaultException(data.getIdpAdapter(), INVALID_SAML_REQUEST);
        }
        if (spSSODescriptor == null) {
            SAML2Utils.debug.error(classMethod + "Unable to get SP SSO Descriptor from meta.");
            throw new ServerFaultException(data.getIdpAdapter(), METADATA_ERROR);
        }
        Set<X509Certificate> certificates = KeyUtil.getVerificationCerts(spSSODescriptor, data.getSpEntityID(), SAML2Constants.SP_ROLE);
        try {
            boolean isSignatureOK;
            if (isFromECP) {
                isSignatureOK = data.getAuthnRequest().isSignatureValid(certificates);
            } else {
                if ("POST".equals(request.getMethod())) {
                    isSignatureOK = data.getAuthnRequest().isSignatureValid(certificates);
                } else {
                    isSignatureOK = QuerySignatureUtil.verify(request.getQueryString(), certificates);
                }
            }
            if (!isSignatureOK) {
                SAML2Utils.debug.error(classMethod + "authn request verification failed.");
                throw new ClientFaultException(data.getIdpAdapter(), "invalidSignInRequest");
            }
            // In ECP profile, sp doesn't know idp.
            if (!isFromECP) {
                // verify Destination
                List ssoServiceList = idpSSODescriptor.getSingleSignOnService();
                String ssoURL = SPSSOFederate.getSSOURL(ssoServiceList, binding);
                if (!SAML2Utils.verifyDestination(data.getAuthnRequest().getDestination(), ssoURL)) {
                    SAML2Utils.debug.error(classMethod + "authn request destination verification failed.");
                    throw new ClientFaultException(data.getIdpAdapter(), "invalidDestination");
                }
            }
        } catch (SAML2Exception se) {
            SAML2Utils.debug.error(classMethod + "authn request verification failed.", se);
            throw new ClientFaultException(data.getIdpAdapter(), "invalidSignInRequest");
        }
        SAML2Utils.debug.message("{} authn request signature verification is successful.", classMethod);
    }
    SAML2Utils.debug.message("{} request id= {}", classMethod, data.getRequestID());
    if (data.getRequestID() == null) {
        SAML2Utils.debug.error(classMethod + "Request id is null");
        throw new ClientFaultException(data.getIdpAdapter(), "InvalidSAMLRequestID");
    }
    if (isFromECP) {
        try {
            IDPECPSessionMapper idpECPSessonMapper = IDPSSOUtil.getIDPECPSessionMapper(data.getRealm(), data.getIdpEntityID());
            data.setSession(idpECPSessonMapper.getSession(request, response));
        } catch (SAML2Exception se) {
            SAML2Utils.debug.message("Unable to retrieve user session.", classMethod);
        }
    } else {
        // get the user sso session from the request
        try {
            data.setSession(SessionManager.getProvider().getSession(request));
        } catch (SessionException se) {
            SAML2Utils.debug.message("{} Unable to retrieve user session.", classMethod);
        }
    }
    if (null != data.getSession()) {
        data.getEventAuditor().setAuthTokenId(data.getSession());
    }
    // will not trigger this adapter call
    if (preSingleSignOn(request, response, data)) {
        return;
    }
    // End of adapter invocation
    IDPAuthnContextMapper idpAuthnContextMapper = null;
    try {
        idpAuthnContextMapper = IDPSSOUtil.getIDPAuthnContextMapper(data.getRealm(), data.getIdpEntityID());
    } catch (SAML2Exception sme) {
        SAML2Utils.debug.error(classMethod, sme);
    }
    if (idpAuthnContextMapper == null) {
        SAML2Utils.debug.error(classMethod + "Unable to get IDPAuthnContextMapper from meta.");
        throw new ServerFaultException(data.getIdpAdapter(), METADATA_ERROR);
    }
    IDPAuthnContextInfo idpAuthnContextInfo = null;
    try {
        idpAuthnContextInfo = idpAuthnContextMapper.getIDPAuthnContextInfo(data.getAuthnRequest(), data.getIdpEntityID(), data.getRealm());
    } catch (SAML2Exception sme) {
        SAML2Utils.debug.error(classMethod, sme);
    }
    if (idpAuthnContextInfo == null) {
        SAML2Utils.debug.message("{} Unable to find valid AuthnContext. Sending error Response.", classMethod);
        try {
            Response res = SAML2Utils.getErrorResponse(data.getAuthnRequest(), SAML2Constants.REQUESTER, SAML2Constants.NO_AUTHN_CONTEXT, null, data.getIdpEntityID());
            StringBuffer returnedBinding = new StringBuffer();
            String acsURL = IDPSSOUtil.getACSurl(data.getSpEntityID(), data.getRealm(), data.getAuthnRequest(), request, returnedBinding);
            String acsBinding = returnedBinding.toString();
            IDPSSOUtil.sendResponse(request, response, out, acsBinding, data.getSpEntityID(), data.getIdpEntityID(), data.getIdpMetaAlias(), data.getRealm(), data.getRelayState(), acsURL, res, data.getSession());
        } catch (SAML2Exception sme) {
            SAML2Utils.debug.error(classMethod, sme);
            throw new ServerFaultException(data.getIdpAdapter(), METADATA_ERROR);
        }
        return;
    }
    // get the relay state query parameter from the request
    data.setRelayState(request.getParameter(SAML2Constants.RELAY_STATE));
    data.setMatchingAuthnContext(idpAuthnContextInfo.getAuthnContext());
    if (data.getSession() == null) {
        // the user has not logged in yet, redirect to auth
        redirectToAuth(spSSODescriptor, binding, idpAuthnContextInfo, data);
    } else {
        SAML2Utils.debug.message("{} There is an existing session", classMethod);
        // Let's verify that the realm is the same for the user and the IdP
        boolean isValidSessionInRealm = IDPSSOUtil.isValidSessionInRealm(data.getRealm(), data.getSession());
        String sessionIndex = IDPSSOUtil.getSessionIndex(data.getSession());
        boolean sessionUpgrade = false;
        if (isValidSessionInRealm) {
            sessionUpgrade = isSessionUpgrade(idpAuthnContextInfo, data.getSession());
            SAML2Utils.debug.message("{} IDP Session Upgrade is : {}", classMethod, sessionUpgrade);
        }
        // Holder for any exception encountered while redirecting for authentication:
        FederatedSSOException redirectException = null;
        if (sessionUpgrade || !isValidSessionInRealm || ((Boolean.TRUE.equals(data.getAuthnRequest().isForceAuthn())) && (!Boolean.TRUE.equals(data.getAuthnRequest().isPassive())))) {
            // sessionIndex
            if (sessionIndex != null && sessionIndex.length() != 0) {
                // Save the original IDP Session
                IDPSession oldIDPSession = IDPCache.idpSessionsByIndices.get(sessionIndex);
                if (oldIDPSession != null) {
                    IDPCache.oldIDPSessionCache.put(data.getRequestID(), oldIDPSession);
                } else {
                    SAML2Utils.debug.error(classMethod + "The old SAML2 session  was not found in the idp session " + "by indices cache");
                }
            }
            // Save the new requestId and AuthnRequest
            IDPCache.authnRequestCache.put(data.getRequestID(), new CacheObject(data.getAuthnRequest()));
            // Save the new requestId and AuthnContext
            IDPCache.idpAuthnContextCache.put(data.getRequestID(), new CacheObject(data.getMatchingAuthnContext()));
            // save if the request was an Session Upgrade case.
            IDPCache.isSessionUpgradeCache.add(data.getRequestID());
            // authenticates
            if (StringUtils.isNotBlank(data.getRelayState())) {
                IDPCache.relayStateCache.put(data.getRequestID(), data.getRelayState());
            }
            // Session upgrade could be requested by asking a greater AuthnContext
            if (isValidSessionInRealm) {
                try {
                    boolean isProxy = IDPProxyUtil.isIDPProxyEnabled(data.getAuthnRequest(), data.getRealm());
                    if (isProxy) {
                        preferredIDP = IDPProxyUtil.getPreferredIDP(data.getAuthnRequest(), data.getIdpEntityID(), data.getRealm(), request, response);
                        if (preferredIDP != null) {
                            if ((SPCache.reqParamHash != null) && (!(SPCache.reqParamHash.containsKey(preferredIDP)))) {
                                // IDP Proxy with configured proxy list
                                SAML2Utils.debug.message("{} IDP to be proxied {}", classMethod, preferredIDP);
                                IDPProxyUtil.sendProxyAuthnRequest(data.getAuthnRequest(), preferredIDP, spSSODescriptor, data.getIdpEntityID(), request, response, data.getRealm(), data.getRelayState(), binding);
                                return;
                            } else {
                                // IDP proxy with introduction cookie
                                Map paramsMap = (Map) SPCache.reqParamHash.get(preferredIDP);
                                paramsMap.put("authnReq", data.getAuthnRequest());
                                paramsMap.put("spSSODescriptor", spSSODescriptor);
                                paramsMap.put("idpEntityID", data.getIdpEntityID());
                                paramsMap.put("realm", data.getRealm());
                                paramsMap.put("relayState", data.getRelayState());
                                paramsMap.put("binding", binding);
                                SPCache.reqParamHash.put(preferredIDP, paramsMap);
                                return;
                            }
                        }
                    }
                //else continue for the local authentication.
                } catch (SAML2Exception re) {
                    SAML2Utils.debug.message("{} Redirecting for the proxy handling error: {}", classMethod, re.getMessage());
                    redirectException = new ServerFaultException(data.getIdpAdapter(), "UnableToRedirectToPreferredIDP", re.getMessage());
                }
            // End of IDP Proxy: Initiate proxying when session upgrade is requested
            }
            // Invoke the IDP Adapter before redirecting to authn
            if (preAuthenticationAdapter(request, response, data)) {
                return;
            }
            //we don't have a session
            try {
                //and they want to authenticate
                if (!Boolean.TRUE.equals(data.getAuthnRequest().isPassive())) {
                    redirectAuthentication(request, response, idpAuthnContextInfo, data, true);
                    return;
                } else {
                    try {
                        //and they want to get into the system with passive auth - response no passive
                        IDPSSOUtil.sendNoPassiveResponse(request, response, out, data.getIdpMetaAlias(), data.getIdpEntityID(), data.getRealm(), data.getAuthnRequest(), data.getRelayState(), data.getSpEntityID());
                    } catch (SAML2Exception sme) {
                        SAML2Utils.debug.error(classMethod, sme);
                        redirectException = new ServerFaultException(data.getIdpAdapter(), METADATA_ERROR);
                    }
                }
            } catch (IOException | SAML2Exception e) {
                SAML2Utils.debug.error(classMethod + "Unable to redirect to authentication.", e);
                sessionUpgrade = false;
                cleanUpCache(data.getRequestID());
                redirectException = new ServerFaultException(data.getIdpAdapter(), "UnableToRedirectToAuth", e.getMessage());
            }
        }
        // generate assertion response
        if (!sessionUpgrade && isValidSessionInRealm) {
            generateAssertionResponse(data);
        }
        if (redirectException != null) {
            throw redirectException;
        }
    }
}
Also used : IDPAuthnContextInfo(com.sun.identity.saml2.plugins.IDPAuthnContextInfo) IDPAuthnContextMapper(com.sun.identity.saml2.plugins.IDPAuthnContextMapper) IDPSession(com.sun.identity.saml2.profile.IDPSession) ServerFaultException(com.sun.identity.saml2.profile.ServerFaultException) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) SessionException(com.sun.identity.plugin.session.SessionException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) IDPECPSessionMapper(com.sun.identity.saml2.plugins.IDPECPSessionMapper) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Response(com.sun.identity.saml2.protocol.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) ClientFaultException(com.sun.identity.saml2.profile.ClientFaultException) List(java.util.List) CacheObject(com.sun.identity.saml2.profile.CacheObject) FederatedSSOException(com.sun.identity.saml2.profile.FederatedSSOException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) Map(java.util.Map) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Example 5 with Response

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

the class UtilProxySAMLAuthenticator method redirectToAuth.

private void redirectToAuth(SPSSODescriptorElement spSSODescriptor, String binding, IDPAuthnContextInfo idpAuthnContextInfo, IDPSSOFederateRequest data) throws IOException, ServerFaultException {
    String classMethod = "IDPSSOFederate.redirectToAuth";
    String preferredIDP;
    // retrieved later when the user successfully authenticates
    synchronized (IDPCache.authnRequestCache) {
        IDPCache.authnRequestCache.put(data.getRequestID(), new CacheObject(data.getAuthnRequest()));
    }
    // retrieved later when the user successfully authenticates
    synchronized (IDPCache.idpAuthnContextCache) {
        IDPCache.idpAuthnContextCache.put(data.getRequestID(), new CacheObject(data.getMatchingAuthnContext()));
    }
    // retrieved later when the user successfully authenticates
    if (StringUtils.isNotBlank(data.getRelayState())) {
        IDPCache.relayStateCache.put(data.getRequestID(), data.getRelayState());
    }
    //IDP Proxy: Initiate proxying
    try {
        boolean isProxy = IDPProxyUtil.isIDPProxyEnabled(data.getAuthnRequest(), data.getRealm());
        if (isProxy) {
            preferredIDP = IDPProxyUtil.getPreferredIDP(data.getAuthnRequest(), data.getIdpEntityID(), data.getRealm(), request, response);
            if (preferredIDP != null) {
                if ((SPCache.reqParamHash != null) && (!(SPCache.reqParamHash.containsKey(preferredIDP)))) {
                    // IDP Proxy with configured proxy list
                    SAML2Utils.debug.message("{} IDP to be proxied {} ", classMethod, preferredIDP);
                    IDPProxyUtil.sendProxyAuthnRequest(data.getAuthnRequest(), preferredIDP, spSSODescriptor, data.getIdpEntityID(), request, response, data.getRealm(), data.getRelayState(), binding);
                    return;
                } else {
                    // IDP proxy with introduction cookie
                    Map paramsMap = (Map) SPCache.reqParamHash.get(preferredIDP);
                    paramsMap.put("authnReq", data.getAuthnRequest());
                    paramsMap.put("spSSODescriptor", spSSODescriptor);
                    paramsMap.put("idpEntityID", data.getIdpEntityID());
                    paramsMap.put("realm", data.getRealm());
                    paramsMap.put("relayState", data.getRelayState());
                    paramsMap.put("binding", binding);
                    SPCache.reqParamHash.put(preferredIDP, paramsMap);
                    return;
                }
            }
        }
    //else continue for the local authentication.
    } catch (SAML2Exception re) {
        SAML2Utils.debug.message("{} Redirecting for the proxy handling error: {}", classMethod, re.getMessage());
        throw new ServerFaultException(data.getIdpAdapter(), "UnableToRedirectToPreferredIDP", re.getMessage());
    }
    // preAuthentication adapter hook
    if (preAuthenticationAdapter(request, response, data)) {
        return;
    }
    // redirect to the authentication service
    try {
        if (!Boolean.TRUE.equals(data.getAuthnRequest().isPassive())) {
            redirectAuthentication(request, response, idpAuthnContextInfo, data, false);
        } else {
            try {
                IDPSSOUtil.sendNoPassiveResponse(request, response, out, data.getIdpMetaAlias(), data.getIdpEntityID(), data.getRealm(), data.getAuthnRequest(), data.getRelayState(), data.getSpEntityID());
            } catch (SAML2Exception sme) {
                SAML2Utils.debug.error(classMethod, sme);
                throw new ServerFaultException(data.getIdpAdapter(), METADATA_ERROR);
            }
        }
    } catch (IOException | SAML2Exception e) {
        SAML2Utils.debug.error(classMethod + "Unable to redirect to authentication.", e);
        throw new ServerFaultException(data.getIdpAdapter(), "UnableToRedirectToAuth", e.getMessage());
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) ServerFaultException(com.sun.identity.saml2.profile.ServerFaultException) CacheObject(com.sun.identity.saml2.profile.CacheObject) IOException(java.io.IOException) Map(java.util.Map)

Aggregations

SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)119 List (java.util.List)53 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)45 ArrayList (java.util.ArrayList)41 IOException (java.io.IOException)40 SessionException (com.sun.identity.plugin.session.SessionException)35 Response (com.sun.identity.saml2.protocol.Response)31 SOAPException (javax.xml.soap.SOAPException)31 Issuer (com.sun.identity.saml2.assertion.Issuer)28 HttpServletResponse (javax.servlet.http.HttpServletResponse)28 SAML2TokenRepositoryException (org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)25 Map (java.util.Map)24 Assertion (com.sun.identity.saml2.assertion.Assertion)23 SPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement)23 SOAPMessage (javax.xml.soap.SOAPMessage)22 IDPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)20 Date (java.util.Date)20 HashMap (java.util.HashMap)20 Element (org.w3c.dom.Element)20 X509Certificate (java.security.cert.X509Certificate)16