Search in sources :

Example 71 with Response

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

the class DoManageNameID method initiateManageNameIDRequest.

/**
     * Parses the request parameters and builds the ManageNameID
     * Request to sent to remote Entity.
     *
     * @param request the HttpServletRequest.
     * @param response the HttpServletResponse.
     * @param metaAlias entityID of hosted entity.
     * @param remoteEntityID entityID of remote entity.
     * @param paramsMap Map of all other parameters.
     * @throws SAML2Exception if error initiating request to remote entity.
     */
public static void initiateManageNameIDRequest(HttpServletRequest request, HttpServletResponse response, String metaAlias, String remoteEntityID, Map paramsMap) throws SAML2Exception {
    String method = "DoManageNameID.initiateManageNameIDRequest: ";
    if (metaManager == null) {
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorMetaManager"));
    }
    if (metaAlias == null) {
        logError("MetaAliasNotFound", LogUtil.MISSING_META_ALIAS, metaAlias);
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullEntityID"));
    }
    if (remoteEntityID == null) {
        logError("nullRemoteEntityID", LogUtil.MISSING_ENTITY, remoteEntityID);
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullRemoteEntityID"));
    }
    Object session = null;
    try {
        session = SessionManager.getProvider().getSession(request);
    } catch (SessionException se) {
        if (debug.messageEnabled()) {
            debug.message(method, se);
        }
    }
    String realm = SAML2MetaUtils.getRealmByMetaAlias(metaAlias);
    String hostEntityID = metaManager.getEntityByMetaAlias(metaAlias);
    String hostEntityRole = SAML2Utils.getHostEntityRole(paramsMap);
    if (session == null) {
        if (debug.messageEnabled()) {
            debug.message(method + "Session is missing." + "redirect to the authentication service");
        }
        // redirect to the authentication service
        try {
            SAML2Utils.redirectAuthentication(request, response, realm, hostEntityID, hostEntityRole);
        } catch (IOException ioe) {
            logError("UnableToRedirectToAuth", LogUtil.REDIRECT_TO_AUTH, null);
            throw new SAML2Exception(ioe.toString());
        }
        return;
    }
    if (debug.messageEnabled()) {
        debug.message(method + "Meta Alias is : " + metaAlias);
        debug.message(method + "Remote EntityID is : " + remoteEntityID);
        debug.message(method + "Host EntityID is : " + hostEntityID);
    }
    try {
        String binding = SAML2Utils.getParameter(paramsMap, SAML2Constants.BINDING);
        ManageNameIDServiceElement mniService = getMNIServiceElement(realm, remoteEntityID, hostEntityRole, binding);
        if (binding == null) {
            binding = mniService.getBinding();
        }
        if (binding == null) {
            logError("UnableTofindBinding", LogUtil.METADATA_ERROR, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("UnableTofindBinding"));
        }
        String mniURL = null;
        if (mniService != null) {
            mniURL = mniService.getLocation();
        }
        if (mniURL == null) {
            logError("mniServiceNotFound", LogUtil.METADATA_ERROR, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("mniServiceNotFound"));
        }
        String requestType = (String) paramsMap.get("requestType");
        boolean changeID = "NewID".equals(requestType);
        String affiliationID = SAML2Utils.getParameter(paramsMap, SAML2Constants.AFFILIATION_ID);
        ManageNameIDRequest mniRequest = createManageNameIDRequest(session, realm, hostEntityID, hostEntityRole, remoteEntityID, mniURL, changeID, affiliationID);
        String relayState = SAML2Utils.getParameter(paramsMap, SAML2Constants.RELAY_STATE);
        if ((relayState == null) || (relayState.equals(""))) {
            relayState = SAML2Utils.getAttributeValueFromSSOConfig(realm, hostEntityID, hostEntityRole, SAML2Constants.DEFAULT_RELAY_STATE);
        }
        // Validate the RelayState URL.
        SAML2Utils.validateRelayStateURL(realm, hostEntityID, relayState, hostEntityRole);
        mniRequest.setDestination(XMLUtils.escapeSpecialCharacters(mniURL));
        saveMNIRequestInfo(request, response, paramsMap, mniRequest, relayState, hostEntityRole, session);
        String mniRequestXMLString = null;
        if (binding.equalsIgnoreCase(SAML2Constants.HTTP_REDIRECT)) {
            mniRequestXMLString = mniRequest.toXMLString(true, true);
            doMNIByHttpRedirect(mniRequestXMLString, mniURL, relayState, realm, hostEntityID, hostEntityRole, remoteEntityID, response);
        } else if (binding.equalsIgnoreCase(SAML2Constants.SOAP)) {
            signMNIRequest(mniRequest, realm, hostEntityID, hostEntityRole, remoteEntityID);
            BaseConfigType config = null;
            if (hostEntityRole.equalsIgnoreCase(SAML2Constants.SP_ROLE)) {
                config = metaManager.getIDPSSOConfig(realm, remoteEntityID);
            } else {
                config = metaManager.getSPSSOConfig(realm, remoteEntityID);
            }
            mniURL = SAML2Utils.fillInBasicAuthInfo(config, mniURL);
            if (!doMNIBySOAP(mniRequest, mniURL, metaAlias, hostEntityRole, request, response)) {
                throw new SAML2Exception(SAML2Utils.bundle.getString("mniFailed"));
            }
        } else if (binding.equalsIgnoreCase(SAML2Constants.HTTP_POST)) {
            signMNIRequest(mniRequest, realm, hostEntityID, hostEntityRole, remoteEntityID);
            mniRequestXMLString = mniRequest.toXMLString(true, true);
            doMNIByPOST(mniRequestXMLString, mniURL, relayState, realm, hostEntityID, hostEntityRole, remoteEntityID, response, request);
        }
    } catch (IOException ioe) {
        logError("errorCreatingMNIRequest", LogUtil.CANNOT_INSTANTIATE_MNI_REQUEST, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("errorCreatingMNIRequest"));
    } catch (SAML2MetaException sme) {
        logError("metaDataError", LogUtil.METADATA_ERROR, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
    } catch (SessionException ssoe) {
        logError("invalidSSOToken", LogUtil.INVALID_SSOTOKEN, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) ManageNameIDServiceElement(com.sun.identity.saml2.jaxb.metadata.ManageNameIDServiceElement) BaseConfigType(com.sun.identity.saml2.jaxb.entityconfig.BaseConfigType) ManageNameIDRequest(com.sun.identity.saml2.protocol.ManageNameIDRequest) SessionException(com.sun.identity.plugin.session.SessionException) IOException(java.io.IOException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException)

Example 72 with Response

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

the class FSUtils method forwardRequest.

/**
     * Forwards or redirects to a new URL. This method will do forwarding
     * if the target url is in  the same web deployment URI as current web 
     * apps. Otherwise will do redirecting.   
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @param url the target URL to be forwarded to redirected.  
     */
public static void forwardRequest(HttpServletRequest request, HttpServletResponse response, String url) {
    FSUtils.debug.message("FSUtils.forwardRequest: called");
    String newUrl = null;
    try {
        SessionProvider sessionProvider = SessionManager.getProvider();
        Object token = sessionProvider.getSession(request);
        if ((token != null) && (sessionProvider.isValid(token))) {
            newUrl = sessionProvider.rewriteURL(token, url);
        }
    } catch (Exception se) {
        if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message("FSUtils.forwardReqeust: couldn't rewrite url: " + se.getMessage());
        }
        newUrl = null;
    }
    if (newUrl == null) {
        newUrl = url;
    }
    try {
        //get source host and port
        String sourceHost = request.getServerName();
        int sourcePort = request.getServerPort();
        FSUtils.debug.message("FSUtils.forwardRequest: " + "SourceHost=" + sourceHost + " SourcePort=" + sourcePort);
        //get target host and port
        URL target = new URL(newUrl);
        String targetHost = target.getHost();
        int targetPort = target.getPort();
        FSUtils.debug.message("FSUtils.forwardRequest: targetHost=" + targetHost + " targetPort=" + targetPort);
        /**
             * IBM websphere is not able to handle forwards with long urls.
             */
        boolean isWebSphere = false;
        String container = SystemConfigurationUtil.getProperty(Constants.IDENTITY_WEB_CONTAINER);
        if (container != null && (container.indexOf("IBM") != -1)) {
            isWebSphere = true;
        }
        int index = newUrl.indexOf(deploymentURI + "/");
        if (!(sourceHost.equals(targetHost)) || !(sourcePort == targetPort) || !(index > 0) || isWebSphere) {
            FSUtils.debug.message("FSUtils.forwardRequest: Source and " + "Target are not on the same container." + "Redirecting to target");
            response.sendRedirect(newUrl);
            return;
        } else {
            String resource = newUrl.substring(index + deploymentURI.length());
            if (FSUtils.debug.messageEnabled()) {
                FSUtils.debug.message("FSUtils.forwardRequest: Forwarding to :" + resource);
            }
            RequestDispatcher dispatcher = request.getRequestDispatcher(resource);
            try {
                dispatcher.forward(request, response);
            } catch (Exception e) {
                FSUtils.debug.error("FSUtils.forwardRequest: Exception " + "occured while trying to forward to resource:" + resource, e);
            }
        }
    } catch (Exception ex) {
        FSUtils.debug.error("FSUtils.forwardRequest: Exception occured", ex);
    }
}
Also used : ServletException(javax.servlet.ServletException) SystemConfigurationException(com.sun.identity.common.SystemConfigurationException) MissingResourceException(java.util.MissingResourceException) IOException(java.io.IOException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) URL(java.net.URL) RequestDispatcher(javax.servlet.RequestDispatcher) SessionProvider(com.sun.identity.plugin.session.SessionProvider)

Example 73 with Response

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

the class SAML2Utils method verifyResponse.

/**
     * Verifies single sign on <code>Response</code> and returns information
     * to SAML2 auth module for further processing. This method is used by
     * SAML2 auth module only.
     *
     * @param httpRequest    HttpServletRequest
     * @param httpResponse   HttpServletResponse
     * @param response       Single Sign On <code>Response</code>.
     * @param orgName        name of the realm or organization the provider is in.
     * @param hostEntityId   Entity ID of the hosted provider.
     * @param profileBinding Profile binding used.
     * @return A Map of information extracted from the Response. The keys of
     * map are:
     * <code>SAML2Constants.SUBJECT</code>,
     * <code>SAML2Constants.POST_ASSERTION</code>,
     * <code>SAML2Constants.ASSERTIONS</code>,
     * <code>SAML2Constants.SESSION_INDEX</code>,
     * <code>SAML2Constants.AUTH_LEVEL</code>,
     * <code>SAML2Constants.MAX_SESSION_TIME</code>.
     * @throws SAML2Exception if the Response is not valid according to the
     *                        processing rules.
     */
public static Map verifyResponse(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final Response response, final String orgName, final String hostEntityId, final String profileBinding) throws SAML2Exception {
    final String method = "SAML2Utils.verifyResponse:";
    if (response == null || orgName == null || orgName.length() == 0) {
        if (debug.messageEnabled()) {
            debug.message(method + "response or orgName is null.");
        }
        throw new SAML2Exception(bundle.getString("nullInput"));
    }
    String respID = response.getID();
    AuthnRequestInfo reqInfo = null;
    String inRespToResp = response.getInResponseTo();
    if (inRespToResp != null && inRespToResp.length() != 0) {
        reqInfo = (AuthnRequestInfo) SPCache.requestHash.get(inRespToResp);
        if (reqInfo == null) {
            if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
                // Attempt to read AuthnRequestInfoCopy from SAML2 repository
                AuthnRequestInfoCopy reqInfoCopy = null;
                try {
                    reqInfoCopy = (AuthnRequestInfoCopy) SAML2FailoverUtils.retrieveSAML2Token(inRespToResp);
                } catch (SAML2TokenRepositoryException se) {
                    debug.error(method + "AuthnRequestInfoCopy" + " unable to retrieve from SAML2 repository for inResponseTo: " + inRespToResp);
                }
                if (reqInfoCopy != null) {
                    // Get back the AuthnRequestInfo
                    reqInfo = reqInfoCopy.getAuthnRequestInfo(httpRequest, httpResponse);
                    if (debug.messageEnabled()) {
                        debug.message(method + "AuthnRequestInfoCopy" + " retrieved from SAML2 repository for inResponseTo: " + inRespToResp);
                    }
                } else {
                    debug.error(method + "InResponseTo attribute in Response" + " is invalid: " + inRespToResp + ", SAML2 failover is enabled");
                    String[] data = { respID };
                    LogUtil.error(Level.INFO, LogUtil.INVALID_INRESPONSETO_RESPONSE, data, null);
                    throw new SAML2Exception(bundle.getString("invalidInResponseToInResponse"));
                }
            } else {
                AuthnRequestInfoCopy reqInfoCopy = (AuthnRequestInfoCopy) SAML2Store.getTokenFromStore(inRespToResp);
                if (reqInfoCopy != null) {
                    // Get back the AuthnRequestInfo
                    reqInfo = reqInfoCopy.getAuthnRequestInfo(httpRequest, httpResponse);
                    if (debug.messageEnabled()) {
                        debug.message(method + "AuthnRequestInfoCopy" + " retrieved from SAML2 repository for inResponseTo: " + inRespToResp);
                    }
                } else {
                    debug.error(method + "InResponseTo attribute in Response" + " is invalid: " + inRespToResp + ", SAML2 failover is enabled");
                    String[] data = { respID };
                    LogUtil.error(Level.INFO, LogUtil.INVALID_INRESPONSETO_RESPONSE, data, null);
                    throw new SAML2Exception(bundle.getString("invalidInResponseToInResponse"));
                }
            }
        }
    }
    // reqInfo can remain null and will do for IDP initiated SSO requests
    // invoke SP Adapter
    SAML2ServiceProviderAdapter spAdapter = SAML2Utils.getSPAdapterClass(hostEntityId, orgName);
    if (spAdapter != null) {
        AuthnRequest authnRequest = null;
        if (reqInfo != null) {
            authnRequest = reqInfo.getAuthnRequest();
        }
        spAdapter.preSingleSignOnProcess(hostEntityId, orgName, httpRequest, httpResponse, authnRequest, response, profileBinding);
    }
    String idpEntityId = null;
    Issuer respIssuer = response.getIssuer();
    if (respIssuer != null) {
        // optional
        if (!isSourceSiteValid(respIssuer, orgName, hostEntityId)) {
            if (debug.messageEnabled()) {
                debug.message(method + "Issuer in Response is not valid.");
            }
            String[] data = { hostEntityId, orgName, respID };
            LogUtil.error(Level.INFO, LogUtil.INVALID_ISSUER_RESPONSE, data, null);
            throw new SAML2Exception(bundle.getString("invalidIssuerInResponse"));
        } else {
            idpEntityId = respIssuer.getValue();
        }
    }
    Status status = response.getStatus();
    if (status == null || !status.getStatusCode().getValue().equals(SAML2Constants.SUCCESS)) {
        String statusCode = (status == null) ? "" : status.getStatusCode().getValue();
        if (debug.messageEnabled()) {
            debug.message(method + "Response's status code is not success: " + statusCode);
        }
        String[] data = { respID, "" };
        if (LogUtil.isErrorLoggable(Level.FINE)) {
            data[1] = statusCode;
        }
        LogUtil.error(Level.INFO, LogUtil.WRONG_STATUS_CODE, data, null);
        if (SAML2Constants.RESPONDER.equals(statusCode)) {
            //In case of passive authentication the NoPassive response will be sent using two StatusCode nodes:
            //the outer StatusCode will be Responder and the inner StatusCode will contain the NoPassive URN
            StatusCode secondLevelStatusCode = status.getStatusCode().getStatusCode();
            if (secondLevelStatusCode != null && SAML2Constants.NOPASSIVE.equals(secondLevelStatusCode.getValue())) {
                throw new SAML2Exception(SAML2Utils.BUNDLE_NAME, "noPassiveResponse", null);
            }
        } else if (SAML2Constants.REQUESTER.equals(statusCode)) {
            // when is AllowCreate=false mode the auth module gets here with a
            // statusCode of urn:oasis:names:tc:SAML:2.0:status:Requester
            StatusCode secondLevelStatusCode = status.getStatusCode().getStatusCode();
            if (secondLevelStatusCode != null && SAML2Constants.INVALID_NAME_ID_POLICY.equals(secondLevelStatusCode.getValue())) {
                throw new SAML2Exception(SAML2Utils.BUNDLE_NAME, "nameIDMReqInvalidNameIDPolicy", null);
            }
        }
        throw new SAML2Exception(bundle.getString("invalidStatusCodeInResponse"));
    }
    if (saml2MetaManager == null) {
        throw new SAML2Exception(bundle.getString("nullMetaManager"));
    }
    SPSSOConfigElement spConfig = null;
    SPSSODescriptorElement spDesc = null;
    spConfig = saml2MetaManager.getSPSSOConfig(orgName, hostEntityId);
    spDesc = saml2MetaManager.getSPSSODescriptor(orgName, hostEntityId);
    if (debug.messageEnabled()) {
        debug.message(method + "binding is :" + profileBinding);
    }
    // SAML spec processing
    //  4.1.4.3   Verify any signatures present on the assertion(s) or the response
    boolean responseIsSigned = false;
    if (response.isSigned()) {
        IDPSSODescriptorElement idpSSODescriptor = null;
        try {
            idpSSODescriptor = saml2MetaManager.getIDPSSODescriptor(orgName, idpEntityId);
        } catch (SAML2MetaException sme) {
            String[] data = { orgName, idpEntityId };
            LogUtil.error(Level.INFO, LogUtil.IDP_METADATA_ERROR, data, null);
            throw new SAML2Exception(sme);
        }
        if (idpSSODescriptor != null) {
            Set<X509Certificate> verificationCerts = KeyUtil.getVerificationCerts(idpSSODescriptor, idpEntityId, SAML2Constants.IDP_ROLE);
            if (CollectionUtils.isEmpty(verificationCerts) || !response.isSignatureValid(verificationCerts)) {
                debug.error(method + "Response is not signed or signature is not valid.");
                String[] data = { orgName, hostEntityId, idpEntityId };
                LogUtil.error(Level.INFO, LogUtil.POST_RESPONSE_INVALID_SIGNATURE, data, null);
                throw new SAML2Exception(bundle.getString("invalidSignInResponse"));
            }
        } else {
            String[] data = { idpEntityId };
            LogUtil.error(Level.INFO, LogUtil.IDP_METADATA_ERROR, data, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
        }
        responseIsSigned = true;
    }
    if (debug.messageEnabled()) {
        debug.message(method + "responseIsSigned is :" + responseIsSigned);
    }
    // assertion encryption check
    boolean needAssertionEncrypted = false;
    String assertionEncryptedAttr = getAttributeValueFromSPSSOConfig(spConfig, SAML2Constants.WANT_ASSERTION_ENCRYPTED);
    needAssertionEncrypted = Boolean.parseBoolean(assertionEncryptedAttr);
    if (debug.messageEnabled()) {
        debug.message(method + "NeedAssertionEncrypted is :" + needAssertionEncrypted);
    }
    List<Assertion> assertions = response.getAssertion();
    if (needAssertionEncrypted && !CollectionUtils.isEmpty(assertions)) {
        String[] data = { respID };
        LogUtil.error(Level.INFO, LogUtil.ASSERTION_NOT_ENCRYPTED, data, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("assertionNotEncrypted"));
    }
    Set<PrivateKey> decryptionKeys;
    List<EncryptedAssertion> encAssertions = response.getEncryptedAssertion();
    if (encAssertions != null) {
        decryptionKeys = KeyUtil.getDecryptionKeys(spConfig);
        for (EncryptedAssertion encAssertion : encAssertions) {
            Assertion assertion = encAssertion.decrypt(decryptionKeys);
            if (assertions == null) {
                assertions = new ArrayList<>();
            }
            assertions.add(assertion);
        }
    }
    if (CollectionUtils.isEmpty(assertions)) {
        if (debug.messageEnabled()) {
            debug.message(method + "no assertion in the Response.");
        }
        String[] data = { respID };
        LogUtil.error(Level.INFO, LogUtil.MISSING_ASSERTION, data, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("missingAssertion"));
    }
    boolean wantAssertionsSigned = spDesc.isWantAssertionsSigned();
    if (debug.messageEnabled()) {
        debug.message(method + "wantAssertionsSigned is :" + wantAssertionsSigned);
    }
    // validate the assertions
    Map smap = null;
    Map bearerMap = null;
    IDPSSODescriptorElement idp = null;
    Set<X509Certificate> verificationCerts = null;
    boolean allAssertionsSigned = true;
    for (Assertion assertion : assertions) {
        String assertionID = assertion.getID();
        Issuer issuer = assertion.getIssuer();
        if (!isSourceSiteValid(issuer, orgName, hostEntityId)) {
            debug.error("assertion's source site is not valid.");
            String[] data = { assertionID };
            LogUtil.error(Level.INFO, LogUtil.INVALID_ISSUER_ASSERTION, data, null);
            throw new SAML2Exception(bundle.getString("invalidIssuerInAssertion"));
        }
        if (idpEntityId == null) {
            idpEntityId = issuer.getValue();
        } else {
            if (!idpEntityId.equals(issuer.getValue())) {
                if (debug.messageEnabled()) {
                    debug.message(method + "Issuer in Assertion doesn't " + "match the Issuer in Response or other " + "Assertions in the Response.");
                }
                String[] data = { assertionID };
                LogUtil.error(Level.INFO, LogUtil.MISMATCH_ISSUER_ASSERTION, data, null);
                throw new SAML2Exception(SAML2Utils.bundle.getString("mismatchIssuer"));
            }
        }
        if (assertion.isSigned()) {
            if (verificationCerts == null) {
                idp = saml2MetaManager.getIDPSSODescriptor(orgName, idpEntityId);
                verificationCerts = KeyUtil.getVerificationCerts(idp, idpEntityId, SAML2Constants.IDP_ROLE);
            }
            if (CollectionUtils.isEmpty(verificationCerts) || !assertion.isSignatureValid(verificationCerts)) {
                debug.error(method + "Assertion is not signed or signature is not valid.");
                String[] data = { assertionID };
                LogUtil.error(Level.INFO, LogUtil.INVALID_SIGNATURE_ASSERTION, data, null);
                throw new SAML2Exception(bundle.getString("invalidSignatureOnAssertion"));
            }
        } else {
            allAssertionsSigned = false;
        }
        List authnStmts = assertion.getAuthnStatements();
        if (authnStmts != null && !authnStmts.isEmpty()) {
            Subject subject = assertion.getSubject();
            if (subject == null) {
                continue;
            }
            List subjectConfirms = subject.getSubjectConfirmation();
            if (subjectConfirms == null || subjectConfirms.isEmpty()) {
                continue;
            }
            bearerMap = isBearerSubjectConfirmation(subjectConfirms, inRespToResp, spDesc, spConfig, assertionID);
            if (!((Boolean) bearerMap.get(SAML2Constants.IS_BEARER))) {
                continue;
            }
            boolean foundAssertion = false;
            if ((SPCache.assertionByIDCache != null) && (SPCache.assertionByIDCache.containsKey(assertionID))) {
                foundAssertion = true;
            }
            if ((!foundAssertion) && SAML2FailoverUtils.isSAML2FailoverEnabled()) {
                try {
                    if (SAML2FailoverUtils.retrieveSAML2Token(assertionID) != null) {
                        foundAssertion = true;
                    }
                } catch (SAML2TokenRepositoryException e) {
                    if (debug.messageEnabled()) {
                        debug.message("Session not found in AMTokenSAML2Repository.", e);
                    }
                }
            }
            if (foundAssertion) {
                debug.error("Bearer Assertion is one time use only!");
                throw new SAML2Exception(bundle.getString("usedBearAssertion"));
            }
            checkAudience(assertion.getConditions(), hostEntityId, assertionID);
            if (smap == null) {
                smap = fillMap(authnStmts, subject, assertion, assertions, reqInfo, inRespToResp, orgName, hostEntityId, idpEntityId, spConfig, (Date) bearerMap.get(SAML2Constants.NOTONORAFTER));
            }
        }
    // end of having authnStmt
    }
    if (smap == null) {
        debug.error("No Authentication Assertion in Response.");
        throw new SAML2Exception(bundle.getString("missingAuthnAssertion"));
    }
    // the enclosing element
    if (wantAssertionsSigned && !(responseIsSigned || allAssertionsSigned)) {
        debug.error(method + "WantAssertionsSigned is true and response or all assertions are not signed");
        String[] data = { orgName, hostEntityId, idpEntityId };
        LogUtil.error(Level.INFO, LogUtil.INVALID_SIGNATURE_ASSERTION, data, null);
        throw new SAML2Exception(bundle.getString("assertionNotSigned"));
    }
    // signing each individual <Assertion> element or by signing the <Response> element.
    if (profileBinding.equals(SAML2Constants.HTTP_POST)) {
        boolean wantPostResponseSigned = SAML2Utils.wantPOSTResponseSigned(orgName, hostEntityId, SAML2Constants.SP_ROLE);
        if (debug.messageEnabled()) {
            debug.message(method + "wantPostResponseSigned is :" + wantPostResponseSigned);
        }
        if (wantPostResponseSigned && !responseIsSigned) {
            debug.error(method + "wantPostResponseSigned is true but response is not signed");
            String[] data = { orgName, hostEntityId, idpEntityId };
            LogUtil.error(Level.INFO, LogUtil.POST_RESPONSE_INVALID_SIGNATURE, data, null);
            throw new SAML2Exception(bundle.getString("responseNotSigned"));
        }
        if (!responseIsSigned && !allAssertionsSigned) {
            debug.error(method + "WantAssertionsSigned is true but some or all assertions are not signed");
            String[] data = { orgName, hostEntityId, idpEntityId };
            LogUtil.error(Level.INFO, LogUtil.INVALID_SIGNATURE_ASSERTION, data, null);
            throw new SAML2Exception(bundle.getString("assertionNotSigned"));
        }
    }
    return smap;
}
Also used : PrivateKey(java.security.PrivateKey) Issuer(com.sun.identity.saml2.assertion.Issuer) AuthnRequestInfo(com.sun.identity.saml2.profile.AuthnRequestInfo) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) StatusCode(com.sun.identity.saml2.protocol.StatusCode) ArrayList(java.util.ArrayList) List(java.util.List) AuthnRequestInfoCopy(com.sun.identity.saml2.profile.AuthnRequestInfoCopy) SAML2ServiceProviderAdapter(com.sun.identity.saml2.plugins.SAML2ServiceProviderAdapter) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) Status(com.sun.identity.saml2.protocol.Status) SPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.SPSSOConfigElement) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) Assertion(com.sun.identity.saml2.assertion.Assertion) X509Certificate(java.security.cert.X509Certificate) Subject(com.sun.identity.saml2.assertion.Subject) Date(java.util.Date) AuthnRequest(com.sun.identity.saml2.protocol.AuthnRequest) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) Map(java.util.Map) HashMap(java.util.HashMap) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Example 74 with Response

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

