Search in sources :

Example 11 with OrderedSet

use of com.sun.identity.shared.datastruct.OrderedSet in project OpenAM by OpenRock.

the class IDPArtifactResolution method onMessage.

/**
     * This method generates a <code>SOAPMessage</code> containing the
     * <code>ArtifactResponse</code> that is corresponding to the
     * <code>ArtifactResolve</code> contained in the 
     * <code>SOAPMessage</code> passed in.
     *
     * @param message <code>SOAPMessage</code> contains a
     *             <code>ArtifactResolve</code> 
     * @param request the <code>HttpServletRequest</code> object
     * @param realm the realm to where the identity provider belongs
     * @param idpEntityID the entity id of the identity provider 
     * 
     * @return <code>SOAPMessage</code> contains the 
     *             <code>ArtifactResponse</code>
     * @exception SAML2Exception if the operation is not successful
     */
public static SOAPMessage onMessage(SOAPMessage message, HttpServletRequest request, HttpServletResponse response, String realm, String idpEntityID) throws SAML2Exception {
    String classMethod = "IDPArtifactResolution.onMessage: ";
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message(classMethod + "Entering onMessage().");
    }
    Element reqElem = SOAPCommunicator.getInstance().getSamlpElement(message, "ArtifactResolve");
    ArtifactResolve artResolve = ProtocolFactory.getInstance().createArtifactResolve(reqElem);
    if (artResolve == null) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "no valid ArtifactResolve node found in SOAP body.");
        }
        return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, "noArtifactResolve", null);
    }
    String spEntityID = artResolve.getIssuer().getValue();
    if (!SAML2Utils.isSourceSiteValid(artResolve.getIssuer(), realm, idpEntityID)) {
        SAML2Utils.debug.error(classMethod + spEntityID + " is not trusted issuer.");
        String[] data = { idpEntityID, realm, artResolve.getID() };
        LogUtil.error(Level.INFO, LogUtil.INVALID_ISSUER_REQUEST, data, null);
        return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, "invalidIssuerInRequest", null);
    }
    SPSSODescriptorElement spSSODescriptor = null;
    try {
        spSSODescriptor = IDPSSOUtil.metaManager.getSPSSODescriptor(realm, spEntityID);
    } catch (SAML2MetaException sme) {
        SAML2Utils.debug.error(classMethod, sme);
        spSSODescriptor = null;
    }
    if (spSSODescriptor == null) {
        SAML2Utils.debug.error(classMethod + "Unable to get SP SSO Descriptor from meta.");
        return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.SERVER_FAULT, "metaDataError", null);
    }
    OrderedSet acsSet = SPSSOFederate.getACSUrl(spSSODescriptor, SAML2Constants.HTTP_ARTIFACT);
    String acsURL = (String) acsSet.get(0);
    //String protocolBinding = (String) acsSet.get(1);
    String isArtifactResolveSigned = SAML2Utils.getAttributeValueFromSSOConfig(realm, idpEntityID, SAML2Constants.IDP_ROLE, SAML2Constants.WANT_ARTIFACT_RESOLVE_SIGNED);
    if ((isArtifactResolveSigned != null) && (isArtifactResolveSigned.equals(SAML2Constants.TRUE))) {
        if (!artResolve.isSigned()) {
            SAML2Utils.debug.error(classMethod + "The artifact resolve is not signed " + "when it is expected to be signed.");
            return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, "ArtifactResolveNotSigned", null);
        }
        Set<X509Certificate> verificationCerts = KeyUtil.getVerificationCerts(spSSODescriptor, spEntityID, SAML2Constants.SP_ROLE);
        if (!artResolve.isSignatureValid(verificationCerts)) {
            SAML2Utils.debug.error(classMethod + "artifact resolve verification failed.");
            return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, "invalidArtifact", null);
        }
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "artifact resolve signature verification is successful.");
        }
    }
    Artifact art = artResolve.getArtifact();
    if (art == null) {
        SAML2Utils.debug.error(classMethod + "Unable to get an artifact from ArtifactResolve.");
        return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, "invalidArtifactSignature", null);
    }
    String artStr = art.getArtifactValue();
    Response res = (Response) IDPCache.responsesByArtifacts.remove(artStr);
    String remoteArtURL = null;
    boolean saml2FailoverEnabled = SAML2FailoverUtils.isSAML2FailoverEnabled();
    if (res == null) {
        // in LB case, artifact may reside on the other server.
        String targetServerID = SAML2Utils.extractServerId(art.getMessageHandle());
        if (targetServerID == null) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + "target serverID is null");
            }
            return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, "InvalidArtifactId", null);
        }
        String localServerID = SAML2Utils.getLocalServerID();
        boolean localTarget = localServerID.equals(targetServerID);
        if (!localTarget) {
            if (!SystemConfigurationUtil.isValidServerId(targetServerID)) {
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.message(classMethod + "target serverID is not valid: " + targetServerID);
                }
                return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, "InvalidArtifactId", null);
            }
            try {
                String remoteServiceURL = SystemConfigurationUtil.getServerFromID(targetServerID);
                remoteArtURL = remoteServiceURL + SAML2Utils.removeDeployUri(request.getRequestURI());
                SOAPConnection con = SOAPCommunicator.getInstance().openSOAPConnection();
                SOAPMessage resMsg = con.call(message, remoteArtURL);
                return resMsg;
            } catch (Exception ex) {
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.message(classMethod + "unable to forward request to remote server. " + "remote url = " + remoteArtURL, ex);
                }
                if (!saml2FailoverEnabled) {
                    return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.SERVER_FAULT, "RemoteArtifactResolutionFailed", null);
                }
            // when the target server is running but the remote call was
            // failed to this server (due to a network error)
            // and the saml2failover is enabled, we can still find the
            // artifact in the SAML2 repository.
            // However the cached entry in the target server will not be
            // deleted this way.
            }
        }
        if (saml2FailoverEnabled) {
            // Check the SAML2 Token Repository
            try {
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.message("Artifact=" + artStr);
                }
                String tmp = (String) SAML2FailoverUtils.retrieveSAML2Token(artStr);
                res = ProtocolFactory.getInstance().createResponse(tmp);
            } catch (SAML2Exception e) {
                SAML2Utils.debug.error(classMethod + " SAML2 ERROR!!!", e);
                return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, "UnableToFindResponseInRepo", null);
            } catch (SAML2TokenRepositoryException se) {
                SAML2Utils.debug.error(classMethod + " There was a problem reading the response " + "from the SAML2 Token Repository using artStr:" + artStr, se);
                return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, "UnableToFindResponseInRepo", null);
            }
        }
    }
    if (res == null) {
        return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.CLIENT_FAULT, saml2FailoverEnabled ? "UnableToFindResponseInRepo" : "UnableToFindResponse", null);
    }
    // Remove Response from SAML2 Token Repository
    try {
        if (saml2FailoverEnabled) {
            SAML2FailoverUtils.deleteSAML2Token(artStr);
        }
    } catch (SAML2TokenRepositoryException e) {
        SAML2Utils.debug.error(classMethod + " Error deleting the response from the SAML2 Token Repository using artStr:" + artStr, e);
    }
    Map props = new HashMap();
    String nameIDString = SAML2Utils.getNameIDStringFromResponse(res);
    if (nameIDString != null) {
        props.put(LogUtil.NAME_ID, nameIDString);
    }
    // check if need to sign the assertion
    boolean signAssertion = spSSODescriptor.isWantAssertionsSigned();
    if (signAssertion) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "signing the assertion.");
        }
    }
    // encrypt the assertion or its NameID and/or Attribute based
    // on SP config setting and sign the assertion.
    IDPSSOUtil.signAndEncryptResponseComponents(realm, spEntityID, idpEntityID, res, signAssertion);
    ArtifactResponse artResponse = ProtocolFactory.getInstance().createArtifactResponse();
    Status status = ProtocolFactory.getInstance().createStatus();
    StatusCode statusCode = ProtocolFactory.getInstance().createStatusCode();
    statusCode.setValue(SAML2Constants.SUCCESS);
    status.setStatusCode(statusCode);
    // set the idp entity id as the response issuer
    Issuer issuer = AssertionFactory.getInstance().createIssuer();
    issuer.setValue(idpEntityID);
    artResponse.setStatus(status);
    artResponse.setID(SAML2Utils.generateID());
    artResponse.setInResponseTo(artResolve.getID());
    artResponse.setVersion(SAML2Constants.VERSION_2_0);
    artResponse.setIssueInstant(new Date());
    artResponse.setAny(res.toXMLString(true, true));
    artResponse.setIssuer(issuer);
    artResponse.setDestination(XMLUtils.escapeSpecialCharacters(acsURL));
    String wantArtifactResponseSigned = SAML2Utils.getAttributeValueFromSSOConfig(realm, spEntityID, SAML2Constants.SP_ROLE, SAML2Constants.WANT_ARTIFACT_RESPONSE_SIGNED);
    if ((wantArtifactResponseSigned != null) && (wantArtifactResponseSigned.equals(SAML2Constants.TRUE))) {
        KeyProvider kp = KeyUtil.getKeyProviderInstance();
        if (kp == null) {
            SAML2Utils.debug.error(classMethod + "Unable to get a key provider instance.");
            return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.SERVER_FAULT, "nullKeyProvider", null);
        }
        String idpSignCertAlias = SAML2Utils.getSigningCertAlias(realm, idpEntityID, SAML2Constants.IDP_ROLE);
        if (idpSignCertAlias == null) {
            SAML2Utils.debug.error(classMethod + "Unable to get the hosted IDP signing certificate alias.");
            return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.SERVER_FAULT, "missingSigningCertAlias", null);
        }
        String encryptedKeyPass = SAML2Utils.getSigningCertEncryptedKeyPass(realm, idpEntityID, SAML2Constants.IDP_ROLE);
        PrivateKey key;
        if (encryptedKeyPass == null || encryptedKeyPass.isEmpty()) {
            key = kp.getPrivateKey(idpSignCertAlias);
        } else {
            key = kp.getPrivateKey(idpSignCertAlias, encryptedKeyPass);
        }
        artResponse.sign(key, kp.getX509Certificate(idpSignCertAlias));
    }
    String str = artResponse.toXMLString(true, true);
    String[] logdata = { idpEntityID, artStr, str };
    LogUtil.access(Level.INFO, LogUtil.ARTIFACT_RESPONSE, logdata, null, props);
    if (str != null) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "ArtifactResponse message:\n" + str);
        }
    } else {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "Unable to print ArtifactResponse message.");
        }
    }
    SOAPMessage msg = null;
    try {
        msg = SOAPCommunicator.getInstance().createSOAPMessage(str, false);
    } catch (SOAPException se) {
        SAML2Utils.debug.error(classMethod + "Unable to create a SOAPMessage and add a document ", se);
        return SOAPCommunicator.getInstance().createSOAPFault(SAML2Constants.SERVER_FAULT, "unableToCreateSOAPMessage", null);
    }
    return msg;
}
Also used : KeyProvider(com.sun.identity.saml.xmlsig.KeyProvider) PrivateKey(java.security.PrivateKey) HashMap(java.util.HashMap) Issuer(com.sun.identity.saml2.assertion.Issuer) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) Element(org.w3c.dom.Element) SOAPConnection(javax.xml.soap.SOAPConnection) SOAPMessage(javax.xml.soap.SOAPMessage) StatusCode(com.sun.identity.saml2.protocol.StatusCode) ArtifactResolve(com.sun.identity.saml2.protocol.ArtifactResolve) SOAPException(javax.xml.soap.SOAPException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) Status(com.sun.identity.saml2.protocol.Status) OrderedSet(com.sun.identity.shared.datastruct.OrderedSet) X509Certificate(java.security.cert.X509Certificate) Artifact(com.sun.identity.saml2.protocol.Artifact) SOAPException(javax.xml.soap.SOAPException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) IOException(java.io.IOException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Date(java.util.Date) Response(com.sun.identity.saml2.protocol.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) ArtifactResponse(com.sun.identity.saml2.protocol.ArtifactResponse) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) ArtifactResponse(com.sun.identity.saml2.protocol.ArtifactResponse) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 12 with OrderedSet

