protected int authenticate(
      long companyId,
      long ldapServerId,
      String emailAddress,
      String screenName,
      long userId,
      String password)
      throws Exception {

    String postfix = LDAPSettingsUtil.getPropertyPostfix(ldapServerId);

    LdapContext ldapContext = PortalLDAPUtil.getContext(ldapServerId, companyId);

    if (ldapContext == null) {
      return FAILURE;
    }

    try {
      String baseDN = PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_BASE_DN + postfix);

      //  Process LDAP auth search filter

      String filter =
          LDAPSettingsUtil.getAuthSearchFilter(
              ldapServerId, companyId, emailAddress, screenName, String.valueOf(userId));

      Properties userMappings = LDAPSettingsUtil.getUserMappings(ldapServerId, companyId);

      String userMappingsScreenName =
          GetterUtil.getString(userMappings.getProperty("screenName")).toLowerCase();

      SearchControls searchControls =
          new SearchControls(
              SearchControls.SUBTREE_SCOPE,
              1,
              0,
              new String[] {userMappingsScreenName},
              false,
              false);

      NamingEnumeration<SearchResult> enu = ldapContext.search(baseDN, filter, searchControls);

      if (enu.hasMoreElements()) {
        if (_log.isDebugEnabled()) {
          _log.debug("Search filter returned at least one result");
        }

        SearchResult result = enu.nextElement();

        String fullUserDN = PortalLDAPUtil.getNameInNamespace(ldapServerId, companyId, result);

        Attributes attributes =
            PortalLDAPUtil.getUserAttributes(ldapServerId, companyId, ldapContext, fullUserDN);

        LDAPAuthResult ldapAuthResult = null;

        if (PropsValues.LDAP_IMPORT_USER_PASSWORD_ENABLED) {
          ldapAuthResult = authenticate(ldapContext, companyId, attributes, fullUserDN, password);

          // Process LDAP failure codes

          String errorMessage = ldapAuthResult.getErrorMessage();

          if (errorMessage != null) {
            if (errorMessage.indexOf(
                    PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_ERROR_USER_LOCKOUT))
                != -1) {

              throw new UserLockoutException();
            } else if (errorMessage.indexOf(
                    PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_ERROR_PASSWORD_EXPIRED))
                != -1) {

              throw new PasswordExpiredException();
            }
          }

          if (!ldapAuthResult.isAuthenticated() && PropsValues.LDAP_IMPORT_USER_PASSWORD_ENABLED) {

            return FAILURE;
          }
        }

        // Get user or create from LDAP

        User user =
            PortalLDAPImporterUtil.importLDAPUser(
                ldapServerId, companyId, ldapContext, attributes, password);

        // Process LDAP success codes

        if (ldapAuthResult != null) {
          String resultCode = ldapAuthResult.getResponseControl();

          if (resultCode.equals(LDAPAuth.RESULT_PASSWORD_RESET)) {
            UserLocalServiceUtil.updatePasswordReset(user.getUserId(), true);
          }
        }
      } else {
        if (_log.isDebugEnabled()) {
          _log.debug("Search filter did not return any results");
        }

        return DNE;
      }

      enu.close();
    } catch (Exception e) {
      if (e instanceof PasswordExpiredException || e instanceof UserLockoutException) {

        throw e;
      }

      _log.error("Problem accessing LDAP server", e);

      return FAILURE;
    } finally {
      if (ldapContext != null) {
        ldapContext.close();
      }
    }

    return SUCCESS;
  }