the class SAML2Utils method getNameIDStringFromResponse.

/**
     * Obtains the value of NameID from Response.
     *
     * @param response <code>Response</code> object
     * @return value of the NameID from the first Assertion in the response.
     * null if the response is null, or no assertion in the response, or
     * no NameID in the assertion.
     */
public static String getNameIDStringFromResponse(Response response) {
    if (response != null) {
        List assertions = response.getAssertion();
        if ((assertions != null) && (assertions.size() > 0)) {
            Assertion assertion = (Assertion) assertions.get(0);
            Subject subject = assertion.getSubject();
            if (subject != null) {
                NameID nameID = subject.getNameID();
                if (nameID != null) {
                    return nameID.getValue();
                }
            }
        }
    }
    return null;
}
Also used : NameID(com.sun.identity.saml2.assertion.NameID) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) Assertion(com.sun.identity.saml2.assertion.Assertion) ArrayList(java.util.ArrayList) List(java.util.List) Subject(com.sun.identity.saml2.assertion.Subject)

Example 75 with Response

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

the class SAML2Utils method sendRequestToOrigServer.

/**
     * Sends the request to the original Federation server and receives the result
     * data.
     *
     * @param request      HttpServletRequest to be sent
     * @param response     HttpServletResponse to be received
     * @param sloServerUrl URL of the original federation server to be
     *                     connected
     * @return HashMap of the result data from the original server's response
     */
