Search in sources :

Example 56 with SAML2Exception

use of com.sun.identity.saml2.common.SAML2Exception in project OpenAM by OpenRock.

the class DefaultLibrarySPAccountMapper method getAutoFedUser.

/**
     * Returns user for the auto federate attribute.
     *
     * @param realm Realm name.
     * @param entityID Hosted <code>EntityID</code>.
     * @param assertion <code>Assertion</code> from the identity provider.
     * @return Auto federation mapped user from the assertion auto federation <code>AttributeStatement</code>. if the
     * statement does not have the auto federation attribute then the NameID value will be used if use NameID as SP user
     * ID is enabled, otherwise null.
     */
protected String getAutoFedUser(String realm, String entityID, Assertion assertion, String decryptedNameID, Set<PrivateKey> decryptionKeys) throws SAML2Exception {
    if (!isAutoFedEnabled(realm, entityID)) {
        if (debug.messageEnabled()) {
            debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Auto federation is disabled.");
        }
        return null;
    }
    String autoFedAttribute = getAttribute(realm, entityID, SAML2Constants.AUTO_FED_ATTRIBUTE);
    if (autoFedAttribute == null || autoFedAttribute.isEmpty()) {
        debug.error("DefaultLibrarySPAccountMapper.getAutoFedUser: " + "Auto federation is enabled but the auto federation attribute is not configured.");
        return null;
    }
    if (debug.messageEnabled()) {
        debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Auto federation attribute is set to: " + autoFedAttribute);
    }
    Set<String> autoFedAttributeValue = null;
    List<AttributeStatement> attributeStatements = assertion.getAttributeStatements();
    if (attributeStatements == null || attributeStatements.isEmpty()) {
        if (debug.messageEnabled()) {
            debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: " + "Assertion does not have any attribute statements.");
        }
    } else {
        for (AttributeStatement statement : attributeStatements) {
            autoFedAttributeValue = getAttribute(statement, autoFedAttribute, decryptionKeys);
            if (autoFedAttributeValue != null && !autoFedAttributeValue.isEmpty()) {
                if (debug.messageEnabled()) {
                    debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: " + "Found auto federation attribute value in Assertion: " + autoFedAttributeValue);
                }
                break;
            }
        }
    }
    if (autoFedAttributeValue == null || autoFedAttributeValue.isEmpty()) {
        if (debug.messageEnabled()) {
            debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Auto federation attribute is not specified" + " as an attribute.");
        }
        if (!useNameIDAsSPUserID(realm, entityID)) {
            if (debug.messageEnabled()) {
                debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: NameID as SP UserID was not enabled " + " and auto federation attribute " + autoFedAttribute + " was not found in the Assertion");
            }
            return null;
        } else {
            if (debug.messageEnabled()) {
                debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Trying now to autofederate with nameID" + ", nameID =" + decryptedNameID);
            }
            autoFedAttributeValue = CollectionUtils.asSet(decryptedNameID);
        }
    }
    String autoFedMapAttribute = null;
    DefaultSPAttributeMapper attributeMapper = new DefaultSPAttributeMapper();
    Map<String, String> attributeMap = attributeMapper.getConfigAttributeMap(realm, entityID, SP);
    if (attributeMap == null || attributeMap.isEmpty()) {
        if (debug.messageEnabled()) {
            debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: attribute map is not configured.");
        }
    } else {
        autoFedMapAttribute = attributeMap.get(autoFedAttribute);
    }
    if (autoFedMapAttribute == null) {
        if (debug.messageEnabled()) {
            debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: " + "Auto federation attribute map is not specified in config.");
        }
        // assume it is the same as the auto fed attribute name 
        autoFedMapAttribute = autoFedAttribute;
    }
    try {
        Map<String, Set<String>> map = new HashMap<>(1);
        map.put(autoFedMapAttribute, autoFedAttributeValue);
        if (debug.messageEnabled()) {
            debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Search map: " + map);
        }
        String userId = dsProvider.getUserID(realm, map);
        if (userId != null && !userId.isEmpty()) {
            return userId;
        } else {
            // return auto-federation attribute value as uid 
            if (isDynamicalOrIgnoredProfile(realm)) {
                if (debug.messageEnabled()) {
                    debug.message("DefaultLibrarySPAccountMapper: dynamical user creation or ignore profile " + "enabled : uid=" + autoFedAttributeValue);
                }
                // return the first value as uid
                return autoFedAttributeValue.iterator().next();
            }
        }
    } catch (DataStoreProviderException dse) {
        if (debug.warningEnabled()) {
            debug.warning("DefaultLibrarySPAccountMapper.getAutoFedUser: Datastore provider exception", dse);
        }
    }
    return null;
}
Also used : DataStoreProviderException(com.sun.identity.plugin.datastore.DataStoreProviderException) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) AttributeStatement(com.sun.identity.saml2.assertion.AttributeStatement)