Ejemplo n.º 2
0
  protected int authenticate(
      long ldapServerId,
      long companyId,
      String emailAddress,
      String screenName,
      long userId,
      String password)
      throws Exception {

    LdapContext ldapContext = _portalLDAP.getContext(ldapServerId, companyId);

    if (ldapContext == null) {
      return FAILURE;
    }

    NamingEnumeration<SearchResult> enu = null;

    try {
      LDAPServerConfiguration ldapServerConfiguration =
          _ldapServerConfigurationProvider.getConfiguration(companyId, ldapServerId);

      String baseDN = ldapServerConfiguration.baseDN();

      //  Process LDAP auth search filter

      String filter =
          _ldapSettings.getAuthSearchFilter(
              ldapServerId, companyId, emailAddress, screenName, String.valueOf(userId));

      Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId);

      String userMappingsScreenName = GetterUtil.getString(userMappings.getProperty("screenName"));

      userMappingsScreenName = StringUtil.toLowerCase(userMappingsScreenName);

      SearchControls searchControls =
          new SearchControls(
              SearchControls.SUBTREE_SCOPE,
              1,
              0,
              new String[] {userMappingsScreenName},
              false,
              false);

      enu = ldapContext.search(baseDN, filter, searchControls);

      if (enu.hasMoreElements()) {
        if (_log.isDebugEnabled()) {
          _log.debug("Search filter returned at least one result");
        }

        SearchResult result = enu.nextElement();

        String fullUserDN = _portalLDAP.getNameInNamespace(ldapServerId, companyId, result);

        Attributes attributes =
            _portalLDAP.getUserAttributes(ldapServerId, companyId, ldapContext, fullUserDN);

        // Get user or create from LDAP

        User user =
            _ldapUserImporter.importUser(
                ldapServerId, companyId, ldapContext, attributes, password);

        // Authenticate

        LDAPAuthResult ldapAuthResult =
            authenticate(ldapContext, companyId, attributes, fullUserDN, password);

        // Process LDAP failure codes

        String errorMessage = ldapAuthResult.getErrorMessage();

        if (errorMessage != null) {
          SystemLDAPConfiguration systemLDAPConfiguration =
              _systemLDAPConfigurationProvider.getConfiguration(companyId);

          int pos = errorMessage.indexOf(systemLDAPConfiguration.errorUserLockout());

          if (pos != -1) {
            throw new UserLockoutException.LDAPLockout(fullUserDN, errorMessage);
          }

          pos = errorMessage.indexOf(systemLDAPConfiguration.errorPasswordExpired());

          if (pos != -1) {
            throw new PasswordExpiredException();
          }
        }

        if (!ldapAuthResult.isAuthenticated()) {
          return FAILURE;
        }

        // Process LDAP success codes

        String resultCode = ldapAuthResult.getResponseControl();

        if (resultCode.equals(LDAPAuth.RESULT_PASSWORD_RESET)) {
          _userLocalService.updatePasswordReset(user.getUserId(), true);
        }
      } else {
        if (_log.isDebugEnabled()) {
          _log.debug("Search filter did not return any results");
        }

        return DNE;
      }
    } catch (Exception e) {
      if (e instanceof LDAPFilterException
          || e instanceof PasswordExpiredException
          || e instanceof UserLockoutException) {

        throw e;
      }

      _log.error("Problem accessing LDAP server", e);

      return FAILURE;
    } finally {
      if (enu != null) {
        enu.close();
      }

      if (ldapContext != null) {
        ldapContext.close();
      }
    }

    return SUCCESS;
  }
  protected LDAPAuthResult authenticate(
      LdapContext ctx, long companyId, Attributes attributes, String userDN, String password)
      throws Exception {

    LDAPAuthResult ldapAuthResult = new LDAPAuthResult();

    // Check passwords by either doing a comparison between the passwords or
    // by binding to the LDAP server. If using LDAP password policies, bind
    // auth method must be used in order to get the result control codes.

    String authMethod = PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_AUTH_METHOD);
    InitialLdapContext innerCtx = null;

    if (authMethod.equals(AUTH_METHOD_BIND)) {
      try {
        Hashtable<String, Object> env = (Hashtable<String, Object>) ctx.getEnvironment();

        env.put(Context.SECURITY_PRINCIPAL, userDN);
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put(Context.REFERRAL, PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_REFERRAL));

        // Do not use pooling because principal changes

        env.put("com.sun.jndi.ldap.connect.pool", "false");

        innerCtx = new InitialLdapContext(env, null);

        // Get LDAP bind results

        Control[] responseControls = innerCtx.getResponseControls();

        ldapAuthResult.setAuthenticated(true);
        ldapAuthResult.setResponseControl(responseControls);
      } catch (Exception e) {
        if (_log.isDebugEnabled()) {
          _log.debug(
              "Failed to bind to the LDAP server with userDN "
                  + userDN
                  + " and password "
                  + password);
        }

        _log.error("Failed to bind to the LDAP server", e);

        ldapAuthResult.setAuthenticated(false);
        ldapAuthResult.setErrorMessage(e.getMessage());
      } finally {
        if (innerCtx != null) {
          innerCtx.close();
        }
      }
    } else if (authMethod.equals(AUTH_METHOD_PASSWORD_COMPARE)) {
      Attribute userPassword = attributes.get("userPassword");

      if (userPassword != null) {
        String ldapPassword = new String((byte[]) userPassword.get());

        String encryptedPassword = password;

        String algorithm =
            PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_AUTH_PASSWORD_ENCRYPTION_ALGORITHM);

        if (Validator.isNotNull(algorithm)) {
          encryptedPassword =
              "******" + algorithm + "}" + PwdEncryptor.encrypt(algorithm, password, ldapPassword);
        }

        if (ldapPassword.equals(encryptedPassword)) {
          ldapAuthResult.setAuthenticated(true);
        } else {
          ldapAuthResult.setAuthenticated(false);

          if (_log.isWarnEnabled()) {
            _log.warn("Passwords do not match for userDN " + userDN);
          }
        }
      }
    }

    return ldapAuthResult;
  }
