James Moger
2014-09-25 54cc7d7c2483d7ca100a5db47f4e1e98bd97c7fe
commit | author | age
04a985 1 /*
JM 2  * Copyright 2013 gitblit.com.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.gitblit.manager;
17
18 import java.nio.charset.Charset;
19 import java.security.Principal;
20 import java.text.MessageFormat;
21 import java.util.ArrayList;
22 import java.util.HashMap;
23 import java.util.List;
24 import java.util.Map;
7ab32b 25 import java.util.concurrent.TimeUnit;
04a985 26
JM 27 import javax.servlet.http.Cookie;
28 import javax.servlet.http.HttpServletRequest;
29 import javax.servlet.http.HttpServletResponse;
30
31 import org.apache.wicket.RequestCycle;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 import com.gitblit.Constants;
36 import com.gitblit.Constants.AccountType;
37 import com.gitblit.Constants.AuthenticationType;
38 import com.gitblit.IStoredSettings;
39 import com.gitblit.Keys;
40 import com.gitblit.auth.AuthenticationProvider;
41 import com.gitblit.auth.AuthenticationProvider.UsernamePasswordAuthenticationProvider;
42 import com.gitblit.auth.HtpasswdAuthProvider;
43 import com.gitblit.auth.LdapAuthProvider;
44 import com.gitblit.auth.PAMAuthProvider;
45 import com.gitblit.auth.RedmineAuthProvider;
46 import com.gitblit.auth.SalesforceAuthProvider;
47 import com.gitblit.auth.WindowsAuthProvider;
48 import com.gitblit.models.TeamModel;
49 import com.gitblit.models.UserModel;
bcc8a0 50 import com.gitblit.transport.ssh.SshKey;
04a985 51 import com.gitblit.utils.Base64;
JM 52 import com.gitblit.utils.HttpUtils;
53 import com.gitblit.utils.StringUtils;
54 import com.gitblit.utils.X509Utils.X509Metadata;
55 import com.gitblit.wicket.GitBlitWebSession;
56
57 /**
58  * The authentication manager handles user login & logout.
59  *
60  * @author James Moger
61  *
62  */
63 public class AuthenticationManager implements IAuthenticationManager {
64
65     private final Logger logger = LoggerFactory.getLogger(getClass());
66
67     private final IStoredSettings settings;
68
69     private final IRuntimeManager runtimeManager;
70
71     private final IUserManager userManager;
72
73     private final List<AuthenticationProvider> authenticationProviders;
74
75     private final Map<String, Class<? extends AuthenticationProvider>> providerNames;
76
77     private final Map<String, String> legacyRedirects;
78
79     public AuthenticationManager(
80             IRuntimeManager runtimeManager,
81             IUserManager userManager) {
82
83         this.settings = runtimeManager.getSettings();
84         this.runtimeManager = runtimeManager;
85         this.userManager = userManager;
86         this.authenticationProviders = new ArrayList<AuthenticationProvider>();
87
88         // map of shortcut provider names
89         providerNames = new HashMap<String, Class<? extends AuthenticationProvider>>();
90         providerNames.put("htpasswd", HtpasswdAuthProvider.class);
91         providerNames.put("ldap", LdapAuthProvider.class);
92         providerNames.put("pam", PAMAuthProvider.class);
93         providerNames.put("redmine", RedmineAuthProvider.class);
94         providerNames.put("salesforce", SalesforceAuthProvider.class);
95         providerNames.put("windows", WindowsAuthProvider.class);
96
97         // map of legacy external user services
98         legacyRedirects = new HashMap<String, String>();
99         legacyRedirects.put("com.gitblit.HtpasswdUserService", "htpasswd");
100         legacyRedirects.put("com.gitblit.LdapUserService", "ldap");
101         legacyRedirects.put("com.gitblit.PAMUserService", "pam");
102         legacyRedirects.put("com.gitblit.RedmineUserService", "redmine");
103         legacyRedirects.put("com.gitblit.SalesforceUserService", "salesforce");
104         legacyRedirects.put("com.gitblit.WindowsUserService", "windows");
105     }
106
107     @Override
108     public AuthenticationManager start() {
109         // automatically adjust legacy configurations
110         String realm = settings.getString(Keys.realm.userService, "${baseFolder}/users.conf");
111         if (legacyRedirects.containsKey(realm)) {
112             logger.warn("");
088b6f 113             logger.warn(Constants.BORDER2);
04a985 114             logger.warn(" IUserService '{}' is obsolete!", realm);
JM 115             logger.warn(" Please set '{}={}'", "realm.authenticationProviders", legacyRedirects.get(realm));
088b6f 116             logger.warn(Constants.BORDER2);
04a985 117             logger.warn("");
JM 118
119             // conditionally override specified authentication providers
120             if (StringUtils.isEmpty(settings.getString(Keys.realm.authenticationProviders, null))) {
121                 settings.overrideSetting(Keys.realm.authenticationProviders, legacyRedirects.get(realm));
122             }
123         }
124
125         // instantiate and setup specified authentication providers
126         List<String> providers = settings.getStrings(Keys.realm.authenticationProviders);
127         if (providers.isEmpty()) {
128             logger.info("External authentication disabled.");
129         } else {
130             for (String provider : providers) {
131                 try {
132                     Class<?> authClass;
133                     if (providerNames.containsKey(provider)) {
134                         // map the name -> class
135                         authClass = providerNames.get(provider);
136                     } else {
137                         // reflective lookup
138                         authClass = Class.forName(provider);
139                     }
140                     logger.info("setting up {}", authClass.getName());
141                     AuthenticationProvider authImpl = (AuthenticationProvider) authClass.newInstance();
142                     authImpl.setup(runtimeManager, userManager);
143                     authenticationProviders.add(authImpl);
144                 } catch (Exception e) {
145                     logger.error("", e);
146                 }
147             }
148         }
149         return this;
150     }
151
152     @Override
153     public AuthenticationManager stop() {
6659fa 154         for (AuthenticationProvider provider : authenticationProviders) {
JM 155             try {
156                 provider.stop();
157             } catch (Exception e) {
158                 logger.error("Failed to stop " + provider.getClass().getSimpleName(), e);
159             }
160         }
04a985 161         return this;
JM 162     }
bcc8a0 163
b4a63a 164     public void addAuthenticationProvider(AuthenticationProvider prov) {
JM 165         authenticationProviders.add(prov);
166     }
04a985 167
JM 168     /**
169      * Authenticate a user based on HTTP request parameters.
170      *
171      * Authentication by X509Certificate is tried first and then by cookie.
172      *
173      * @param httpRequest
174      * @return a user object or null
175      */
176     @Override
177     public UserModel authenticate(HttpServletRequest httpRequest) {
178         return authenticate(httpRequest, false);
179     }
180
181     /**
182      * Authenticate a user based on HTTP request parameters.
183      *
184      * Authentication by servlet container principal, X509Certificate, cookie,
185      * and finally BASIC header.
186      *
187      * @param httpRequest
188      * @param requiresCertificate
189      * @return a user object or null
190      */
191     @Override
192     public UserModel authenticate(HttpServletRequest httpRequest, boolean requiresCertificate) {
193         // try to authenticate by servlet container principal
194         if (!requiresCertificate) {
195             Principal principal = httpRequest.getUserPrincipal();
196             if (principal != null) {
197                 String username = principal.getName();
198                 if (!StringUtils.isEmpty(username)) {
23e08c 199                     boolean internalAccount = userManager.isInternalAccount(username);
04a985 200                     UserModel user = userManager.getUserModel(username);
JM 201                     if (user != null) {
202                         // existing user
203                         flagWicketSession(AuthenticationType.CONTAINER);
204                         logger.debug(MessageFormat.format("{0} authenticated by servlet container principal from {1}",
205                                 user.username, httpRequest.getRemoteAddr()));
9aa119 206                         return validateAuthentication(user, AuthenticationType.CONTAINER);
04a985 207                     } else if (settings.getBoolean(Keys.realm.container.autoCreateAccounts, false)
JM 208                             && !internalAccount) {
209                         // auto-create user from an authenticated container principal
210                         user = new UserModel(username.toLowerCase());
211                         user.displayName = username;
212                         user.password = Constants.EXTERNAL_ACCOUNT;
213                         user.accountType = AccountType.CONTAINER;
214                         userManager.updateUserModel(user);
215                         flagWicketSession(AuthenticationType.CONTAINER);
216                         logger.debug(MessageFormat.format("{0} authenticated and created by servlet container principal from {1}",
217                                 user.username, httpRequest.getRemoteAddr()));
9aa119 218                         return validateAuthentication(user, AuthenticationType.CONTAINER);
04a985 219                     } else if (!internalAccount) {
JM 220                         logger.warn(MessageFormat.format("Failed to find UserModel for {0}, attempted servlet container authentication from {1}",
221                                 principal.getName(), httpRequest.getRemoteAddr()));
222                     }
223                 }
224             }
225         }
226
227         // try to authenticate by certificate
228         boolean checkValidity = settings.getBoolean(Keys.git.enforceCertificateValidity, true);
229         String [] oids = settings.getStrings(Keys.git.certificateUsernameOIDs).toArray(new String[0]);
230         UserModel model = HttpUtils.getUserModelFromCertificate(httpRequest, checkValidity, oids);
231         if (model != null) {
232             // grab real user model and preserve certificate serial number
233             UserModel user = userManager.getUserModel(model.username);
234             X509Metadata metadata = HttpUtils.getCertificateMetadata(httpRequest);
235             if (user != null) {
236                 flagWicketSession(AuthenticationType.CERTIFICATE);
237                 logger.debug(MessageFormat.format("{0} authenticated by client certificate {1} from {2}",
238                         user.username, metadata.serialNumber, httpRequest.getRemoteAddr()));
9aa119 239                 return validateAuthentication(user, AuthenticationType.CERTIFICATE);
04a985 240             } else {
JM 241                 logger.warn(MessageFormat.format("Failed to find UserModel for {0}, attempted client certificate ({1}) authentication from {2}",
242                         model.username, metadata.serialNumber, httpRequest.getRemoteAddr()));
243             }
244         }
245
246         if (requiresCertificate) {
247             // caller requires client certificate authentication (e.g. git servlet)
248             return null;
249         }
250
7ab32b 251         UserModel user = null;
JM 252
04a985 253         // try to authenticate by cookie
7ab32b 254         String cookie = getCookie(httpRequest);
JM 255         if (!StringUtils.isEmpty(cookie)) {
256             user = userManager.getUserModel(cookie.toCharArray());
257             if (user != null) {
258                 flagWicketSession(AuthenticationType.COOKIE);
259                 logger.debug(MessageFormat.format("{0} authenticated by cookie from {1}",
04a985 260                     user.username, httpRequest.getRemoteAddr()));
9aa119 261                 return validateAuthentication(user, AuthenticationType.COOKIE);
7ab32b 262             }
04a985 263         }
JM 264
265         // try to authenticate by BASIC
266         final String authorization = httpRequest.getHeader("Authorization");
267         if (authorization != null && authorization.startsWith("Basic")) {
268             // Authorization: Basic base64credentials
269             String base64Credentials = authorization.substring("Basic".length()).trim();
270             String credentials = new String(Base64.decode(base64Credentials),
271                     Charset.forName("UTF-8"));
272             // credentials = username:password
273             final String[] values = credentials.split(":", 2);
274
275             if (values.length == 2) {
276                 String username = values[0];
277                 char[] password = values[1].toCharArray();
278                 user = authenticate(username, password);
279                 if (user != null) {
280                     flagWicketSession(AuthenticationType.CREDENTIALS);
281                     logger.debug(MessageFormat.format("{0} authenticated by BASIC request header from {1}",
282                             user.username, httpRequest.getRemoteAddr()));
9aa119 283                     return validateAuthentication(user, AuthenticationType.CREDENTIALS);
04a985 284                 } else {
JM 285                     logger.warn(MessageFormat.format("Failed login attempt for {0}, invalid credentials from {1}",
286                             username, httpRequest.getRemoteAddr()));
287                 }
288             }
289         }
290         return null;
9aa119 291     }
JM 292
293     /**
44e2ee 294      * Authenticate a user based on a public key.
e3b636 295      *
44e2ee 296      * This implementation assumes that the authentication has already take place
JM 297      * (e.g. SSHDaemon) and that this is a validation/verification of the user.
298      *
299      * @param username
300      * @param key
e3b636 301      * @return a user object or null
DO 302      */
303     @Override
bcc8a0 304     public UserModel authenticate(String username, SshKey key) {
e3b636 305         if (username != null) {
DO 306             if (!StringUtils.isEmpty(username)) {
307                 UserModel user = userManager.getUserModel(username);
308                 if (user != null) {
309                     // existing user
44e2ee 310                     logger.debug(MessageFormat.format("{0} authenticated by {1} public key",
JM 311                             user.username, key.getAlgorithm()));
312                     return validateAuthentication(user, AuthenticationType.PUBLIC_KEY);
e3b636 313                 }
44e2ee 314                 logger.warn(MessageFormat.format("Failed to find UserModel for {0} during public key authentication",
JM 315                             username));
e3b636 316             }
DO 317         } else {
44e2ee 318             logger.warn("Empty user passed to AuthenticationManager.authenticate!");
e3b636 319         }
DO 320         return null;
321     }
322
323
324     /**
9aa119 325      * This method allows the authentication manager to reject authentication
JM 326      * attempts.  It is called after the username/secret have been verified to
327      * ensure that the authentication technique has been logged.
328      *
329      * @param user
330      * @return
331      */
332     protected UserModel validateAuthentication(UserModel user, AuthenticationType type) {
333         if (user == null) {
334             return null;
335         }
336         if (user.disabled) {
337             // user has been disabled
338             logger.warn("Rejected {} authentication attempt by disabled account \"{}\"",
339                     type, user.username);
340             return null;
341         }
342         return user;
04a985 343     }
JM 344
345     protected void flagWicketSession(AuthenticationType authenticationType) {
346         RequestCycle requestCycle = RequestCycle.get();
347         if (requestCycle != null) {
348             // flag the Wicket session, if this is a Wicket request
349             GitBlitWebSession session = GitBlitWebSession.get();
350             session.authenticationType = authenticationType;
351         }
352     }
353
354     /**
355      * Authenticate a user based on a username and password.
356      *
357      * @see IUserService.authenticate(String, char[])
358      * @param username
359      * @param password
360      * @return a user object or null
361      */
362     @Override
363     public UserModel authenticate(String username, char[] password) {
364         if (StringUtils.isEmpty(username)) {
365             // can not authenticate empty username
366             return null;
367         }
368
369         String usernameDecoded = StringUtils.decodeUsername(username);
370         String pw = new String(password);
371         if (StringUtils.isEmpty(pw)) {
372             // can not authenticate empty password
373             return null;
374         }
375
376         UserModel user = userManager.getUserModel(usernameDecoded);
1293c2 377
JM 378         // try local authentication
379         if (user != null && user.isLocalAccount()) {
b4a63a 380             return authenticateLocal(user, password);
04a985 381         }
JM 382
383         // try registered external authentication providers
b4a63a 384         for (AuthenticationProvider provider : authenticationProviders) {
JM 385             if (provider instanceof UsernamePasswordAuthenticationProvider) {
386                 UserModel returnedUser = provider.authenticate(usernameDecoded, password);
387                 if (returnedUser != null) {
388                     // user authenticated
389                     returnedUser.accountType = provider.getAccountType();
390                     return validateAuthentication(returnedUser, AuthenticationType.CREDENTIALS);
04a985 391                 }
JM 392             }
393         }
bcc8a0 394
b4a63a 395         // could not authenticate locally or with a provider
JM 396         return null;
397     }
bcc8a0 398
b4a63a 399     /**
JM 400      * Returns a UserModel if local authentication succeeds.
bcc8a0 401      *
b4a63a 402      * @param user
JM 403      * @param password
404      * @return a UserModel if local authentication succeeds, null otherwise
405      */
406     protected UserModel authenticateLocal(UserModel user, char [] password) {
407         UserModel returnedUser = null;
408         if (user.password.startsWith(StringUtils.MD5_TYPE)) {
409             // password digest
410             String md5 = StringUtils.MD5_TYPE + StringUtils.getMD5(new String(password));
411             if (user.password.equalsIgnoreCase(md5)) {
412                 returnedUser = user;
413             }
414         } else if (user.password.startsWith(StringUtils.COMBINED_MD5_TYPE)) {
415             // username+password digest
416             String md5 = StringUtils.COMBINED_MD5_TYPE
417                     + StringUtils.getMD5(user.username.toLowerCase() + new String(password));
418             if (user.password.equalsIgnoreCase(md5)) {
419                 returnedUser = user;
420             }
421         } else if (user.password.equals(new String(password))) {
422             // plain-text password
423             returnedUser = user;
424         }
425         return validateAuthentication(returnedUser, AuthenticationType.CREDENTIALS);
04a985 426     }
JM 427
428     /**
7ab32b 429      * Returns the Gitlbit cookie in the request.
JM 430      *
431      * @param request
432      * @return the Gitblit cookie for the request or null if not found
433      */
434     @Override
435     public String getCookie(HttpServletRequest request) {
436         if (settings.getBoolean(Keys.web.allowCookieAuthentication, true)) {
437             Cookie[] cookies = request.getCookies();
438             if (cookies != null && cookies.length > 0) {
439                 for (Cookie cookie : cookies) {
440                     if (cookie.getName().equals(Constants.NAME)) {
441                         String value = cookie.getValue();
442                         return value;
443                     }
444                 }
445             }
446         }
447         return null;
448     }
449
450     /**
04a985 451      * Sets a cookie for the specified user.
JM 452      *
453      * @param response
454      * @param user
455      */
456     @Override
ec7ed8 457     @Deprecated
04a985 458     public void setCookie(HttpServletResponse response, UserModel user) {
ec7ed8 459         setCookie(null, response, user);
JM 460     }
461
462     /**
463      * Sets a cookie for the specified user.
464      *
465      * @param request
466      * @param response
467      * @param user
468      */
469     @Override
470     public void setCookie(HttpServletRequest request, HttpServletResponse response, UserModel user) {
04a985 471         if (settings.getBoolean(Keys.web.allowCookieAuthentication, true)) {
JM 472             GitBlitWebSession session = GitBlitWebSession.get();
473             boolean standardLogin = session.authenticationType.isStandard();
474
475             if (standardLogin) {
476                 Cookie userCookie;
477                 if (user == null) {
478                     // clear cookie for logout
479                     userCookie = new Cookie(Constants.NAME, "");
480                 } else {
481                     // set cookie for login
482                     String cookie = userManager.getCookie(user);
483                     if (StringUtils.isEmpty(cookie)) {
484                         // create empty cookie
485                         userCookie = new Cookie(Constants.NAME, "");
486                     } else {
487                         // create real cookie
488                         userCookie = new Cookie(Constants.NAME, cookie);
7ab32b 489                         // expire the cookie in 7 days
JM 490                         userCookie.setMaxAge((int) TimeUnit.DAYS.toSeconds(7));
04a985 491                     }
JM 492                 }
ec7ed8 493                 String path = "/";
JM 494                 if (request != null) {
495                     if (!StringUtils.isEmpty(request.getContextPath())) {
496                         path = request.getContextPath();
497                     }
498                 }
499                 userCookie.setPath(path);
04a985 500                 response.addCookie(userCookie);
JM 501             }
502         }
503     }
504
505     /**
506      * Logout a user.
507      *
ec7ed8 508      * @param response
04a985 509      * @param user
JM 510      */
511     @Override
ec7ed8 512     @Deprecated
04a985 513     public void logout(HttpServletResponse response, UserModel user) {
ec7ed8 514         setCookie(null, response,  null);
JM 515     }
516
517     /**
518      * Logout a user.
519      *
520      * @param request
521      * @param response
522      * @param user
523      */
524     @Override
525     public void logout(HttpServletRequest request, HttpServletResponse response, UserModel user) {
526         setCookie(request, response,  null);
04a985 527     }
JM 528
529     /**
530      * Returns true if the user's credentials can be changed.
531      *
532      * @param user
533      * @return true if the user service supports credential changes
534      */
535     @Override
536     public boolean supportsCredentialChanges(UserModel user) {
537         return (user != null && user.isLocalAccount()) || findProvider(user).supportsCredentialChanges();
538     }
539
540     /**
541      * Returns true if the user's display name can be changed.
542      *
543      * @param user
544      * @return true if the user service supports display name changes
545      */
546     @Override
547     public boolean supportsDisplayNameChanges(UserModel user) {
548         return (user != null && user.isLocalAccount()) || findProvider(user).supportsDisplayNameChanges();
549     }
550
551     /**
552      * Returns true if the user's email address can be changed.
553      *
554      * @param user
555      * @return true if the user service supports email address changes
556      */
557     @Override
558     public boolean supportsEmailAddressChanges(UserModel user) {
559         return (user != null && user.isLocalAccount()) || findProvider(user).supportsEmailAddressChanges();
560     }
561
562     /**
563      * Returns true if the user's team memberships can be changed.
564      *
565      * @param user
566      * @return true if the user service supports team membership changes
567      */
568     @Override
569     public boolean supportsTeamMembershipChanges(UserModel user) {
570         return (user != null && user.isLocalAccount()) || findProvider(user).supportsTeamMembershipChanges();
571     }
572
573     /**
574      * Returns true if the team memberships can be changed.
575      *
576      * @param user
577      * @return true if the team membership can be changed
578      */
579     @Override
580     public boolean supportsTeamMembershipChanges(TeamModel team) {
581         return (team != null && team.isLocalTeam()) || findProvider(team).supportsTeamMembershipChanges();
582     }
583
584     protected AuthenticationProvider findProvider(UserModel user) {
585         for (AuthenticationProvider provider : authenticationProviders) {
586             if (provider.getAccountType().equals(user.accountType)) {
587                 return provider;
588             }
589         }
590         return AuthenticationProvider.NULL_PROVIDER;
591     }
592
593     protected AuthenticationProvider findProvider(TeamModel team) {
594         for (AuthenticationProvider provider : authenticationProviders) {
595             if (provider.getAccountType().equals(team.accountType)) {
596                 return provider;
597             }
598         }
599         return AuthenticationProvider.NULL_PROVIDER;
600     }
601 }