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
.api
.NodeConstants
;
31 import org
.argeo
.api
.security
.CryptoKeyring
;
32 import org
.argeo
.cms
.internal
.kernel
.Activator
;
33 import org
.argeo
.naming
.LdapAttrs
;
34 import org
.argeo
.osgi
.useradmin
.AuthenticatingUser
;
35 import org
.argeo
.osgi
.useradmin
.IpaUtils
;
36 import org
.argeo
.osgi
.useradmin
.TokenUtils
;
37 import org
.osgi
.framework
.BundleContext
;
38 import org
.osgi
.framework
.FrameworkUtil
;
39 import org
.osgi
.framework
.ServiceReference
;
40 import org
.osgi
.service
.useradmin
.Authorization
;
41 import org
.osgi
.service
.useradmin
.Group
;
42 import org
.osgi
.service
.useradmin
.User
;
43 import org
.osgi
.service
.useradmin
.UserAdmin
;
46 * Use the {@link UserAdmin} in the OSGi registry as the basis for
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 IllegalStateException("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 boolean preauth
= false;
89 if (sharedState
.containsKey(CmsAuthUtils
.SHARED_STATE_NAME
)
90 && sharedState
.containsKey(CmsAuthUtils
.SHARED_STATE_PWD
)) {
91 // NB: required by Basic http auth
92 username
= (String
) sharedState
.get(CmsAuthUtils
.SHARED_STATE_NAME
);
93 password
= (char[]) sharedState
.get(CmsAuthUtils
.SHARED_STATE_PWD
);
95 } else if (sharedState
.containsKey(CmsAuthUtils
.SHARED_STATE_NAME
)
96 && sharedState
.containsKey(CmsAuthUtils
.SHARED_STATE_CERTIFICATE_CHAIN
)) {
97 String certDn
= (String
) sharedState
.get(CmsAuthUtils
.SHARED_STATE_NAME
);
100 // ldapName = new LdapName(certificateName);
101 // } catch (InvalidNameException e) {
102 // e.printStackTrace();
105 // username = ldapName.getRdn(ldapName.size() - 1).getValue().toString();
107 certificateChain
= sharedState
.get(CmsAuthUtils
.SHARED_STATE_CERTIFICATE_CHAIN
);
109 } else if (sharedState
.containsKey(CmsAuthUtils
.SHARED_STATE_NAME
)
110 && sharedState
.containsKey(CmsAuthUtils
.SHARED_STATE_REMOTE_ADDR
)
111 && sharedState
.containsKey(CmsAuthUtils
.SHARED_STATE_REMOTE_PORT
)) {// ident
112 username
= (String
) sharedState
.get(CmsAuthUtils
.SHARED_STATE_NAME
);
115 // } else if (singleUser) {
116 // username = OsUserUtils.getOsUsername();
118 // // TODO retrieve from http session
119 // locale = Locale.getDefault();
122 // ask for username and password
123 NameCallback nameCallback
= new NameCallback("User");
124 PasswordCallback passwordCallback
= new PasswordCallback("Password", false);
125 LanguageCallback langCallback
= new LanguageCallback();
127 callbackHandler
.handle(new Callback
[] { nameCallback
, passwordCallback
, langCallback
});
128 } catch (IOException e
) {
129 throw new LoginException("Cannot handle callback: " + e
.getMessage());
130 } catch (UnsupportedCallbackException e
) {
135 locale
= langCallback
.getLocale();
137 locale
= Locale
.getDefault();
138 // FIXME add it to Subject
139 // Locale.setDefault(locale);
141 username
= nameCallback
.getName();
142 if (username
== null || username
.trim().equals("")) {
143 // authorization = userAdmin.getAuthorization(null);
144 throw new CredentialNotFoundException("No credentials provided");
146 if (passwordCallback
.getPassword() != null)
147 password
= passwordCallback
.getPassword();
149 throw new CredentialNotFoundException("No credentials provided");
150 sharedState
.put(CmsAuthUtils
.SHARED_STATE_NAME
, username
);
151 sharedState
.put(CmsAuthUtils
.SHARED_STATE_PWD
, password
);
153 User user
= searchForUser(userAdmin
, username
);
157 String token
= username
;
158 Group tokenGroup
= searchForToken(userAdmin
, token
);
159 if (tokenGroup
!= null) {
160 Authorization tokenAuthorization
= getAuthorizationFromToken(userAdmin
, tokenGroup
);
161 if (tokenAuthorization
!= null) {
162 bindAuthorization
= tokenAuthorization
;
163 authenticatedUser
= (User
) userAdmin
.getRole(bindAuthorization
.getName());
170 return true;// expect Kerberos
172 if (password
!= null) {
175 AuthenticatingUser authenticatingUser
= new AuthenticatingUser(user
.getName(), password
);
176 bindAuthorization
= userAdmin
.getAuthorization(authenticatingUser
);
177 // TODO check tokens as well
178 if (bindAuthorization
!= null) {
179 authenticatedUser
= user
;
182 } catch (Exception e
) {
184 if (log
.isTraceEnabled())
185 log
.trace("Bind failed", e
);
188 // works only if a connection password is provided
189 if (!user
.hasCredential(null, password
)) {
192 } else if (certificateChain
!= null) {
193 // TODO check CRLs/OSCP validity?
194 // NB: authorization in commit() will work only if an LDAP connection password
196 // } else if (singleUser) {
197 // // TODO verify IP address?
198 } else if (preauth
) {
201 throw new CredentialNotFoundException("No credentials provided");
204 authenticatedUser
= user
;
209 public boolean commit() throws LoginException
{
211 subject
.getPublicCredentials().add(locale
);
214 // OsUserUtils.loginAsSystemUser(subject);
216 UserAdmin userAdmin
= Activator
.getUserAdmin();
217 Authorization authorization
;
218 if (callbackHandler
== null) {// anonymous
219 authorization
= userAdmin
.getAuthorization(null);
220 } else if (bindAuthorization
!= null) {// bind
221 authorization
= bindAuthorization
;
223 User authenticatingUser
;
224 Set
<KerberosPrincipal
> kerberosPrincipals
= subject
.getPrincipals(KerberosPrincipal
.class);
225 if (kerberosPrincipals
.isEmpty()) {
226 if (authenticatedUser
== null) {
227 if (log
.isTraceEnabled())
228 log
.trace("Neither kerberos nor user admin login succeeded. Login failed.");
229 throw new CredentialNotFoundException("Bad credentials.");
231 authenticatingUser
= authenticatedUser
;
234 KerberosPrincipal kerberosPrincipal
= kerberosPrincipals
.iterator().next();
235 LdapName dn
= IpaUtils
.kerberosToDn(kerberosPrincipal
.getName());
236 authenticatingUser
= new AuthenticatingUser(dn
);
237 if (authenticatedUser
!= null && !authenticatingUser
.getName().equals(authenticatedUser
.getName()))
238 throw new LoginException("Kerberos login " + authenticatingUser
.getName()
239 + " is inconsistent with user admin login " + authenticatedUser
.getName());
241 authorization
= Subject
.doAs(subject
, new PrivilegedAction
<Authorization
>() {
244 public Authorization
run() {
245 Authorization authorization
= userAdmin
.getAuthorization(authenticatingUser
);
246 return authorization
;
250 if (authorization
== null)
251 throw new LoginException(
252 "User admin found no authorization for authenticated user " + authenticatingUser
.getName());
255 // Log and monitor new login
256 HttpServletRequest request
= (HttpServletRequest
) sharedState
.get(CmsAuthUtils
.SHARED_STATE_HTTP_REQUEST
);
257 CmsAuthUtils
.addAuthorization(subject
, authorization
);
259 // Unlock keyring (underlying login to the JCR repository)
260 char[] password
= (char[]) sharedState
.get(CmsAuthUtils
.SHARED_STATE_PWD
);
261 if (password
!= null) {
262 ServiceReference
<CryptoKeyring
> keyringSr
= bc
.getServiceReference(CryptoKeyring
.class);
263 if (keyringSr
!= null) {
264 CryptoKeyring keyring
= bc
.getService(keyringSr
);
265 Subject
.doAs(subject
, new PrivilegedAction
<Void
>() {
270 keyring
.unlock(password
);
271 } catch (Exception e
) {
273 log
.warn("Could not unlock keyring with the password provided by " + authorization
.getName()
274 + ": " + e
.getMessage());
283 // Register CmsSession with initial subject
284 CmsAuthUtils
.registerSessionAuthorization(request
, subject
, authorization
, locale
);
286 if (log
.isDebugEnabled())
287 log
.debug("Logged in to CMS: " + subject
);
292 public boolean abort() throws LoginException
{
297 public boolean logout() throws LoginException
{
298 if (log
.isTraceEnabled())
299 log
.trace("Logging out from CMS... " + subject
);
300 CmsAuthUtils
.cleanUp(subject
);
304 protected User
searchForUser(UserAdmin userAdmin
, String providedUsername
) {
306 // TODO check value null or empty
307 Set
<User
> collectedUsers
= new HashSet
<>();
312 for (String attr
: indexedUserProperties
) {
313 user
= userAdmin
.getUser(attr
, providedUsername
);
315 collectedUsers
.add(user
);
317 if (collectedUsers
.size() == 1) {
318 user
= collectedUsers
.iterator().next();
320 } else if (collectedUsers
.size() > 1) {
321 log
.warn(collectedUsers
.size() + " users for provided username" + providedUsername
);
323 // try DN as a last resort
325 user
= (User
) userAdmin
.getRole(providedUsername
);
328 } catch (Exception e
) {
332 } catch (Exception e
) {
333 if (log
.isTraceEnabled())
334 log
.warn("Cannot search for user " + providedUsername
, e
);
340 protected Group
searchForToken(UserAdmin userAdmin
, String token
) {
341 String dn
= cn
+ "=" + token
+ "," + NodeConstants
.TOKENS_BASEDN
;
342 Group tokenGroup
= (Group
) userAdmin
.getRole(dn
);
346 protected Authorization
getAuthorizationFromToken(UserAdmin userAdmin
, Group tokenGroup
) {
347 if (TokenUtils
.isExpired(tokenGroup
))
349 // String expiryDateStr = (String) tokenGroup.getProperties().get(description.name());
350 // if (expiryDateStr != null) {
351 // Instant expiryDate = NamingUtils.ldapDateToInstant(expiryDateStr);
352 // if (expiryDate.isBefore(Instant.now())) {
353 // if (log.isDebugEnabled())
354 // log.debug("Token " + tokenGroup.getName() + " has expired.");
358 String userDn
= TokenUtils
.userDn(tokenGroup
);
359 User user
= (User
) userAdmin
.getRole(userDn
);
360 Authorization auth
= userAdmin
.getAuthorization(user
);