Ejemplo n.º 4
0
  protected LDAPAuthResult authenticate(
      LdapContext ctx, long companyId, Attributes attributes, String userDN, String password)
      throws Exception {

    LDAPAuthResult ldapAuthResult = null;

    // Check passwords by either doing a comparison between the passwords or
    // by binding to the LDAP server. If using LDAP password policies, bind
    // auth method must be used in order to get the result control codes.

    LDAPAuthConfiguration ldapAuthConfiguration =
        _ldapAuthConfigurationProvider.getConfiguration(companyId);

    String authMethod = ldapAuthConfiguration.method();

    SystemLDAPConfiguration systemLDAPConfiguration =
        _systemLDAPConfigurationProvider.getConfiguration(companyId);

    if (authMethod.equals(AUTH_METHOD_BIND)) {
      Hashtable<String, Object> env = (Hashtable<String, Object>) ctx.getEnvironment();

      env.put(Context.REFERRAL, systemLDAPConfiguration.referral());
      env.put(Context.SECURITY_CREDENTIALS, password);
      env.put(Context.SECURITY_PRINCIPAL, userDN);

      // Do not use pooling because principal changes

      env.put("com.sun.jndi.ldap.connect.pool", "false");

      ldapAuthResult = getFailedLDAPAuthResult(env);

      if (ldapAuthResult != null) {
        return ldapAuthResult;
      }

      ldapAuthResult = new LDAPAuthResult();

      InitialLdapContext initialLdapContext = null;

      try {
        initialLdapContext = new InitialLdapContext(env, null);

        // Get LDAP bind results

        Control[] responseControls = initialLdapContext.getResponseControls();

        ldapAuthResult.setAuthenticated(true);
        ldapAuthResult.setResponseControl(responseControls);
      } catch (Exception e) {
        if (_log.isDebugEnabled()) {
          _log.debug(
              "Failed to bind to the LDAP server with userDN "
                  + userDN
                  + " and password "
                  + password,
              e);
        }

        ldapAuthResult.setAuthenticated(false);
        ldapAuthResult.setErrorMessage(e.getMessage());

        setFailedLDAPAuthResult(env, ldapAuthResult);
      } finally {
        if (initialLdapContext != null) {
          initialLdapContext.close();
        }
      }
    } else if (authMethod.equals(AUTH_METHOD_PASSWORD_COMPARE)) {
      ldapAuthResult = new LDAPAuthResult();

      Attribute userPassword = attributes.get("userPassword");

      if (userPassword != null) {
        String ldapPassword = new String((byte[]) userPassword.get());

        String encryptedPassword = password;

        String algorithm = ldapAuthConfiguration.passwordEncryptionAlgorithm();

        if (Validator.isNotNull(algorithm)) {
          encryptedPassword = _passwordEncryptor.encrypt(algorithm, password, ldapPassword);
        }

        if (ldapPassword.equals(encryptedPassword)) {
          ldapAuthResult.setAuthenticated(true);
        } else {
          ldapAuthResult.setAuthenticated(false);

          if (_log.isDebugEnabled()) {
            _log.debug("Passwords do not match for userDN " + userDN);
          }
        }
      }
    }

    return ldapAuthResult;
  }