Example 57 with SAML2Exception

use of com.sun.identity.saml2.common.SAML2Exception in project OpenAM by OpenRock.

the class DefaultLibrarySPAccountMapper method getAttribute.

private Set<String> getAttribute(AttributeStatement statement, String attributeName, Set<PrivateKey> decryptionKeys) {
    if (debug.messageEnabled()) {
        debug.message("DefaultLibrarySPAccountMapper.getAttribute: attribute Name =" + attributeName);
    }
    // check it if the attribute needs to be encrypted?
    List<Attribute> list = statement.getAttribute();
    List<EncryptedAttribute> encList = statement.getEncryptedAttribute();
    if (encList != null && !encList.isEmpty()) {
        // a new list to hold the union of clear and encrypted attributes
        List<Attribute> allList = new ArrayList<>();
        if (list != null) {
            allList.addAll(list);
        }
        list = allList;
        for (EncryptedAttribute encryptedAttribute : encList) {
            try {
                list.add(encryptedAttribute.decrypt(decryptionKeys));
            } catch (SAML2Exception se) {
                debug.error("Decryption error:", se);
                return null;
            }
        }
    }
    for (Attribute attribute : list) {
        if (!attributeName.equalsIgnoreCase(attribute.getName())) {
            continue;
        }
        List<String> values = attribute.getAttributeValueString();
        if (values == null || values.isEmpty()) {
            return null;
        }
        return new HashSet<>(values);
    }
    return null;
}
Also used : EncryptedAttribute(com.sun.identity.saml2.assertion.EncryptedAttribute) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Attribute(com.sun.identity.saml2.assertion.Attribute) EncryptedAttribute(com.sun.identity.saml2.assertion.EncryptedAttribute) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet)

Example 58 with SAML2Exception

use of com.sun.identity.saml2.common.SAML2Exception in project OpenAM by OpenRock.

the class DoManageNameID method processPOSTRequest.

