2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.usermanager.internal;
11 import java.io.FileNotFoundException;
12 import java.io.IOException;
13 import java.io.ObjectInputStream;
14 import java.util.ArrayList;
15 import java.util.Collections;
16 import java.util.EnumSet;
17 import java.util.HashMap;
18 import java.util.HashSet;
19 import java.util.List;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.ConcurrentMap;
25 import org.apache.commons.lang3.StringUtils;
26 import org.eclipse.osgi.framework.console.CommandInterpreter;
27 import org.eclipse.osgi.framework.console.CommandProvider;
28 import org.opendaylight.controller.clustering.services.CacheConfigException;
29 import org.opendaylight.controller.clustering.services.CacheExistException;
30 import org.opendaylight.controller.clustering.services.IClusterGlobalServices;
31 import org.opendaylight.controller.clustering.services.IClusterServices;
32 import org.opendaylight.controller.configuration.IConfigurationAware;
33 import org.opendaylight.controller.containermanager.IContainerAuthorization;
34 import org.opendaylight.controller.sal.authorization.AuthResultEnum;
35 import org.opendaylight.controller.sal.authorization.IResourceAuthorization;
36 import org.opendaylight.controller.sal.authorization.UserLevel;
37 import org.opendaylight.controller.sal.utils.StatusCode;
38 import org.opendaylight.controller.sal.utils.GlobalConstants;
39 import org.opendaylight.controller.sal.utils.IObjectReader;
40 import org.opendaylight.controller.sal.utils.ObjectReader;
41 import org.opendaylight.controller.sal.utils.ObjectWriter;
42 import org.opendaylight.controller.sal.utils.Status;
43 import org.opendaylight.controller.usermanager.AuthResponse;
44 import org.opendaylight.controller.usermanager.AuthenticatedUser;
45 import org.opendaylight.controller.usermanager.AuthorizationConfig;
46 import org.opendaylight.controller.usermanager.IAAAProvider;
47 import org.opendaylight.controller.usermanager.ISessionManager;
48 import org.opendaylight.controller.usermanager.IUserManager;
49 import org.opendaylight.controller.usermanager.ServerConfig;
50 import org.opendaylight.controller.usermanager.UserConfig;
51 import org.opendaylight.controller.usermanager.security.SessionManager;
52 import org.opendaylight.controller.usermanager.security.UserSecurityContextRepository;
54 import org.osgi.framework.BundleContext;
55 import org.osgi.framework.FrameworkUtil;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58 import org.springframework.security.authentication.AuthenticationProvider;
59 import org.springframework.security.authentication.AuthenticationServiceException;
60 import org.springframework.security.authentication.BadCredentialsException;
61 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
62 import org.springframework.security.core.Authentication;
63 import org.springframework.security.core.AuthenticationException;
64 import org.springframework.security.core.userdetails.User;
65 import org.springframework.security.core.userdetails.UserDetails;
66 import org.springframework.security.core.userdetails.UsernameNotFoundException;
67 import org.springframework.security.web.context.SecurityContextRepository;
70 * The internal implementation of the User Manager.
72 public class UserManagerImpl implements IUserManager, IObjectReader,
73 IConfigurationAware, CommandProvider, AuthenticationProvider {
74 private static final Logger logger = LoggerFactory
75 .getLogger(UserManagerImpl.class);
76 private static final String defaultAdmin = "admin";
77 private static final String defaultAdminPassword = "admin";
78 private static final String defaultAdminRole = UserLevel.NETWORKADMIN
80 private static final String ROOT = GlobalConstants.STARTUPHOME.toString();
81 private static final String SAVE = "save";
82 private static final String usersFileName = ROOT + "users.conf";
83 private static final String serversFileName = ROOT + "servers.conf";
84 private static final String authFileName = ROOT + "authorization.conf";
85 private ConcurrentMap<String, UserConfig> localUserConfigList;
86 private ConcurrentMap<String, ServerConfig> remoteServerConfigList;
87 // local authorization info for remotely authenticated users
88 private ConcurrentMap<String, AuthorizationConfig> authorizationConfList;
89 private ConcurrentMap<String, AuthenticatedUser> activeUsers;
90 private ConcurrentMap<String, IAAAProvider> authProviders;
91 private ConcurrentMap<Long, String> localUserListSaveConfigEvent,
92 remoteServerSaveConfigEvent, authorizationSaveConfigEvent;
93 private IClusterGlobalServices clusterGlobalService = null;
94 private SecurityContextRepository securityContextRepo = new UserSecurityContextRepository();
95 private IContainerAuthorization containerAuthorizationClient;
96 private Set<IResourceAuthorization> applicationAuthorizationClients;
97 private ISessionManager sessionMgr = new SessionManager();
99 public boolean addAAAProvider(IAAAProvider provider) {
100 if (provider == null || provider.getName() == null
101 || provider.getName().trim().isEmpty()) {
104 if (authProviders.get(provider.getName()) != null) {
108 authProviders.put(provider.getName(), provider);
112 public void removeAAAProvider(IAAAProvider provider) {
113 authProviders.remove(provider.getName());
116 public IAAAProvider getAAAProvider(String name) {
117 return authProviders.get(name);
121 public Set<String> getAAAProviderNames() {
122 return authProviders.keySet();
125 @SuppressWarnings("deprecation")
126 private void allocateCaches() {
127 this.applicationAuthorizationClients = Collections
128 .synchronizedSet(new HashSet<IResourceAuthorization>());
129 if (clusterGlobalService == null) {
130 logger.error("un-initialized clusterGlobalService, can't create cache");
135 clusterGlobalService.createCache("usermanager.localUserConfigList",
136 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
138 clusterGlobalService.createCache(
139 "usermanager.remoteServerConfigList",
140 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
142 clusterGlobalService.createCache(
143 "usermanager.authorizationConfList",
144 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
146 clusterGlobalService.createCache("usermanager.activeUsers",
147 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
149 clusterGlobalService.createCache(
150 "usermanager.localUserSaveConfigEvent",
151 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
153 clusterGlobalService.createCache(
154 "usermanager.remoteServerSaveConfigEvent",
155 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
157 clusterGlobalService.createCache(
158 "usermanager.authorizationSaveConfigEvent",
159 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
160 } catch (CacheConfigException cce) {
161 logger.error("Cache configuration invalid - check cache mode");
162 } catch (CacheExistException ce) {
163 logger.debug("Skipping cache creation as already present");
167 @SuppressWarnings({ "unchecked", "deprecation" })
168 private void retrieveCaches() {
169 if (clusterGlobalService == null) {
170 logger.error("un-initialized clusterService, can't retrieve cache");
174 activeUsers = (ConcurrentMap<String, AuthenticatedUser>) clusterGlobalService
175 .getCache("usermanager.activeUsers");
176 if (activeUsers == null) {
177 logger.error("Failed to get cache for activeUsers");
180 localUserConfigList = (ConcurrentMap<String, UserConfig>) clusterGlobalService
181 .getCache("usermanager.localUserConfigList");
182 if (localUserConfigList == null) {
183 logger.error("Failed to get cache for localUserConfigList");
186 remoteServerConfigList = (ConcurrentMap<String, ServerConfig>) clusterGlobalService
187 .getCache("usermanager.remoteServerConfigList");
188 if (remoteServerConfigList == null) {
189 logger.error("Failed to get cache for remoteServerConfigList");
192 authorizationConfList = (ConcurrentMap<String, AuthorizationConfig>) clusterGlobalService
193 .getCache("usermanager.authorizationConfList");
194 if (authorizationConfList == null) {
195 logger.error("Failed to get cache for authorizationConfList");
198 localUserListSaveConfigEvent = (ConcurrentMap<Long, String>) clusterGlobalService
199 .getCache("usermanager.localUserSaveConfigEvent");
200 if (localUserListSaveConfigEvent == null) {
201 logger.error("Failed to get cache for localUserSaveConfigEvent");
204 remoteServerSaveConfigEvent = (ConcurrentMap<Long, String>) clusterGlobalService
205 .getCache("usermanager.remoteServerSaveConfigEvent");
206 if (remoteServerSaveConfigEvent == null) {
207 logger.error("Failed to get cache for remoteServerSaveConfigEvent");
210 authorizationSaveConfigEvent = (ConcurrentMap<Long, String>) clusterGlobalService
211 .getCache("usermanager.authorizationSaveConfigEvent");
212 if (authorizationSaveConfigEvent == null) {
213 logger.error("Failed to get cache for authorizationSaveConfigEvent");
217 private void loadConfigurations() {
218 // To encode and decode user and server configuration objects
222 * Do not load local startup file if we already got the configurations
223 * synced from another cluster node
225 if (localUserConfigList.isEmpty()) {
228 if (remoteServerConfigList.isEmpty()) {
231 if (authorizationConfList.isEmpty()) {
236 private void loadSecurityKeys() {
240 private void checkDefaultNetworkAdmin() {
241 // If startup config is not there, it's old or it was deleted,
242 // need to add Default Admin
243 if (!localUserConfigList.containsKey(defaultAdmin)) {
244 List<String> roles = new ArrayList<String>(1);
245 roles.add(defaultAdminRole);
246 localUserConfigList.put(defaultAdmin, new UserConfig(defaultAdmin,
247 defaultAdminPassword, roles));
252 public AuthResultEnum authenticate(String userName, String password) {
253 IAAAProvider aaaClient;
254 AuthResponse rcResponse = null;
255 AuthenticatedUser result;
256 boolean remotelyAuthenticated = false;
257 boolean authorizationInfoIsPresent = false;
258 boolean authorized = false;
261 * Attempt remote authentication first if server is configured
263 for (ServerConfig aaaServer : remoteServerConfigList.values()) {
264 String protocol = aaaServer.getProtocol();
265 aaaClient = this.getAAAProvider(protocol);
266 if (aaaClient != null) {
267 rcResponse = aaaClient.authService(userName, password,
268 aaaServer.getAddress(), aaaServer.getSecret());
269 if (rcResponse.getStatus() == AuthResultEnum.AUTH_ACCEPT) {
271 "Remote Authentication Succeeded for User: \"{}\", by Server: {}",
272 userName, aaaServer.getAddress());
273 remotelyAuthenticated = true;
275 } else if (rcResponse.getStatus() == AuthResultEnum.AUTH_REJECT) {
277 "Remote Authentication Rejected User: \"{}\", from Server: {}, Reason:{}",
278 new Object[] { userName, aaaServer.getAddress(),
279 rcResponse.getStatus().toString() });
282 "Remote Authentication Failed for User: \"{}\", from Server: {}, Reason:{}",
283 new Object[] { userName, aaaServer.getAddress(),
284 rcResponse.getStatus().toString() });
289 if (!remotelyAuthenticated) {
290 UserConfig localUser = this.localUserConfigList.get(userName);
291 if (localUser == null) {
293 "Local Authentication Failed for User:\"{}\", Reason: "
294 + "user not found in Local Database", userName);
295 return (AuthResultEnum.AUTH_INVALID_LOC_USER);
297 rcResponse = localUser.authenticate(password);
298 if (rcResponse.getStatus() != AuthResultEnum.AUTH_ACCEPT_LOC) {
300 "Local Authentication Failed for User: \"{}\", Reason: {}",
301 userName, rcResponse.getStatus().toString());
303 return (rcResponse.getStatus());
305 logger.info("Local Authentication Succeeded for User: \"{}\"",
310 * Authentication succeeded
312 result = new AuthenticatedUser(userName);
315 * Extract attributes from response All the information we are
316 * interested in is in the first Cisco VSA (vendor specific attribute).
317 * Just process the first VSA and return
319 String attributes = (rcResponse.getData() != null && !rcResponse
320 .getData().isEmpty()) ? rcResponse.getData().get(0) : null;
323 * Check if the authorization information is present
325 authorizationInfoIsPresent = checkAuthorizationInfo(attributes);
328 * The AAA server was only used to perform the authentication Look for
329 * locally stored authorization info for this user If found, add the
330 * data to the rcResponse
332 if (remotelyAuthenticated && !authorizationInfoIsPresent) {
334 "No Remote Authorization Info provided by Server for User: \"{}\"",
337 "Looking for Local Authorization Info for User: \"{}\"",
340 AuthorizationConfig resource = authorizationConfList.get(userName);
341 if (resource != null) {
342 logger.info("Found Local Authorization Info for User: \"{}\"",
344 attributes = resource.getRolesString();
347 authorizationInfoIsPresent = checkAuthorizationInfo(attributes);
351 * Common response parsing for local & remote authenticated user Looking
352 * for authorized resources, detecting attributes' validity
354 if (authorizationInfoIsPresent) {
355 // Identifying the administrative role
356 result.setRoleList(attributes.split(" "));
359 logger.info("Not able to find Authorization Info for User: \"{}\"",
364 * Add profile for authenticated user
366 putUserInActiveList(userName, result);
368 logger.info("User \"{}\" authorized for the following role(s): {}",
369 userName, result.getUserRoles());
371 logger.info("User \"{}\" Not Authorized for any role ", userName);
374 return rcResponse.getStatus();
377 // Check in the attributes string whether or not authorization information
379 private boolean checkAuthorizationInfo(String attributes) {
380 return (attributes != null && !attributes.isEmpty());
383 private void putUserInActiveList(String user, AuthenticatedUser result) {
384 activeUsers.put(user, result);
387 private void removeUserFromActiveList(String user) {
388 if (!activeUsers.containsKey(user)) {
389 // as cookie persists in cache, we can get logout for unexisting
393 activeUsers.remove(user);
397 public Status saveLocalUserList() {
398 return saveLocalUserListInternal();
401 private Status saveLocalUserListInternal() {
402 ObjectWriter objWriter = new ObjectWriter();
403 return objWriter.write(new ConcurrentHashMap<String, UserConfig>(
404 localUserConfigList), usersFileName);
408 public Status saveAAAServerList() {
409 return saveAAAServerListInternal();
412 private Status saveAAAServerListInternal() {
413 ObjectWriter objWriter = new ObjectWriter();
414 return objWriter.write(new ConcurrentHashMap<String, ServerConfig>(
415 remoteServerConfigList), serversFileName);
419 public Status saveAuthorizationList() {
420 return saveAuthorizationListInternal();
423 private Status saveAuthorizationListInternal() {
424 ObjectWriter objWriter = new ObjectWriter();
425 return objWriter.write(
426 new ConcurrentHashMap<String, AuthorizationConfig>(
427 authorizationConfList), authFileName);
431 public Object readObject(ObjectInputStream ois)
432 throws FileNotFoundException, IOException, ClassNotFoundException {
433 // Perform the class deserialization locally, from inside the package
434 // where the class is defined
435 return ois.readObject();
438 @SuppressWarnings("unchecked")
439 private void loadUserConfig() {
440 ObjectReader objReader = new ObjectReader();
441 ConcurrentMap<String, UserConfig> confList = (ConcurrentMap<String, UserConfig>) objReader
442 .read(this, usersFileName);
444 if (confList == null) {
448 for (UserConfig conf : confList.values()) {
453 @SuppressWarnings("unchecked")
454 private void loadServerConfig() {
455 ObjectReader objReader = new ObjectReader();
456 ConcurrentMap<String, ServerConfig> confList = (ConcurrentMap<String, ServerConfig>) objReader
457 .read(this, serversFileName);
459 if (confList == null) {
463 for (ServerConfig conf : confList.values()) {
468 @SuppressWarnings("unchecked")
469 private void loadAuthConfig() {
470 ObjectReader objReader = new ObjectReader();
471 ConcurrentMap<String, AuthorizationConfig> confList = (ConcurrentMap<String, AuthorizationConfig>) objReader
472 .read(this, authFileName);
474 if (confList == null) {
478 for (AuthorizationConfig conf : confList.values()) {
484 * Interaction with GUI START
486 public Status addRemoveLocalUser(UserConfig AAAconf, boolean delete) {
487 // UserConfig Validation check
488 Status validCheck = AAAconf.validate();
489 if (!validCheck.isSuccess()) {
493 // Update Config database
495 if (AAAconf.getUser().equals(UserManagerImpl.defaultAdmin)) {
496 String msg = "Invalid Request: Default Network Admin User "
497 + "cannot be deleted";
499 return new Status(StatusCode.NOTALLOWED, msg);
501 localUserConfigList.remove(AAAconf.getUser());
503 * A user account has been removed form local database, we assume
504 * admin does not want this user to stay connected, in case he has
505 * an open session. So we clean the active list as well.
507 removeUserFromActiveList(AAAconf.getUser());
509 if (AAAconf.getUser().equals(UserManagerImpl.defaultAdmin)) {
510 String msg = "Invalid Request: Default Network Admin User "
513 return new Status(StatusCode.NOTALLOWED, msg);
515 localUserConfigList.put(AAAconf.getUser(), AAAconf);
518 return new Status(StatusCode.SUCCESS, null);
521 private Status addRemoveAAAServer(ServerConfig AAAconf, boolean delete) {
523 if (!AAAconf.isValid()) {
524 String msg = "Invalid Server configuration";
526 return new Status(StatusCode.BADREQUEST, msg);
529 // Update configuration database
531 remoteServerConfigList.remove(AAAconf.getAddress());
533 remoteServerConfigList.put(AAAconf.getAddress(), AAAconf);
536 return new Status(StatusCode.SUCCESS, null);
539 private Status addRemoveAuthInfo(AuthorizationConfig AAAconf, boolean delete) {
540 Status configCheck = AAAconf.validate();
541 if (!configCheck.isSuccess()) {
542 String msg = "Invalid Authorization configuration: "
543 + configCheck.getDescription();
545 return new Status(StatusCode.BADREQUEST, msg);
548 // Update configuration database
550 authorizationConfList.remove(AAAconf.getUser());
552 authorizationConfList.put(AAAconf.getUser(), AAAconf);
555 return new Status(StatusCode.SUCCESS, null);
559 public Status addLocalUser(UserConfig AAAconf) {
560 return addRemoveLocalUser(AAAconf, false);
564 public Status removeLocalUser(UserConfig AAAconf) {
565 return addRemoveLocalUser(AAAconf, true);
569 public Status removeLocalUser(String userName) {
570 if (userName == null || userName.trim().isEmpty()) {
571 return new Status(StatusCode.BADREQUEST, "Invalid user name");
573 if (!localUserConfigList.containsKey(userName)) {
574 return new Status(StatusCode.NOTFOUND, "User does not exist");
576 return addRemoveLocalUser(localUserConfigList.get(userName), true);
580 public Status addAAAServer(ServerConfig AAAconf) {
581 return addRemoveAAAServer(AAAconf, false);
585 public Status removeAAAServer(ServerConfig AAAconf) {
586 return addRemoveAAAServer(AAAconf, true);
590 public Status addAuthInfo(AuthorizationConfig AAAconf) {
591 return addRemoveAuthInfo(AAAconf, false);
595 public Status removeAuthInfo(AuthorizationConfig AAAconf) {
596 return addRemoveAuthInfo(AAAconf, true);
600 public List<UserConfig> getLocalUserList() {
601 return new ArrayList<UserConfig>(localUserConfigList.values());
605 public List<ServerConfig> getAAAServerList() {
606 return new ArrayList<ServerConfig>(remoteServerConfigList.values());
610 public List<AuthorizationConfig> getAuthorizationList() {
611 return new ArrayList<AuthorizationConfig>(
612 authorizationConfList.values());
616 public Status changeLocalUserPassword(String user, String curPassword,
617 String newPassword) {
618 UserConfig targetConfigEntry = null;
620 // update configuration entry
621 targetConfigEntry = localUserConfigList.get(user);
622 if (targetConfigEntry == null) {
623 return new Status(StatusCode.NOTFOUND, "User not found");
625 Status status = targetConfigEntry
626 .update(curPassword, newPassword, null);
627 if (!status.isSuccess()) {
630 // Trigger cluster update
631 localUserConfigList.put(user, targetConfigEntry);
633 logger.info("Password changed for User \"{}\"", user);
639 public void userLogout(String userName) {
640 // TODO: if user was authenticated through AAA server, send
641 // Acct-Status-Type=stop message to server with logout as reason
642 removeUserFromActiveList(userName);
643 logger.info("User \"{}\" logged out", userName);
647 * This function will get called by http session mgr when session times out
650 public void userTimedOut(String userName) {
651 // TODO: if user was authenticated through AAA server, send
652 // Acct-Status-Type=stop message to server with timeout as reason
653 removeUserFromActiveList(userName);
654 logger.info("User \"{}\" timed out", userName);
658 public String getAccessDate(String user) {
659 return this.activeUsers.get(user).getAccessDate();
663 public synchronized Map<String, List<String>> getUserLoggedIn() {
664 Map<String, List<String>> loggedInList = new HashMap<String, List<String>>();
665 for (Map.Entry<String, AuthenticatedUser> user : activeUsers.entrySet()) {
666 String userNameShow = user.getKey();
667 loggedInList.put(userNameShow, user.getValue().getUserRoles());
672 public void _umAddUser(CommandInterpreter ci) {
673 String userName = ci.nextArgument();
674 String password = ci.nextArgument();
675 String role = ci.nextArgument();
677 List<String> roles = new ArrayList<String>();
678 while (role != null) {
679 if (!role.trim().isEmpty()) {
682 role = ci.nextArgument();
685 if (userName == null || userName.trim().isEmpty() || password == null
686 || password.trim().isEmpty() || roles == null
687 || roles.isEmpty()) {
688 ci.println("Invalid Arguments");
689 ci.println("umAddUser <user_name> <password> <user_role>");
692 ci.print(this.addLocalUser(new UserConfig(userName, password, roles)));
695 public void _umRemUser(CommandInterpreter ci) {
696 String userName = ci.nextArgument();
698 if (userName == null || userName.trim().isEmpty()) {
699 ci.println("Invalid Arguments");
700 ci.println("umRemUser <user_name>");
703 UserConfig target = localUserConfigList.get(userName);
704 if (target == null) {
705 ci.println("User not found");
708 ci.println(this.removeLocalUser(target));
711 public void _umGetUsers(CommandInterpreter ci) {
712 for (UserConfig conf : this.getLocalUserList()) {
713 ci.println(conf.getUser() + " " + conf.getRoles());
717 public void _addAAAServer(CommandInterpreter ci) {
718 String server = ci.nextArgument();
719 String secret = ci.nextArgument();
720 String protocol = ci.nextArgument();
722 if (server == null || secret == null || protocol == null) {
723 ci.println("Usage : addAAAServer <server> <secret> <protocol>");
726 ServerConfig s = new ServerConfig(server, secret, protocol);
730 public void _removeAAAServer(CommandInterpreter ci) {
731 String server = ci.nextArgument();
732 String secret = ci.nextArgument();
733 String protocol = ci.nextArgument();
735 if (server == null || secret == null || protocol == null) {
736 ci.println("Usage : addAAAServer <server> <secret> <protocol>");
739 ServerConfig s = new ServerConfig(server, secret, protocol);
743 public void _printAAAServers(CommandInterpreter ci) {
744 for (ServerConfig aaaServer : remoteServerConfigList.values()) {
745 ci.println(aaaServer.getAddress() + "-" + aaaServer.getProtocol());
750 public String getHelp() {
751 StringBuffer help = new StringBuffer();
752 return help.toString();
755 void setClusterGlobalService(IClusterGlobalServices s) {
756 logger.debug("Cluster Service Global set");
757 this.clusterGlobalService = s;
760 void unsetClusterGlobalService(IClusterGlobalServices s) {
761 if (this.clusterGlobalService == s) {
762 logger.debug("Cluster Service Global removed!");
763 this.clusterGlobalService = null;
767 void unsetContainerAuthClient(IContainerAuthorization s) {
768 if (this.containerAuthorizationClient == s) {
769 this.containerAuthorizationClient = null;
773 void setContainerAuthClient(IContainerAuthorization s) {
774 this.containerAuthorizationClient = s;
777 void setAppAuthClient(IResourceAuthorization s) {
778 this.applicationAuthorizationClients.add(s);
781 void unsetAppAuthClient(IResourceAuthorization s) {
782 this.applicationAuthorizationClients.remove(s);
786 * Function called by the dependency manager when all the required
787 * dependencies are satisfied
794 * Function called by the dependency manager when at least one dependency
795 * become unsatisfied or when the component is shutting down because for
796 * example bundle is being stopped.
803 * Function called by dependency manager after "init ()" is called and after
804 * the services provided by the class are registered in the service registry
808 authProviders = new ConcurrentHashMap<String, IAAAProvider>();
809 // Instantiate cluster synced variables
813 // Read startup configuration and populate databases
814 loadConfigurations();
816 // Make sure default Network Admin account is there
817 checkDefaultNetworkAdmin();
818 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
820 bundleContext.registerService(CommandProvider.class.getName(), this,
825 * Function called by the dependency manager before the services exported by
826 * the component are unregistered, this will be followed by a "destroy ()"
834 public List<String> getUserRoles(String userName) {
835 List<String> roles = null;
836 if (userName != null) {
838 * First look in active users then in local configured users,
839 * finally in local authorized users
841 if (activeUsers.containsKey(userName)) {
842 roles = activeUsers.get(userName).getUserRoles();
843 } else if (localUserConfigList.containsKey(userName)) {
844 roles = localUserConfigList.get(userName).getRoles();
845 } else if (authorizationConfList.containsKey(userName)) {
846 roles = authorizationConfList.get(userName).getRoles();
849 return (roles == null) ? new ArrayList<String>(0) : roles;
853 public UserLevel getUserLevel(String username) {
854 // Returns the highest controller user level for the passed user
855 List<String> rolesNames = getUserRoles(username);
857 if (rolesNames.isEmpty()) {
858 return UserLevel.NOUSER;
861 // Check against the well known controller roles first
862 if (rolesNames.contains(UserLevel.SYSTEMADMIN.toString())) {
863 return UserLevel.SYSTEMADMIN;
865 if (rolesNames.contains(UserLevel.NETWORKADMIN.toString())) {
866 return UserLevel.NETWORKADMIN;
868 if (rolesNames.contains(UserLevel.NETWORKOPERATOR.toString())) {
869 return UserLevel.NETWORKOPERATOR;
871 // Check if container user now
872 if (containerAuthorizationClient != null) {
873 for (String roleName : rolesNames) {
874 if (containerAuthorizationClient.isApplicationRole(roleName)) {
875 return UserLevel.CONTAINERUSER;
879 // Finally check if application user
880 if (applicationAuthorizationClients != null) {
881 for (String roleName : rolesNames) {
882 for (IResourceAuthorization client : this.applicationAuthorizationClients) {
883 if (client.isApplicationRole(roleName)) {
884 return UserLevel.APPUSER;
889 return UserLevel.NOUSER;
894 public List<UserLevel> getUserLevels(String username) {
895 // Returns the controller user levels for the passed user
896 List<String> rolesNames = getUserRoles(username);
897 List<UserLevel> levels = new ArrayList<UserLevel>();
899 if (rolesNames.isEmpty()) {
903 // Check against the well known controller roles first
904 if (rolesNames.contains(UserLevel.SYSTEMADMIN.toString())) {
905 levels.add(UserLevel.SYSTEMADMIN);
907 if (rolesNames.contains(UserLevel.NETWORKADMIN.toString())) {
908 levels.add(UserLevel.NETWORKADMIN);
910 if (rolesNames.contains(UserLevel.NETWORKOPERATOR.toString())) {
911 levels.add(UserLevel.NETWORKOPERATOR);
913 // Check if container user now
914 if (containerAuthorizationClient != null) {
915 for (String roleName : rolesNames) {
916 if (containerAuthorizationClient.isApplicationRole(roleName)) {
917 levels.add(UserLevel.CONTAINERUSER);
922 // Finally check if application user
923 if (applicationAuthorizationClients != null) {
924 for (String roleName : rolesNames) {
925 for (IResourceAuthorization client : this.applicationAuthorizationClients) {
926 if (client.isApplicationRole(roleName)) {
927 levels.add(UserLevel.APPUSER);
937 public Status saveConfiguration() {
938 boolean success = true;
939 Status ret = saveLocalUserList();
940 if (!ret.isSuccess()) {
943 ret = saveAAAServerList();
944 if (!ret.isSuccess()) {
947 ret = saveAuthorizationList();
948 if (!ret.isSuccess()) {
953 return new Status(StatusCode.SUCCESS, null);
956 return new Status(StatusCode.INTERNALERROR,
957 "Failed to save user configurations");
961 public UserDetails loadUserByUsername(String username)
962 throws UsernameNotFoundException {
963 AuthenticatedUser user = activeUsers.get(username);
966 boolean enabled = true;
967 boolean accountNonExpired = true;
968 boolean credentialsNonExpired = true;
969 boolean accountNonLocked = true;
971 return new User(username, localUserConfigList.get(username)
972 .getPassword(), enabled, accountNonExpired,
973 credentialsNonExpired, accountNonLocked,
974 user.getGrantedAuthorities(getUserLevel(username)));
976 throw new UsernameNotFoundException("User not found " + username);
981 public boolean supports(Class<?> authentication) {
982 return UsernamePasswordAuthenticationToken.class
983 .isAssignableFrom(authentication);
988 public SecurityContextRepository getSecurityContextRepo() {
989 return securityContextRepo;
992 public void setSecurityContextRepo(
993 SecurityContextRepository securityContextRepo) {
994 this.securityContextRepo = securityContextRepo;
998 public Authentication authenticate(Authentication authentication)
999 throws AuthenticationException {
1001 if (StringUtils.isBlank((String) authentication.getCredentials())
1002 || StringUtils.isBlank((String) authentication.getPrincipal())) {
1003 throw new BadCredentialsException(
1004 "Username or credentials did not match");
1007 AuthResultEnum result = authenticate(
1008 (String) authentication.getPrincipal(),
1009 (String) authentication.getCredentials());
1010 if (result.equals(AuthResultEnum.AUTHOR_PASS)
1011 || result.equals(AuthResultEnum.AUTH_ACCEPT_LOC)
1012 || result.equals(AuthResultEnum.AUTH_ACCEPT)) {
1014 AuthenticatedUser user = activeUsers.get(authentication
1015 .getPrincipal().toString());
1018 throw new AuthenticationServiceException(
1019 "Authentication Failure");
1022 authentication = new UsernamePasswordAuthenticationToken(
1023 authentication.getPrincipal(),
1024 authentication.getCredentials(),
1025 user.getGrantedAuthorities(getUserLevel(authentication
1027 return authentication;
1030 throw new BadCredentialsException(
1031 "Username or credentials did not match");
1036 // Following are setters for use in unit testing
1037 void setLocalUserConfigList(ConcurrentMap<String, UserConfig> ucl) {
1039 this.localUserConfigList = ucl;
1043 void setRemoteServerConfigList(ConcurrentMap<String, ServerConfig> scl) {
1045 this.remoteServerConfigList = scl;
1049 void setAuthorizationConfList(ConcurrentMap<String, AuthorizationConfig> acl) {
1051 this.authorizationConfList = acl;
1055 void setActiveUsers(ConcurrentMap<String, AuthenticatedUser> au) {
1057 this.activeUsers = au;
1061 void setAuthProviders(ConcurrentMap<String, IAAAProvider> ap) {
1063 this.authProviders = ap;
1068 public ISessionManager getSessionManager() {
1069 return this.sessionMgr;
1072 public void setSessionMgr(ISessionManager sessionMgr) {
1073 this.sessionMgr = sessionMgr;
1077 public String getPassword(String username) {
1078 return localUserConfigList.get(username).getPassword();
1082 public boolean isRoleInUse(String role) {
1083 if (role == null || role.isEmpty()) {
1086 // Check against controller roles
1087 if (role.equals(UserLevel.SYSTEMADMIN.toString())
1088 || role.equals(UserLevel.NETWORKADMIN.toString())
1089 || role.equals(UserLevel.NETWORKOPERATOR.toString())) {
1092 // Check if container roles
1093 if (containerAuthorizationClient != null) {
1094 if (containerAuthorizationClient.isApplicationRole(role)) {
1098 // Finally if application role
1099 if (applicationAuthorizationClients != null) {
1100 for (IResourceAuthorization client : this.applicationAuthorizationClients) {
1101 if (client.isApplicationRole(role)) {