use of com.sun.identity.shared.datastruct.OrderedSet in project OpenAM by OpenRock.

the class DirectoryServicesImpl method getSearchResults.

/**
     * convert search results to a AMSearchResults object TODO: Refactor code
     */
private AMSearchResults getSearchResults(SearchResults results, SortKey skey, String[] attrNames, Collator collator, boolean getAllAttrs) throws UMSException {
    TreeMap tm = null;
    TreeSet tmpTreeSet = null;
    if (skey != null) {
        tm = new TreeMap(collator);
        tmpTreeSet = new TreeSet();
    }
    Set set = new OrderedSet();
    Map map = new HashMap();
    int errorCode = AMSearchResults.SUCCESS;
    try {
        if (results != null) {
            while (results.hasMoreElements()) {
                PersistentObject po = results.next();
                String dn = po.getGuid().toString();
                if (tm != null) {
                    Attr attr = po.getAttribute(skey.attributeName);
                    if (attr != null) {
                        String attrValue = attr.getStringValues()[0];
                        Object obj = tm.get(attrValue);
                        if (obj == null) {
                            tm.put(attrValue, dn);
                        } else if (obj instanceof java.lang.String) {
                            TreeSet tmpSet = new TreeSet();
                            tmpSet.add(obj);
                            tmpSet.add(dn);
                            tm.put(attrValue, tmpSet);
                        } else {
                            ((TreeSet) obj).add(dn);
                        }
                    } else {
                        tmpTreeSet.add(dn);
                    }
                } else {
                    set.add(dn);
                }
                AttrSet attrSet = new AttrSet();
                if (attrNames != null) {
                    // Support for multiple return values
                    attrSet = po.getAttributes(attrNames, true);
                } else {
                    /*
                         * Support for multiple return values when attribute
                         * names are not passed as part of the return
                         * attributes. This boolean check is to make sure user
                         * has set the setAllReturnAttributes flag in
                         * AMSearchControl in order to get all attributes or
                         * not.
                         */
                    if (getAllAttrs) {
                        attrSet = po.getAttributes(po.getAttributeNames(), true);
                    }
                }
                map.put(dn, CommonUtils.attrSetToMap(attrSet));
            }
        }
    } catch (SizeLimitExceededException slee) {
        errorCode = AMSearchResults.SIZE_LIMIT_EXCEEDED;
    } catch (TimeLimitExceededException tlee) {
        errorCode = AMSearchResults.TIME_LIMIT_EXCEEDED;
    }
    Integer count = (Integer) results.get(SearchResults.VLVRESPONSE_CONTENT_COUNT);
    int countValue;
    if (count == null) {
        countValue = AMSearchResults.UNDEFINED_RESULT_COUNT;
    } else {
        countValue = count.intValue();
    }
    if (tm != null) {
        Object[] values = tm.values().toArray();
        int len = values.length;
        if (skey.reverse) {
            for (int i = len - 1; i >= 0; i--) {
                Object obj = values[i];
                if (obj instanceof java.lang.String) {
                    set.add(obj);
                } else {
                    set.addAll((Collection) obj);
                }
            }
        } else {
            for (int i = 0; i < len; i++) {
                Object obj = values[i];
                if (obj instanceof java.lang.String) {
                    set.add(obj);
                } else {
                    set.addAll((Collection) obj);
                }
            }
        }
        Iterator iter = tmpTreeSet.iterator();
        while (iter.hasNext()) {
            set.add(iter.next());
        }
    }
    AMSearchResults searchResults = new AMSearchResults(countValue, set, errorCode, map);
    return searchResults;
}
Also used : OrderedSet(com.sun.identity.shared.datastruct.OrderedSet) Set(java.util.Set) OrderedSet(com.sun.identity.shared.datastruct.OrderedSet) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) AttrSet(com.iplanet.services.ldap.AttrSet) AMHashMap(com.iplanet.am.sdk.AMHashMap) HashMap(java.util.HashMap) PersistentObject(com.iplanet.ums.PersistentObject) TreeMap(java.util.TreeMap) AMSearchResults(com.iplanet.am.sdk.AMSearchResults) Attr(com.iplanet.services.ldap.Attr) AttrSet(com.iplanet.services.ldap.AttrSet) SizeLimitExceededException(com.iplanet.ums.SizeLimitExceededException) TreeSet(java.util.TreeSet) Iterator(java.util.Iterator) AMObject(com.iplanet.am.sdk.AMObject) UMSObject(com.iplanet.ums.UMSObject) PersistentObject(com.iplanet.ums.PersistentObject) TimeLimitExceededException(com.iplanet.ums.TimeLimitExceededException) Map(java.util.Map) AMHashMap(com.iplanet.am.sdk.AMHashMap) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap)