public static HashMap sendRequestToOrigServer(HttpServletRequest request, HttpServletResponse response, String sloServerUrl) {
    HashMap origRequestData = new HashMap();
    String classMethod = "SAML2Utils.sendRequestToOrigServer: ";
    // Print request Headers
    if (debug.messageEnabled()) {
        for (Enumeration<String> requestHeaders = request.getHeaderNames(); requestHeaders.hasMoreElements(); ) {
            String name = requestHeaders.nextElement();
            Enumeration<String> value = request.getHeaders(name);
            debug.message(classMethod + "Header name = " + name + " Value = " + value);
        }
    }
    // Open URL connection
    HttpURLConnection conn = null;
    String strCookies = null;
    try {
        URL sloRoutingURL = new URL(sloServerUrl);
        if (debug.messageEnabled()) {
            debug.message(classMethod + "Connecting to : " + sloRoutingURL);
        }
        conn = HttpURLConnectionManager.getConnection(sloRoutingURL);
        boolean isGET = request.getMethod().equalsIgnoreCase(GET_METHOD);
        if (isGET) {
            conn.setRequestMethod(GET_METHOD);
        } else {
            conn.setDoOutput(true);
            conn.setRequestMethod(POST_METHOD);
        }
        HttpURLConnection.setFollowRedirects(false);
        conn.setInstanceFollowRedirects(false);
        // replay cookies
        strCookies = getCookiesString(request);
        if (strCookies != null) {
            if (debug.messageEnabled()) {
                debug.message(classMethod + "Sending cookies : " + strCookies);
            }
            conn.setRequestProperty("Cookie", strCookies);
        }
        conn.setRequestProperty("Host", request.getHeader("host"));
        conn.setRequestProperty(SAMLConstants.ACCEPT_LANG_HEADER, request.getHeader(SAMLConstants.ACCEPT_LANG_HEADER));
        // do the remote connection
        if (isGET) {
            conn.connect();
        } else {
            String data = "";
            Map<String, String[]> params = request.getParameterMap();
            for (Map.Entry<String, String[]> param : params.entrySet()) {
                data = data + param.getKey() + "=" + URLEncDec.encode(param.getValue()[0]) + "&";
            }
            data = data.substring(0, data.length() - 1);
            if (debug.messageEnabled()) {
                debug.message(classMethod + "DATA to be SENT: " + data);
            }
            OutputStreamWriter writer = null;
            try {
                writer = new OutputStreamWriter(conn.getOutputStream());
                writer.write(data);
            } catch (IOException ioe) {
                debug.error(classMethod + "Could not write to the destination", ioe);
            } finally {
                writer.close();
            }
        }
        // Receiving input from Original Federation server...
        if (debug.messageEnabled()) {
            debug.message(classMethod + "RECEIVING DATA ... ");
            debug.message(classMethod + "Response Code: " + conn.getResponseCode());
            debug.message(classMethod + "Response Message: " + conn.getResponseMessage());
            debug.message(classMethod + "Follow redirect : " + HttpURLConnection.getFollowRedirects());
        }
        // Input from Original servlet...
        StringBuilder in_buf = new StringBuilder();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        int len;
        char[] buf = new char[1024];
        while ((len = in.read(buf, 0, buf.length)) != -1) {
            in_buf.append(buf, 0, len);
        }
        String in_string = in_buf.toString();
        if (debug.messageEnabled()) {
            debug.message(classMethod + "Received response data : " + in_string);
        }
        origRequestData.put(SAML2Constants.OUTPUT_DATA, in_string);
        String redirect_url = conn.getHeaderField(LOCATION);
        if (redirect_url != null) {
            origRequestData.put(SAML2Constants.AM_REDIRECT_URL, redirect_url);
        }
        origRequestData.put(SAML2Constants.RESPONSE_CODE, Integer.toString(conn.getResponseCode()));
        // retrieves cookies from the response
        Map headers = conn.getHeaderFields();
        processCookies(headers, request, response);
    } catch (Exception ex) {
        if (debug.messageEnabled()) {
            debug.message(classMethod + "send exception : ", ex);
        }
    }
    return origRequestData;
}
Also used : InputStreamReader(java.io.InputStreamReader) HashMap(java.util.HashMap) IOException(java.io.IOException) URL(java.net.URL) SystemConfigurationException(com.sun.identity.common.SystemConfigurationException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) SessionException(com.sun.identity.plugin.session.SessionException) DataStoreProviderException(com.sun.identity.plugin.datastore.DataStoreProviderException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) COTException(com.sun.identity.cot.COTException) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) HttpURLConnection(java.net.HttpURLConnection) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) Map(java.util.Map) HashMap(java.util.HashMap)

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