1 package org
.argeo
.cms
.auth
;
3 import static org
.argeo
.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
;
26 import javax
.servlet
.http
.HttpServletRequest
;
28 import org
.apache
.commons
.logging
.Log
;
29 import org
.apache
.commons
.logging
.LogFactory
;
30 import org
.argeo
.cms
.CmsException
;
31 import org
.argeo
.cms
.internal
.kernel
.Activator
;
32 import org
.argeo
.naming
.LdapAttrs
;
33 import org
.argeo
.node
.NodeConstants
;
34 import org
.argeo
.node
.security
.CryptoKeyring
;
35 import org
.argeo
.osgi
.useradmin
.AuthenticatingUser
;
36 import org
.argeo
.osgi
.useradmin
.IpaUtils
;
37 import org
.argeo
.osgi
.useradmin
.OsUserUtils
;
38 import org
.argeo
.osgi
.useradmin
.TokenUtils
;
39 import org
.osgi
.framework
.BundleContext
;
40 import org
.osgi
.framework
.FrameworkUtil
;
41 import org
.osgi
.framework
.ServiceReference
;
42 import org
.osgi
.service
.useradmin
.Authorization
;
43 import org
.osgi
.service
.useradmin
.Group
;
44 import org
.osgi
.service
.useradmin
.User
;
45 import org
.osgi
.service
.useradmin
.UserAdmin
;
47 public class UserAdminLoginModule
implements LoginModule
{
48 private final static Log log
= LogFactory
.getLog(UserAdminLoginModule
.class);
50 private Subject subject
;
51 private CallbackHandler callbackHandler
;
52 private Map
<String
, Object
> sharedState
= null;
54 private List
<String
> indexedUserProperties
= Arrays
55 .asList(new String
[] { LdapAttrs
.mail
.name(), LdapAttrs
.uid
.name(), LdapAttrs
.authPassword
.name() });
58 private BundleContext bc
;
59 private User authenticatedUser
= null;
60 private Locale locale
;
62 private Authorization bindAuthorization
= null;
64 private boolean singleUser
= Activator
.isSingleUser();
66 @SuppressWarnings("unchecked")
68 public void initialize(Subject subject
, CallbackHandler callbackHandler
, Map
<String
, ?
> sharedState
,
69 Map
<String
, ?
> options
) {
70 this.subject
= subject
;
72 bc
= FrameworkUtil
.getBundle(UserAdminLoginModule
.class).getBundleContext();
73 this.callbackHandler
= callbackHandler
;
74 this.sharedState
= (Map
<String
, Object
>) sharedState
;
75 } catch (Exception e
) {
76 throw new CmsException("Cannot initialize login module", e
);
81 public boolean login() throws LoginException
{
82 UserAdmin userAdmin
= Activator
.getUserAdmin();
83 final String username
;
84 final char[] password
;
85 Object certificateChain
= null;
86 if (sharedState
.containsKey(CmsAuthUtils
.SHARED_STATE_NAME
)
87 && sharedState
.containsKey(CmsAuthUtils
.SHARED_STATE_PWD
)) {
88 // NB: required by Basic http auth
89 username
= (String
) sharedState
.get(CmsAuthUtils
.SHARED_STATE_NAME
);
90 password
= (char[]) sharedState
.get(CmsAuthUtils
.SHARED_STATE_PWD
);
92 } else if (sharedState
.containsKey(CmsAuthUtils
.SHARED_STATE_NAME
)
93 && sharedState
.containsKey(CmsAuthUtils
.SHARED_STATE_CERTIFICATE_CHAIN
)) {
94 String certDn
= (String
) sharedState
.get(CmsAuthUtils
.SHARED_STATE_NAME
);
97 // ldapName = new LdapName(certificateName);
98 // } catch (InvalidNameException e) {
99 // e.printStackTrace();
102 // username = ldapName.getRdn(ldapName.size() - 1).getValue().toString();
104 certificateChain
= sharedState
.get(CmsAuthUtils
.SHARED_STATE_CERTIFICATE_CHAIN
);
106 } else if (singleUser
) {
107 username
= OsUserUtils
.getOsUsername();
111 // ask for username and password
112 NameCallback nameCallback
= new NameCallback("User");
113 PasswordCallback passwordCallback
= new PasswordCallback("Password", false);
114 LanguageCallback langCallback
= new LanguageCallback();
116 callbackHandler
.handle(new Callback
[] { nameCallback
, passwordCallback
, langCallback
});
117 } catch (IOException e
) {
118 throw new LoginException("Cannot handle callback: " + e
.getMessage());
119 } catch (UnsupportedCallbackException e
) {
124 locale
= langCallback
.getLocale();
126 locale
= Locale
.getDefault();
127 // FIXME add it to Subject
128 // Locale.setDefault(locale);
130 username
= nameCallback
.getName();
131 if (username
== null || username
.trim().equals("")) {
132 // authorization = userAdmin.getAuthorization(null);
133 throw new CredentialNotFoundException("No credentials provided");
135 if (passwordCallback
.getPassword() != null)
136 password
= passwordCallback
.getPassword();
138 throw new CredentialNotFoundException("No credentials provided");
139 sharedState
.put(CmsAuthUtils
.SHARED_STATE_NAME
, username
);
140 sharedState
.put(CmsAuthUtils
.SHARED_STATE_PWD
, password
);
142 User user
= searchForUser(userAdmin
, username
);
146 String token
= username
;
147 Group tokenGroup
= searchForToken(userAdmin
, token
);
148 if (tokenGroup
!= null) {
149 Authorization tokenAuthorization
= getAuthorizationFromToken(userAdmin
, tokenGroup
);
150 if (tokenAuthorization
!= null) {
151 bindAuthorization
= tokenAuthorization
;
152 authenticatedUser
= (User
) userAdmin
.getRole(bindAuthorization
.getName());
159 return true;// expect Kerberos
161 if (password
!= null) {
164 AuthenticatingUser authenticatingUser
= new AuthenticatingUser(user
.getName(), password
);
165 bindAuthorization
= userAdmin
.getAuthorization(authenticatingUser
);
166 // TODO check tokens as well
167 if (bindAuthorization
!= null) {
168 authenticatedUser
= user
;
171 } catch (Exception e
) {
173 if (log
.isTraceEnabled())
174 log
.trace("Bind failed", e
);
177 // works only if a connection password is provided
178 if (!user
.hasCredential(null, password
)) {
181 } else if (certificateChain
!= null) {
182 // TODO check CRLs/OSCP validity?
183 // NB: authorization in commit() will work only if an LDAP connection password
185 } else if (singleUser
) {
186 // TODO verify IP address?
188 throw new CredentialNotFoundException("No credentials provided");
191 authenticatedUser
= user
;
196 public boolean commit() throws LoginException
{
198 subject
.getPublicCredentials().add(Locale
.getDefault());
200 subject
.getPublicCredentials().add(locale
);
203 OsUserUtils
.loginAsSystemUser(subject
);
205 UserAdmin userAdmin
= Activator
.getUserAdmin();
206 Authorization authorization
;
207 if (callbackHandler
== null) {// anonymous
208 authorization
= userAdmin
.getAuthorization(null);
209 } else if (bindAuthorization
!= null) {// bind
210 authorization
= bindAuthorization
;
212 User authenticatingUser
;
213 Set
<KerberosPrincipal
> kerberosPrincipals
= subject
.getPrincipals(KerberosPrincipal
.class);
214 if (kerberosPrincipals
.isEmpty()) {
215 if (authenticatedUser
== null) {
216 if (log
.isTraceEnabled())
217 log
.trace("Neither kerberos nor user admin login succeeded. Login failed.");
220 authenticatingUser
= authenticatedUser
;
223 KerberosPrincipal kerberosPrincipal
= kerberosPrincipals
.iterator().next();
224 LdapName dn
= IpaUtils
.kerberosToDn(kerberosPrincipal
.getName());
225 authenticatingUser
= new AuthenticatingUser(dn
);
226 if (authenticatedUser
!= null && !authenticatingUser
.getName().equals(authenticatedUser
.getName()))
227 throw new LoginException("Kerberos login " + authenticatingUser
.getName()
228 + " is inconsistent with user admin login " + authenticatedUser
.getName());
230 authorization
= Subject
.doAs(subject
, new PrivilegedAction
<Authorization
>() {
233 public Authorization
run() {
234 Authorization authorization
= userAdmin
.getAuthorization(authenticatingUser
);
235 return authorization
;
239 if (authorization
== null)
240 throw new LoginException(
241 "User admin found no authorization for authenticated user " + authenticatingUser
.getName());
244 // Log and monitor new login
245 HttpServletRequest request
= (HttpServletRequest
) sharedState
.get(CmsAuthUtils
.SHARED_STATE_HTTP_REQUEST
);
246 CmsAuthUtils
.addAuthorization(subject
, authorization
, locale
, request
);
248 // Unlock keyring (underlying login to the JCR repository)
249 char[] password
= (char[]) sharedState
.get(CmsAuthUtils
.SHARED_STATE_PWD
);
250 if (password
!= null) {
251 ServiceReference
<CryptoKeyring
> keyringSr
= bc
.getServiceReference(CryptoKeyring
.class);
252 if (keyringSr
!= null) {
253 CryptoKeyring keyring
= bc
.getService(keyringSr
);
254 Subject
.doAs(subject
, new PrivilegedAction
<Void
>() {
259 keyring
.unlock(password
);
260 } catch (Exception e
) {
262 log
.warn("Could not unlock keyring with the password provided by " + authorization
.getName()
263 + ": " + e
.getMessage());
272 // Register CmsSession with initial subject
273 CmsAuthUtils
.registerSessionAuthorization(request
, subject
, authorization
, locale
);
275 if (log
.isDebugEnabled())
276 log
.debug("Logged in to CMS: " + subject
);
281 public boolean abort() throws LoginException
{
286 public boolean logout() throws LoginException
{
287 if (log
.isTraceEnabled())
288 log
.trace("Logging out from CMS... " + subject
);
289 // boolean httpSessionLogoutOk = CmsAuthUtils.logoutSession(bc,
291 CmsAuthUtils
.cleanUp(subject
);
295 protected User
searchForUser(UserAdmin userAdmin
, String providedUsername
) {
297 // TODO check value null or empty
298 Set
<User
> collectedUsers
= new HashSet
<>();
302 for (String attr
: indexedUserProperties
) {
303 user
= userAdmin
.getUser(attr
, providedUsername
);
305 collectedUsers
.add(user
);
307 if (collectedUsers
.size() == 1) {
308 user
= collectedUsers
.iterator().next();
310 } else if (collectedUsers
.size() > 1) {
311 log
.warn(collectedUsers
.size() + " users for provided username" + providedUsername
);
313 // try DN as a last resort
315 user
= (User
) userAdmin
.getRole(providedUsername
);
318 } catch (Exception e
) {
322 } catch (Exception e
) {
323 if (log
.isTraceEnabled())
324 log
.warn("Cannot search for user " + providedUsername
, e
);
330 protected Group
searchForToken(UserAdmin userAdmin
, String token
) {
331 String dn
= cn
+ "=" + token
+ "," + NodeConstants
.TOKENS_BASEDN
;
332 Group tokenGroup
= (Group
) userAdmin
.getRole(dn
);
336 protected Authorization
getAuthorizationFromToken(UserAdmin userAdmin
, Group tokenGroup
) {
337 if (TokenUtils
.isExpired(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
);