Example 13 with OrderedSet

use of com.sun.identity.shared.datastruct.OrderedSet in project OpenAM by OpenRock.

the class FSSAMLSiteID method getValues.

public Set getValues() {
    Set values = new OrderedSet();
    for (Iterator i = sites.iterator(); i.hasNext(); ) {
        SiteID siteId = (SiteID) i.next();
        values.add(siteId.toString());
    }
    return values;
}
Also used : OrderedSet(com.sun.identity.shared.datastruct.OrderedSet) Set(java.util.Set) OrderedSet(com.sun.identity.shared.datastruct.OrderedSet) Iterator(java.util.Iterator)

Example 14 with OrderedSet

use of com.sun.identity.shared.datastruct.OrderedSet in project OpenAM by OpenRock.

the class FSSAMLSiteIDEditViewBean method handleButton1Request.

protected void handleButton1Request(Map values) throws AMConsoleException {
    FSSAMLServiceViewBean vb = (FSSAMLServiceViewBean) getViewBean(FSSAMLServiceViewBean.class);
    Map mapAttrs = (Map) getPageSessionAttribute(FSSAMLServiceViewBean.PROPERTY_ATTRIBUTE);
    OrderedSet siteIDs = (OrderedSet) mapAttrs.get(FSSAMLServiceViewBean.TABLE_SITE_ID);
    FSSAMLSiteID container = new FSSAMLSiteID(siteIDs);
    int index = Integer.parseInt((String) getPageSessionAttribute(PGATTR_INDEX));
    container.replaceSiteID(index, values);
    mapAttrs.put(FSSAMLServiceViewBean.TABLE_SITE_ID, container.getValues());
    backTrail();
    unlockPageTrailForSwapping();
    setPageSessionAttribute(FSSAMLServiceViewBean.MODIFIED, "1");
    passPgSessionMap(vb);
    vb.setValues();
    vb.forwardTo(getRequestContext());
}
Also used : OrderedSet(com.sun.identity.shared.datastruct.OrderedSet) Map(java.util.Map)

