aboutsummaryrefslogtreecommitdiffstats
path: root/server/sonar-auth-ldap/src/main/java/org/sonar/auth/ldap/DefaultLdapAuthenticator.java
blob: b5f0bc03e28f6d49ef3f31fcef176043b481086a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
/*
 * SonarQube
 * Copyright (C) 2009-2025 SonarSource SA
 * mailto:info AT sonarsource DOT com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package org.sonar.auth.ldap;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchResult;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.server.ServerSide;

/**
 * @author Evgeny Mandrikov
 */
@ServerSide
public class DefaultLdapAuthenticator implements LdapAuthenticator {

  private static final Pattern SANITIZE_PATTERN = Pattern.compile("[\n\r]");

  private static final Logger LOG = LoggerFactory.getLogger(DefaultLdapAuthenticator.class);
  private final Map<String, LdapContextFactory> contextFactories;
  private final Map<String, LdapUserMapping> userMappings;

  public DefaultLdapAuthenticator(Map<String, LdapContextFactory> contextFactories, Map<String, LdapUserMapping> userMappings) {
    this.contextFactories = contextFactories;
    this.userMappings = userMappings;
  }

  @Override
  public LdapAuthenticationResult doAuthenticate(Context context) {
    return authenticate(context.getUsername(), context.getPassword());
  }

  /**
   * Authenticate the user against LDAP servers until first success.
   *
   * @param login    The login to use.
   * @param password The password to use.
   * @return false if specified user cannot be authenticated with specified password on any LDAP server
   */
  private LdapAuthenticationResult authenticate(String login, String password) {
    for (Map.Entry<String, LdapUserMapping> ldapEntry : userMappings.entrySet()) {
      String ldapKey = ldapEntry.getKey();
      LdapUserMapping ldapUserMapping = ldapEntry.getValue();
      LdapContextFactory ldapContextFactory = contextFactories.get(ldapKey);
      final String principal;
      if (ldapContextFactory.isSasl()) {
        principal = login;
      } else {
        SearchResult result = findUser(login, ldapKey, ldapUserMapping, ldapContextFactory);
        if (result == null) {
          continue;
        }
        principal = result.getNameInNamespace();
      }
      boolean passwordValid = isPasswordValid(password, ldapKey, ldapContextFactory, principal);
      if (passwordValid) {
        return LdapAuthenticationResult.success(ldapKey);
      }
    }
    LOG.atDebug().log("User {} not found", getSanitizedLogin(login));
    return LdapAuthenticationResult.failed();
  }

  private static SearchResult findUser(String login, String ldapKey, LdapUserMapping ldapUserMapping, LdapContextFactory ldapContextFactory) {
    SearchResult result;
    try {
      result = ldapUserMapping.createSearch(ldapContextFactory, login).findUnique();
    } catch (NamingException e) {
      LOG.atDebug().log("User {} not found in server <{}>: {}", getSanitizedLogin(login), ldapKey, e.toString());
      return null;
    }
    if (result == null) {
      LOG.atDebug().log("User {} not found in <{}>", getSanitizedLogin(login), ldapKey);
      return null;
    }
    return result;
  }

  private static String getSanitizedLogin(String login) {
    Matcher matcher = SANITIZE_PATTERN.matcher(login);
    return matcher.replaceAll("_");
  }

  private boolean isPasswordValid(String password, String ldapKey, LdapContextFactory ldapContextFactory, String principal) {
    if (ldapContextFactory.isGssapi()) {
      return checkPasswordUsingGssapi(principal, password, ldapKey);
    }
    return checkPasswordUsingBind(principal, password, ldapKey);
  }

  private boolean checkPasswordUsingBind(String principal, String password, String ldapKey) {
    if (StringUtils.isEmpty(password)) {
      LOG.debug("Password is blank.");
      return false;
    }
    InitialDirContext context = null;
    try {
      context = contextFactories.get(ldapKey).createUserContext(principal, password);
      return true;
    } catch (NamingException e) {
      LOG.debug("Password not valid for user {} in server {}: {}", principal, ldapKey, e.getMessage());
      return false;
    } finally {
      ContextHelper.closeQuietly(context);
    }
  }

  private boolean checkPasswordUsingGssapi(String principal, String password, String ldapKey) {
    // Use our custom configuration to avoid reliance on external config
    Configuration.setConfiguration(new Krb5LoginConfiguration());
    LoginContext lc;
    try {
      lc = new LoginContext(getClass().getName(), new CallbackHandlerImpl(principal, password));
      lc.login();
    } catch (LoginException e) {
      // Bad username: Client not found in Kerberos database
      // Bad password: Integrity check on decrypted field failed
      LOG.debug("Password not valid for {} in server {}: {}", principal, ldapKey, e.getMessage());
      return false;
    }
    try {
      lc.logout();
    } catch (LoginException e) {
      LOG.warn("Logout fails", e);
    }
    return true;
  }

}