1 package org
.argeo
.cms
.auth
;
3 import static org
.argeo
.naming
.LdapAttrs
.cn
;
4 import static org
.argeo
.naming
.LdapAttrs
.description
;
6 import java
.io
.IOException
;
7 import java
.security
.PrivilegedAction
;
8 import java
.time
.Instant
;
9 import java
.util
.Arrays
;
10 import java
.util
.HashSet
;
11 import java
.util
.List
;
12 import java
.util
.Locale
;
16 import javax
.naming
.ldap
.LdapName
;
17 import javax
.security
.auth
.Subject
;
18 import javax
.security
.auth
.callback
.Callback
;
19 import javax
.security
.auth
.callback
.CallbackHandler
;
20 import javax
.security
.auth
.callback
.LanguageCallback
;
21 import javax
.security
.auth
.callback
.NameCallback
;
22 import javax
.security
.auth
.callback
.PasswordCallback
;
23 import javax
.security
.auth
.callback
.UnsupportedCallbackException
;
24 import javax
.security
.auth
.kerberos
.KerberosPrincipal
;
25 import javax
.security
.auth
.login
.CredentialNotFoundException
;
26 import javax
.security
.auth
.login
.LoginException
;
27 import javax
.security
.auth
.spi
.LoginModule
;
28 import javax
.servlet
.http
.HttpServletRequest
;
30 import org
.apache
.commons
.logging
.Log
;
31 import org
.apache
.commons
.logging
.LogFactory
;
32 import org
.argeo
.cms
.CmsException
;
33 import org
.argeo
.cms
.internal
.kernel
.Activator
;
34 import org
.argeo
.naming
.LdapAttrs
;
35 import org
.argeo
.naming
.NamingUtils
;
36 import org
.argeo
.node
.NodeConstants
;
37 import org
.argeo
.node
.security
.CryptoKeyring
;
38 import org
.argeo
.osgi
.useradmin
.AuthenticatingUser
;
39 import org
.argeo
.osgi
.useradmin
.IpaUtils
;
40 import org
.argeo
.osgi
.useradmin
.OsUserUtils
;
41 import org
.osgi
.framework
.BundleContext
;
42 import org
.osgi
.framework
.FrameworkUtil
;
43 import org
.osgi
.framework
.ServiceReference
;
44 import org
.osgi
.service
.useradmin
.Authorization
;
45 import org
.osgi
.service
.useradmin
.Group
;
46 import org
.osgi
.service
.useradmin
.User
;
47 import org
.osgi
.service
.useradmin
.UserAdmin
;
49 public class UserAdminLoginModule
implements LoginModule
{
50 private final static Log log
= LogFactory
.getLog(UserAdminLoginModule
.class);
52 private Subject subject
;
53 private CallbackHandler callbackHandler
;
54 private Map
<String
, Object
> sharedState
= null;
56 private List
<String
> indexedUserProperties
= Arrays
57 .asList(new String
[] { LdapAttrs
.mail
.name(), LdapAttrs
.uid
.name(), LdapAttrs
.authPassword
.name() });
60 private BundleContext bc
;
61 private User authenticatedUser
= null;
62 private Locale locale
;
64 private Authorization bindAuthorization
= null;
66 private boolean singleUser
= Activator
.isSingleUser();
68 @SuppressWarnings("unchecked")
70 public void initialize(Subject subject
, CallbackHandler callbackHandler
, Map
<String
, ?
> sharedState
,
71 Map
<String
, ?
> options
) {
72 this.subject
= subject
;
74 bc
= FrameworkUtil
.getBundle(UserAdminLoginModule
.class).getBundleContext();
75 this.callbackHandler
= callbackHandler
;
76 this.sharedState
= (Map
<String
, Object
>) sharedState
;
77 } catch (Exception e
) {
78 throw new CmsException("Cannot initialize login module", e
);
83 public boolean login() throws LoginException
{
84 UserAdmin userAdmin
= Activator
.getUserAdmin();
85 final String username
;
86 final char[] password
;
87 Object certificateChain
= null;
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 (singleUser
) {
109 username
= OsUserUtils
.getOsUsername();
113 // ask for username and password
114 NameCallback nameCallback
= new NameCallback("User");
115 PasswordCallback passwordCallback
= new PasswordCallback("Password", false);
116 LanguageCallback langCallback
= new LanguageCallback();
118 callbackHandler
.handle(new Callback
[] { nameCallback
, passwordCallback
, langCallback
});
119 } catch (IOException e
) {
120 throw new LoginException("Cannot handle callback: " + e
.getMessage());
121 } catch (UnsupportedCallbackException e
) {
126 locale
= langCallback
.getLocale();
128 locale
= Locale
.getDefault();
129 // FIXME add it to Subject
130 // Locale.setDefault(locale);
132 username
= nameCallback
.getName();
133 if (username
== null || username
.trim().equals("")) {
134 // authorization = userAdmin.getAuthorization(null);
135 throw new CredentialNotFoundException("No credentials provided");
137 if (passwordCallback
.getPassword() != null)
138 password
= passwordCallback
.getPassword();
140 throw new CredentialNotFoundException("No credentials provided");
141 sharedState
.put(CmsAuthUtils
.SHARED_STATE_NAME
, username
);
142 sharedState
.put(CmsAuthUtils
.SHARED_STATE_PWD
, password
);
144 User user
= searchForUser(userAdmin
, username
);
148 String token
= username
;
149 Group tokenGroup
= searchForToken(userAdmin
, token
);
150 if (tokenGroup
!= null) {
151 Authorization tokenAuthorization
= getAuthorizationFromToken(userAdmin
, tokenGroup
);
152 if (tokenAuthorization
!= null) {
153 bindAuthorization
= tokenAuthorization
;
154 authenticatedUser
= (User
) userAdmin
.getRole(bindAuthorization
.getName());
161 return true;// expect Kerberos
163 if (password
!= null) {
166 AuthenticatingUser authenticatingUser
= new AuthenticatingUser(user
.getName(), password
);
167 bindAuthorization
= userAdmin
.getAuthorization(authenticatingUser
);
168 // TODO check tokens as well
169 if (bindAuthorization
!= null) {
170 authenticatedUser
= user
;
173 } catch (Exception e
) {
175 if (log
.isTraceEnabled())
176 log
.trace("Bind failed", e
);
179 // works only if a connection password is provided
180 if (!user
.hasCredential(null, password
)) {
183 } else if (certificateChain
!= null) {
184 // TODO check CRLs/OSCP validity?
185 // NB: authorization in commit() will work only if an LDAP connection password
187 } else if (singleUser
) {
188 // TODO verify IP address?
190 throw new CredentialNotFoundException("No credentials provided");
193 authenticatedUser
= user
;
198 public boolean commit() throws LoginException
{
200 subject
.getPublicCredentials().add(Locale
.getDefault());
202 subject
.getPublicCredentials().add(locale
);
205 OsUserUtils
.loginAsSystemUser(subject
);
207 UserAdmin userAdmin
= Activator
.getUserAdmin();
208 Authorization authorization
;
209 if (callbackHandler
== null) {// anonymous
210 authorization
= userAdmin
.getAuthorization(null);
211 } else if (bindAuthorization
!= null) {// bind
212 authorization
= bindAuthorization
;
214 User authenticatingUser
;
215 Set
<KerberosPrincipal
> kerberosPrincipals
= subject
.getPrincipals(KerberosPrincipal
.class);
216 if (kerberosPrincipals
.isEmpty()) {
217 if (authenticatedUser
== null) {
218 if (log
.isTraceEnabled())
219 log
.trace("Neither kerberos nor user admin login succeeded. Login failed.");
222 authenticatingUser
= authenticatedUser
;
225 KerberosPrincipal kerberosPrincipal
= kerberosPrincipals
.iterator().next();
226 LdapName dn
= IpaUtils
.kerberosToDn(kerberosPrincipal
.getName());
227 authenticatingUser
= new AuthenticatingUser(dn
);
228 if (authenticatedUser
!= null && !authenticatingUser
.getName().equals(authenticatedUser
.getName()))
229 throw new LoginException("Kerberos login " + authenticatingUser
.getName()
230 + " is inconsistent with user admin login " + authenticatedUser
.getName());
232 authorization
= Subject
.doAs(subject
, new PrivilegedAction
<Authorization
>() {
235 public Authorization
run() {
236 Authorization authorization
= userAdmin
.getAuthorization(authenticatingUser
);
237 return authorization
;
241 if (authorization
== null)
242 throw new LoginException(
243 "User admin found no authorization for authenticated user " + authenticatingUser
.getName());
246 // Log and monitor new login
247 HttpServletRequest request
= (HttpServletRequest
) sharedState
.get(CmsAuthUtils
.SHARED_STATE_HTTP_REQUEST
);
248 CmsAuthUtils
.addAuthorization(subject
, authorization
, locale
, request
);
250 // Unlock keyring (underlying login to the JCR repository)
251 char[] password
= (char[]) sharedState
.get(CmsAuthUtils
.SHARED_STATE_PWD
);
252 if (password
!= null) {
253 ServiceReference
<CryptoKeyring
> keyringSr
= bc
.getServiceReference(CryptoKeyring
.class);
254 if (keyringSr
!= null) {
255 CryptoKeyring keyring
= bc
.getService(keyringSr
);
256 Subject
.doAs(subject
, new PrivilegedAction
<Void
>() {
261 keyring
.unlock(password
);
262 } catch (Exception e
) {
264 log
.warn("Could not unlock keyring with the password provided by " + authorization
.getName()
265 + ": " + e
.getMessage());
274 // Register CmsSession with initial subject
275 CmsAuthUtils
.registerSessionAuthorization(request
, subject
, authorization
, locale
);
277 if (log
.isDebugEnabled())
278 log
.debug("Logged in to CMS: " + subject
);
283 public boolean abort() throws LoginException
{
288 public boolean logout() throws LoginException
{
289 if (log
.isTraceEnabled())
290 log
.trace("Logging out from CMS... " + subject
);
291 // boolean httpSessionLogoutOk = CmsAuthUtils.logoutSession(bc,
293 CmsAuthUtils
.cleanUp(subject
);
297 protected User
searchForUser(UserAdmin userAdmin
, String providedUsername
) {
299 // TODO check value null or empty
300 Set
<User
> collectedUsers
= new HashSet
<>();
304 for (String attr
: indexedUserProperties
) {
305 user
= userAdmin
.getUser(attr
, providedUsername
);
307 collectedUsers
.add(user
);
309 if (collectedUsers
.size() == 1) {
310 user
= collectedUsers
.iterator().next();
312 } else if (collectedUsers
.size() > 1) {
313 log
.warn(collectedUsers
.size() + " users for provided username" + providedUsername
);
315 // try DN as a last resort
317 user
= (User
) userAdmin
.getRole(providedUsername
);
320 } catch (Exception e
) {
324 } catch (Exception e
) {
325 if (log
.isTraceEnabled())
326 log
.warn("Cannot search for user " + providedUsername
, e
);
332 protected Group
searchForToken(UserAdmin userAdmin
, String token
) {
333 String dn
= cn
+ "=" + token
+ "," + NodeConstants
.TOKENS_BASEDN
;
334 Group tokenGroup
= (Group
) userAdmin
.getRole(dn
);
338 protected Authorization
getAuthorizationFromToken(UserAdmin userAdmin
, Group tokenGroup
) {
339 String expiryDateStr
= (String
) tokenGroup
.getProperties().get(description
.name());
340 if (expiryDateStr
!= null) {
341 Instant expiryDate
= NamingUtils
.ldapDateToInstant(expiryDateStr
);
342 if (expiryDate
.isBefore(Instant
.now())) {
343 if (log
.isDebugEnabled())
344 log
.debug("Token " + tokenGroup
.getName() + " has expired.");
348 Authorization auth
= userAdmin
.getAuthorization(tokenGroup
);