public static void processPOSTRequest(HttpServletRequest request, HttpServletResponse response, Map paramsMap) throws SAML2Exception, IOException, SOAPException, SessionException, ServletException {
    String classMethod = "DoManageNameID.processPOSTRequest:";
    String samlRequest = request.getParameter(SAML2Constants.SAML_REQUEST);
    if (samlRequest == null) {
        SAMLUtils.sendError(request, response, response.SC_BAD_REQUEST, "MissingSAMLRequest", SAML2Utils.bundle.getString("MissingSAMLRequest"));
        throw new SAML2Exception(SAML2Utils.bundle.getString("MissingSAMLRequest"));
    }
    String metaAlias = SAML2MetaUtils.getMetaAliasByUri(request.getRequestURI());
    if (metaAlias == null) {
        logError("MetaAliasNotFound", LogUtil.MISSING_META_ALIAS, metaAlias);
        throw new SAML2Exception(SAML2Utils.bundle.getString("MetaAliasNotFound"));
    }
    String realm = SAML2MetaUtils.getRealmByMetaAlias(metaAlias);
    String hostEntityID = metaManager.getEntityByMetaAlias(metaAlias);
    String hostEntityRole = SAML2Utils.getHostEntityRole(paramsMap);
    boolean isSupported = false;
    if (SAML2Constants.IDP_ROLE.equals(hostEntityRole)) {
        isSupported = SAML2Utils.isIDPProfileBindingSupported(realm, hostEntityID, SAML2Constants.MNI_SERVICE, SAML2Constants.HTTP_POST);
    } else {
        isSupported = SAML2Utils.isSPProfileBindingSupported(realm, hostEntityID, SAML2Constants.MNI_SERVICE, SAML2Constants.HTTP_POST);
    }
    if (!isSupported) {
        debug.error(classMethod + "MNI binding: POST is not supported for " + hostEntityID);
        String[] data = { hostEntityID, SAML2Constants.HTTP_POST };
        LogUtil.error(Level.INFO, LogUtil.BINDING_NOT_SUPPORTED, data, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("unsupportedBinding"));
    }
    ManageNameIDRequest mniRequest = null;
    ByteArrayInputStream bis = null;
    try {
        byte[] raw = Base64.decode(samlRequest);
        if (raw != null) {
            bis = new ByteArrayInputStream(raw);
            Document doc = XMLUtils.toDOMDocument(bis, SAML2Utils.debug);
            if (doc != null) {
                mniRequest = ProtocolFactory.getInstance().createManageNameIDRequest(doc.getDocumentElement());
            }
        }
    } catch (SAML2Exception se) {
        debug.error("DoManageNameID.processPOSTRequest:", se);
        SAMLUtils.sendError(request, response, response.SC_BAD_REQUEST, "nullDecodedStrFromSamlResponse", SAML2Utils.bundle.getString("nullDecodedStrFromSamlResponse") + " " + se.getMessage());
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullDecodedStrFromSamlResponse"));
    } catch (Exception e) {
        debug.error("DoManageNameID.processPOSTRequest:", e);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "nullDecodedStrFromSamlResponse", SAML2Utils.bundle.getString("nullDecodedStrFromSamlResponse") + " " + e.getMessage());
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullDecodedStrFromSamlResponse"));
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (Exception ie) {
                if (debug.messageEnabled()) {
                    debug.message("DoManageNameID.processPOSTRequest:", ie);
                }
            }
        }
    }
    if (mniRequest != null) {
        String remoteEntityID = mniRequest.getIssuer().getValue();
        if (remoteEntityID == null) {
            logError("nullRemoteEntityID", LogUtil.MISSING_ENTITY, metaAlias);
            throw new SAML2Exception(SAML2Utils.bundle.getString("nullRemoteEntityID"));
        }
        if (debug.messageEnabled()) {
            debug.message("DoManageNameID.processPOSTRequest: " + "Meta Alias is : " + metaAlias);
            debug.message("DoManageNameID.processPOSTRequest: " + "Host EntityID is : " + hostEntityID);
            debug.message("DoManageNameID.processPOSTRequest: " + "Remote EntityID is : " + remoteEntityID);
        }
        String dest = mniRequest.getDestination();
        boolean valid = verifyMNIRequest(mniRequest, realm, remoteEntityID, hostEntityID, hostEntityRole, dest);
        if (!valid) {
            logError("invalidSignInRequest", LogUtil.MNI_REQUEST_INVALID_SIGNATURE, metaAlias);
            throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignInRequest"));
        }
        ManageNameIDServiceElement mniService = getMNIServiceElement(realm, remoteEntityID, hostEntityRole, SAML2Constants.HTTP_POST);
        String mniURL = mniService.getResponseLocation();
        if (mniURL == null) {
            mniURL = mniService.getLocation();
        }
        ///common for post, redirect, soap
        ManageNameIDResponse mniResponse = processManageNameIDRequest(mniRequest, metaAlias, remoteEntityID, paramsMap, null, SAML2Constants.HTTP_POST, request, response);
        signMNIResponse(mniResponse, realm, hostEntityID, hostEntityRole, remoteEntityID);
        //send MNI Response by POST
        String mniRespString = mniResponse.toXMLString(true, true);
        String encMsg = SAML2Utils.encodeForPOST(mniRespString);
        String relayState = request.getParameter(SAML2Constants.RELAY_STATE);
        try {
            SAML2Utils.postToTarget(request, response, "SAMLResponse", encMsg, "RelayState", relayState, mniURL);
        } catch (Exception e) {
            debug.message("DoManageNameID.processPOSTRequest:", e);
            throw new SAML2Exception("Error posting to target");
        }
    }
    return;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) ManageNameIDServiceElement(com.sun.identity.saml2.jaxb.metadata.ManageNameIDServiceElement) ManageNameIDRequest(com.sun.identity.saml2.protocol.ManageNameIDRequest) ByteArrayInputStream(java.io.ByteArrayInputStream) Document(org.w3c.dom.Document) ManageNameIDResponse(com.sun.identity.saml2.protocol.ManageNameIDResponse) ServletException(javax.servlet.ServletException) SOAPException(javax.xml.soap.SOAPException) SessionException(com.sun.identity.plugin.session.SessionException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) IOException(java.io.IOException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception)

Example 59 with SAML2Exception

use of com.sun.identity.saml2.common.SAML2Exception in project OpenAM by OpenRock.

the class DoManageNameID method setNameIDForMNIRequest.