Example 15 with OrderedSet

use of com.sun.identity.shared.datastruct.OrderedSet in project OpenAM by OpenRock.

the class FSSAMLServiceViewBean method setValues.

void setValues() {
    Map attrValues = (Map) getPageSessionAttribute(PROPERTY_ATTRIBUTE);
    FSSAMLServiceModel model = (FSSAMLServiceModel) getModel();
    if (attrValues == null) {
        attrValues = model.getAttributeValues();
    }
    Map displayValues = new HashMap(attrValues.size() * 2);
    // set tables
    for (Iterator iter = attrValues.keySet().iterator(); iter.hasNext(); ) {
        String name = (String) iter.next();
        Set values = (Set) attrValues.get(name);
        if (tabledAttributes.contains(name)) {
            populateTable(name, values);
            OrderedSet ordered = new OrderedSet();
            ordered.addAll(values);
            displayValues.put(name, ordered);
        } else {
            displayValues.put(name, values);
        }
    }
    // set other attributes
    AMPropertySheet ps = (AMPropertySheet) getChild(PROPERTY_ATTRIBUTE);
    ps.setAttributeValues(attrValues, model);
    setPageSessionAttribute(PROPERTY_ATTRIBUTE, (HashMap) displayValues);
}
Also used : OrderedSet(com.sun.identity.shared.datastruct.OrderedSet) HashSet(java.util.HashSet) Set(java.util.Set) OrderedSet(com.sun.identity.shared.datastruct.OrderedSet) HashMap(java.util.HashMap) AMPropertySheet(com.sun.identity.console.base.AMPropertySheet) Iterator(java.util.Iterator) FSSAMLServiceModel(com.sun.identity.console.federation.model.FSSAMLServiceModel) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

OrderedSet (com.sun.identity.shared.datastruct.OrderedSet)87 Map (java.util.Map)52 Set (java.util.Set)36 Iterator (java.util.Iterator)20 HashMap (java.util.HashMap)17 HashSet (java.util.HashSet)16 AMConsoleException (com.sun.identity.console.base.model.AMConsoleException)13 CCActionTableModel (com.sun.web.ui.model.CCActionTableModel)13 CCActionTable (com.sun.web.ui.view.table.CCActionTable)12 AMServiceProfileModel (com.sun.identity.console.base.model.AMServiceProfileModel)6 CaseInsensitiveHashSet (com.sun.identity.common.CaseInsensitiveHashSet)5 ArrayList (java.util.ArrayList)5 LinkedHashSet (java.util.LinkedHashSet)5 SMDiscoveryServiceData (com.sun.identity.console.service.model.SMDiscoveryServiceData)4 List (java.util.List)4 AuthPropertiesModel (com.sun.identity.console.authentication.model.AuthPropertiesModel)3 WSAuthHandlerEntry (com.sun.identity.console.webservices.model.WSAuthHandlerEntry)3 IdRepo (com.sun.identity.idm.IdRepo)3 Issuer (com.sun.identity.saml2.assertion.Issuer)3 SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)3