1 package org
.argeo
.cms
.auth
;
3 import static org
.argeo
.util
.naming
.LdapAttrs
.cn
;
5 import java
.io
.IOException
;
6 import java
.security
.PrivilegedAction
;
7 import java
.util
.Arrays
;
8 import java
.util
.HashSet
;
10 import java
.util
.Locale
;
14 import javax
.naming
.ldap
.LdapName
;
15 import javax
.security
.auth
.Subject
;
16 import javax
.security
.auth
.callback
.Callback
;
17 import javax
.security
.auth
.callback
.CallbackHandler
;
18 import javax
.security
.auth
.callback
.LanguageCallback
;
19 import javax
.security
.auth
.callback
.NameCallback
;
20 import javax
.security
.auth
.callback
.PasswordCallback
;
21 import javax
.security
.auth
.callback
.UnsupportedCallbackException
;
22 import javax
.security
.auth
.kerberos
.KerberosPrincipal
;
23 import javax
.security
.auth
.login
.CredentialNotFoundException
;
24 import javax
.security
.auth
.login
.LoginException
;
25 import javax
.security
.auth
.spi
.LoginModule
;
27 import org
.argeo
.api
.cms
.CmsConstants
;
28 import org
.argeo
.api
.cms
.CmsLog
;
29 import org
.argeo
.cms
.internal
.osgi
.NodeUserAdmin
;
30 import org
.argeo
.cms
.internal
.runtime
.CmsContextImpl
;
31 import org
.argeo
.cms
.security
.CryptoKeyring
;
32 import org
.argeo
.osgi
.useradmin
.AuthenticatingUser
;
33 import org
.argeo
.osgi
.useradmin
.IpaUtils
;
34 import org
.argeo
.osgi
.useradmin
.TokenUtils
;
35 import org
.argeo
.util
.naming
.LdapAttrs
;
36 import org
.osgi
.framework
.BundleContext
;
37 import org
.osgi
.framework
.FrameworkUtil
;
38 import org
.osgi
.framework
.ServiceReference
;
39 import org
.osgi
.service
.useradmin
.Authorization
;
40 import org
.osgi
.service
.useradmin
.Group
;
41 import org
.osgi
.service
.useradmin
.User
;
42 import org
.osgi
.service
.useradmin
.UserAdmin
;
45 * Use the {@link UserAdmin} in the OSGi registry as the basis for
48 public class UserAdminLoginModule
implements LoginModule
{
49 private final static CmsLog log
= CmsLog
.getLog(UserAdminLoginModule
.class);
51 private Subject subject
;
52 private CallbackHandler callbackHandler
;
53 private Map
<String
, Object
> sharedState
= null;
55 private List
<String
> indexedUserProperties
= Arrays
56 .asList(new String
[] { LdapAttrs
.mail
.name(), LdapAttrs
.uid
.name(), LdapAttrs
.authPassword
.name() });
59 private BundleContext bc
;
60 private User authenticatedUser
= null;
61 private Locale locale
;
63 private Authorization bindAuthorization
= null;
65 // private boolean singleUser = Activator.isSingleUser();
67 @SuppressWarnings("unchecked")
69 public void initialize(Subject subject
, CallbackHandler callbackHandler
, Map
<String
, ?
> sharedState
,
70 Map
<String
, ?
> options
) {
71 this.subject
= subject
;
73 bc
= FrameworkUtil
.getBundle(UserAdminLoginModule
.class).getBundleContext();
74 this.callbackHandler
= callbackHandler
;
75 this.sharedState
= (Map
<String
, Object
>) sharedState
;
76 } catch (Exception e
) {
77 throw new IllegalStateException("Cannot initialize login module", e
);
82 public boolean login() throws LoginException
{
83 UserAdmin userAdmin
= CmsContextImpl
.getUserAdmin();
84 final String username
;
85 final char[] password
;
86 Object certificateChain
= null;
87 boolean preauth
= false;
88 if (sharedState
.containsKey(CmsAuthUtils
.SHARED_STATE_NAME
)
89 && sharedState
.containsKey(CmsAuthUtils
.SHARED_STATE_PWD
)) {
90 // NB: required by Basic http auth
91 username
= (String
) sharedState
.get(CmsAuthUtils
.SHARED_STATE_NAME
);
92 password
= (char[]) sharedState
.get(CmsAuthUtils
.SHARED_STATE_PWD
);
94 } else if (sharedState
.containsKey(CmsAuthUtils
.SHARED_STATE_NAME
)
95 && sharedState
.containsKey(CmsAuthUtils
.SHARED_STATE_CERTIFICATE_CHAIN
)) {
96 String certDn
= (String
) sharedState
.get(CmsAuthUtils
.SHARED_STATE_NAME
);
99 // ldapName = new LdapName(certificateName);
100 // } catch (InvalidNameException e) {
101 // e.printStackTrace();
104 // username = ldapName.getRdn(ldapName.size() - 1).getValue().toString();
106 certificateChain
= sharedState
.get(CmsAuthUtils
.SHARED_STATE_CERTIFICATE_CHAIN
);
108 } else if (sharedState
.containsKey(CmsAuthUtils
.SHARED_STATE_NAME
)
109 && sharedState
.containsKey(CmsAuthUtils
.SHARED_STATE_REMOTE_ADDR
)
110 && sharedState
.containsKey(CmsAuthUtils
.SHARED_STATE_REMOTE_PORT
)) {// ident
111 username
= (String
) sharedState
.get(CmsAuthUtils
.SHARED_STATE_NAME
);
114 // } else if (singleUser) {
115 // username = OsUserUtils.getOsUsername();
117 // // TODO retrieve from http session
118 // locale = Locale.getDefault();
121 // ask for username and password
122 NameCallback nameCallback
= new NameCallback("User");
123 PasswordCallback passwordCallback
= new PasswordCallback("Password", false);
124 LanguageCallback langCallback
= new LanguageCallback();
126 callbackHandler
.handle(new Callback
[] { nameCallback
, passwordCallback
, langCallback
});
127 } catch (IOException e
) {
128 throw new LoginException("Cannot handle callback: " + e
.getMessage());
129 } catch (UnsupportedCallbackException e
) {
134 locale
= langCallback
.getLocale();
136 locale
= Locale
.getDefault();
137 // FIXME add it to Subject
138 // Locale.setDefault(locale);
140 username
= nameCallback
.getName();
141 if (username
== null || username
.trim().equals("")) {
142 // authorization = userAdmin.getAuthorization(null);
143 throw new CredentialNotFoundException("No credentials provided");
145 if (passwordCallback
.getPassword() != null)
146 password
= passwordCallback
.getPassword();
148 throw new CredentialNotFoundException("No credentials provided");
149 sharedState
.put(CmsAuthUtils
.SHARED_STATE_NAME
, username
);
150 sharedState
.put(CmsAuthUtils
.SHARED_STATE_PWD
, password
);
152 User user
= searchForUser(userAdmin
, username
);
156 String token
= username
;
157 Group tokenGroup
= searchForToken(userAdmin
, token
);
158 if (tokenGroup
!= null) {
159 Authorization tokenAuthorization
= getAuthorizationFromToken(userAdmin
, tokenGroup
);
160 if (tokenAuthorization
!= null) {
161 bindAuthorization
= tokenAuthorization
;
162 authenticatedUser
= (User
) userAdmin
.getRole(bindAuthorization
.getName());
169 return true;// expect Kerberos
171 if (password
!= null) {
174 AuthenticatingUser authenticatingUser
= new AuthenticatingUser(user
.getName(), password
);
175 bindAuthorization
= userAdmin
.getAuthorization(authenticatingUser
);
176 // TODO check tokens as well
177 if (bindAuthorization
!= null) {
178 authenticatedUser
= user
;
181 } catch (Exception e
) {
183 if (log
.isTraceEnabled())
184 log
.trace("Bind failed", e
);
187 // works only if a connection password is provided
188 if (!user
.hasCredential(null, password
)) {
191 } else if (certificateChain
!= null) {
192 // TODO check CRLs/OSCP validity?
193 // NB: authorization in commit() will work only if an LDAP connection password
195 // } else if (singleUser) {
196 // // TODO verify IP address?
197 } else if (preauth
) {
200 throw new CredentialNotFoundException("No credentials provided");
203 authenticatedUser
= user
;
208 public boolean commit() throws LoginException
{
210 subject
.getPublicCredentials().add(locale
);
213 // OsUserUtils.loginAsSystemUser(subject);
215 UserAdmin userAdmin
= CmsContextImpl
.getUserAdmin();
216 Authorization authorization
;
217 if (callbackHandler
== null) {// anonymous
218 authorization
= userAdmin
.getAuthorization(null);
219 } else if (bindAuthorization
!= null) {// bind
220 authorization
= bindAuthorization
;
222 User authenticatingUser
;
223 Set
<KerberosPrincipal
> kerberosPrincipals
= subject
.getPrincipals(KerberosPrincipal
.class);
224 if (kerberosPrincipals
.isEmpty()) {
225 if (authenticatedUser
== null) {
226 if (log
.isTraceEnabled())
227 log
.trace("Neither kerberos nor user admin login succeeded. Login failed.");
228 throw new CredentialNotFoundException("Bad credentials.");
230 authenticatingUser
= authenticatedUser
;
233 KerberosPrincipal kerberosPrincipal
= kerberosPrincipals
.iterator().next();
234 LdapName dn
= IpaUtils
.kerberosToDn(kerberosPrincipal
.getName());
235 authenticatingUser
= new AuthenticatingUser(dn
);
236 if (authenticatedUser
!= null && !authenticatingUser
.getName().equals(authenticatedUser
.getName()))
237 throw new LoginException("Kerberos login " + authenticatingUser
.getName()
238 + " is inconsistent with user admin login " + authenticatedUser
.getName());
240 authorization
= Subject
.doAs(subject
, new PrivilegedAction
<Authorization
>() {
243 public Authorization
run() {
244 Authorization authorization
= userAdmin
.getAuthorization(authenticatingUser
);
245 return authorization
;
249 if (authorization
== null)
250 throw new LoginException(
251 "User admin found no authorization for authenticated user " + authenticatingUser
.getName());
254 // Log and monitor new login
255 RemoteAuthRequest request
= (RemoteAuthRequest
) sharedState
.get(CmsAuthUtils
.SHARED_STATE_HTTP_REQUEST
);
256 CmsAuthUtils
.addAuthorization(subject
, authorization
);
258 // Unlock keyring (underlying login to the JCR repository)
259 char[] password
= (char[]) sharedState
.get(CmsAuthUtils
.SHARED_STATE_PWD
);
260 if (password
!= null) {
261 ServiceReference
<CryptoKeyring
> keyringSr
= bc
.getServiceReference(CryptoKeyring
.class);
262 if (keyringSr
!= null) {
263 CryptoKeyring keyring
= bc
.getService(keyringSr
);
264 Subject
.doAs(subject
, new PrivilegedAction
<Void
>() {
269 keyring
.unlock(password
);
270 } catch (Exception e
) {
272 log
.warn("Could not unlock keyring with the password provided by " + authorization
.getName()
273 + ": " + e
.getMessage());
282 // Register CmsSession with initial subject
283 CmsAuthUtils
.registerSessionAuthorization(request
, subject
, authorization
, locale
);
285 if (log
.isDebugEnabled())
286 log
.debug("Logged in to CMS: " + subject
);
291 public boolean abort() throws LoginException
{
296 public boolean logout() throws LoginException
{
297 if (log
.isTraceEnabled())
298 log
.trace("Logging out from CMS... " + subject
);
299 CmsAuthUtils
.cleanUp(subject
);
303 protected User
searchForUser(UserAdmin userAdmin
, String providedUsername
) {
305 // TODO check value null or empty
306 Set
<User
> collectedUsers
= new HashSet
<>();
311 for (String attr
: indexedUserProperties
) {
312 user
= userAdmin
.getUser(attr
, providedUsername
);
314 collectedUsers
.add(user
);
316 if (collectedUsers
.size() == 1) {
317 user
= collectedUsers
.iterator().next();
319 } else if (collectedUsers
.size() > 1) {
320 log
.warn(collectedUsers
.size() + " users for provided username" + providedUsername
);
322 // try DN as a last resort
324 user
= (User
) userAdmin
.getRole(providedUsername
);
327 } catch (Exception e
) {
331 } catch (Exception e
) {
332 if (log
.isTraceEnabled())
333 log
.warn("Cannot search for user " + providedUsername
, e
);
339 protected Group
searchForToken(UserAdmin userAdmin
, String token
) {
340 String dn
= cn
+ "=" + token
+ "," + CmsConstants
.TOKENS_BASEDN
;
341 Group tokenGroup
= (Group
) userAdmin
.getRole(dn
);
345 protected Authorization
getAuthorizationFromToken(UserAdmin userAdmin
, Group tokenGroup
) {
346 if (TokenUtils
.isExpired(tokenGroup
))
348 // String expiryDateStr = (String) tokenGroup.getProperties().get(description.name());
349 // if (expiryDateStr != null) {
350 // Instant expiryDate = NamingUtils.ldapDateToInstant(expiryDateStr);
351 // if (expiryDate.isBefore(Instant.now())) {
352 // if (log.isDebugEnabled())
353 // log.debug("Token " + tokenGroup.getName() + " has expired.");
357 String userDn
= TokenUtils
.userDn(tokenGroup
);
358 User user
= (User
) userAdmin
.getRole(userDn
);
359 Authorization auth
= userAdmin
.getAuthorization(user
);