private static void setNameIDForMNIRequest(ManageNameIDRequest mniRequest, NameID nameID, boolean changeID, String realm, String hostEntity, String hostEntityRole, String remoteEntity) throws SAML2Exception {
    String method = "DoManageNameID.setNameIDForMNIRequest: ";
    boolean needEncryptIt = false;
    if (hostEntityRole.equalsIgnoreCase(SAML2Constants.IDP_ROLE)) {
        needEncryptIt = SAML2Utils.getWantNameIDEncrypted(realm, remoteEntity, SAML2Constants.SP_ROLE);
    } else {
        needEncryptIt = SAML2Utils.getWantNameIDEncrypted(realm, remoteEntity, SAML2Constants.IDP_ROLE);
    }
    NewID newID = null;
    if (changeID) {
        String newIDValue = SAML2Utils.createNameIdentifier();
        newID = ProtocolFactory.getInstance().createNewID(newIDValue);
        mniRequest.setNewID(newID);
    }
    mniRequest.setNameID(nameID);
    if (!needEncryptIt) {
        if (debug.messageEnabled()) {
            debug.message(method + "NamID doesn't need to be encrypted.");
        }
        return;
    }
    EncInfo encInfo = null;
    if (hostEntityRole.equalsIgnoreCase(SAML2Constants.IDP_ROLE)) {
        SPSSODescriptorElement spSSODesc = metaManager.getSPSSODescriptor(realm, remoteEntity);
        encInfo = KeyUtil.getEncInfo(spSSODesc, remoteEntity, SAML2Constants.SP_ROLE);
    } else {
        IDPSSODescriptorElement idpSSODesc = metaManager.getIDPSSODescriptor(realm, remoteEntity);
        encInfo = KeyUtil.getEncInfo(idpSSODesc, remoteEntity, SAML2Constants.IDP_ROLE);
    }
    if (debug.messageEnabled()) {
        debug.message(method + "realm is : " + realm);
        debug.message(method + "hostEntity is : " + hostEntity);
        debug.message(method + "Host Entity role is : " + hostEntityRole);
        debug.message(method + "remoteEntity is : " + remoteEntity);
    }
    if (encInfo == null) {
        logError("UnableToFindEncryptKeyInfo", LogUtil.METADATA_ERROR, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("UnableToFindEncryptKeyInfo"));
    }
    EncryptedID encryptedID = nameID.encrypt(encInfo.getWrappingKey(), encInfo.getDataEncAlgorithm(), encInfo.getDataEncStrength(), remoteEntity);
    // This non-encrypted NameID will be removed just 
    // after saveMNIRequestInfo and just before it send to 
    mniRequest.setEncryptedID(encryptedID);
    if (newID != null) {
        NewEncryptedID newEncID = newID.encrypt(encInfo.getWrappingKey(), encInfo.getDataEncAlgorithm(), encInfo.getDataEncStrength(), remoteEntity);
        // This non-encrypted newID will be removed just 
        // after saveMNIRequestInfo and just before it send to 
        mniRequest.setNewEncryptedID(newEncID);
    }
}
Also used : EncInfo(com.sun.identity.saml2.key.EncInfo) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) NewID(com.sun.identity.saml2.protocol.NewID) NewEncryptedID(com.sun.identity.saml2.protocol.NewEncryptedID) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) NewEncryptedID(com.sun.identity.saml2.protocol.NewEncryptedID) EncryptedID(com.sun.identity.saml2.assertion.EncryptedID) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Example 60 with SAML2Exception

use of com.sun.identity.saml2.common.SAML2Exception in project OpenAM by OpenRock.

the class DoManageNameID method getMNIBindingInfo.

/**
     * Returns binding information of MNI Service for remote entity 
     * from request or meta configuration.
     *
     * @param request the HttpServletRequest.
     * @param metaAlias entityID of hosted entity.
     * @param hostEntityRole Role of hosted entity.
     * @param remoteEntityID entityID of remote entity.
     * @return return true if the processing is successful.
     * @throws SAML2Exception if no binding information is configured.
     */
public static String getMNIBindingInfo(HttpServletRequest request, String metaAlias, String hostEntityRole, String remoteEntityID) throws SAML2Exception {
    String binding = request.getParameter(SAML2Constants.BINDING);
    try {
        if (binding == null) {
            String realm = SAML2MetaUtils.getRealmByMetaAlias(metaAlias);
            ManageNameIDServiceElement mniService = getMNIServiceElement(realm, remoteEntityID, hostEntityRole, null);
            if (mniService != null) {
                binding = mniService.getBinding();
            }
        }
    } catch (SessionException e) {
        logError("invalidSSOToken", LogUtil.INVALID_SSOTOKEN, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
    }
    if (binding == null) {
        logError("UnableTofindBinding", LogUtil.METADATA_ERROR, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("UnableTofindBinding"));
    }
    return binding;
}
Also used : ManageNameIDServiceElement(com.sun.identity.saml2.jaxb.metadata.ManageNameIDServiceElement) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) SessionException(com.sun.identity.plugin.session.SessionException)

Aggregations

SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)275 ArrayList (java.util.ArrayList)92 List (java.util.List)86 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)72 Element (org.w3c.dom.Element)64 SessionException (com.sun.identity.plugin.session.SessionException)56 IOException (java.io.IOException)51 SPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement)44 Map (java.util.Map)44 HashMap (java.util.HashMap)43 Iterator (java.util.Iterator)43 Issuer (com.sun.identity.saml2.assertion.Issuer)42 Date (java.util.Date)40 SOAPException (javax.xml.soap.SOAPException)39 SAML2TokenRepositoryException (org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)39 X509Certificate (java.security.cert.X509Certificate)36 NodeList (org.w3c.dom.NodeList)36 IDPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)35 Node (org.w3c.dom.Node)34 Response (com.sun.identity.saml2.protocol.Response)30