1 package org
.argeo
.osgi
.useradmin
;
3 import static java
.nio
.charset
.StandardCharsets
.US_ASCII
;
5 import java
.math
.BigInteger
;
6 import java
.nio
.charset
.StandardCharsets
;
7 import java
.util
.ArrayList
;
8 import java
.util
.Arrays
;
9 import java
.util
.Base64
;
10 import java
.util
.Collections
;
11 import java
.util
.Dictionary
;
12 import java
.util
.Enumeration
;
13 import java
.util
.HashSet
;
14 import java
.util
.Iterator
;
15 import java
.util
.List
;
17 import java
.util
.StringJoiner
;
19 import javax
.naming
.NamingEnumeration
;
20 import javax
.naming
.NamingException
;
21 import javax
.naming
.directory
.Attribute
;
22 import javax
.naming
.directory
.Attributes
;
23 import javax
.naming
.directory
.BasicAttribute
;
24 import javax
.naming
.ldap
.LdapName
;
26 import org
.argeo
.util
.naming
.AuthPassword
;
27 import org
.argeo
.util
.naming
.LdapAttrs
;
28 import org
.argeo
.util
.naming
.LdapObjs
;
29 import org
.argeo
.util
.naming
.SharedSecret
;
31 /** Directory user implementation */
32 class LdifUser
implements DirectoryUser
{
33 private final AbstractUserDirectory userAdmin
;
35 private final LdapName dn
;
37 private final boolean frozen
;
38 private Attributes publishedAttributes
;
40 private final AttributeDictionary properties
;
41 private final AttributeDictionary credentials
;
43 LdifUser(AbstractUserDirectory userAdmin
, LdapName dn
, Attributes attributes
) {
44 this(userAdmin
, dn
, attributes
, false);
47 private LdifUser(AbstractUserDirectory userAdmin
, LdapName dn
, Attributes attributes
, boolean frozen
) {
48 this.userAdmin
= userAdmin
;
50 this.publishedAttributes
= attributes
;
51 properties
= new AttributeDictionary(false);
52 credentials
= new AttributeDictionary(true);
57 public String
getName() {
62 public int getType() {
67 public Dictionary
<String
, Object
> getProperties() {
72 public Dictionary
<String
, Object
> getCredentials() {
77 public boolean hasCredential(String key
, Object value
) {
79 // TODO check other sources (like PKCS12)
80 // String pwd = new String((char[]) value);
81 // authPassword (RFC 312 https://tools.ietf.org/html/rfc3112)
82 char[] password
= DigestUtils
.bytesToChars(value
);
84 if (userAdmin
.getForcedPassword() != null && userAdmin
.getForcedPassword().equals(new String(password
)))
87 AuthPassword authPassword
= AuthPassword
.matchAuthValue(getAttributes(), password
);
88 if (authPassword
!= null) {
89 if (authPassword
.getAuthScheme().equals(SharedSecret
.X_SHARED_SECRET
)) {
90 SharedSecret onceToken
= new SharedSecret(authPassword
);
91 if (onceToken
.isExpired()) {
92 // AuthPassword.remove(getAttributes(), onceToken);
95 // boolean wasRemoved = AuthPassword.remove(getAttributes(), onceToken);
98 // TODO delete expired tokens?
100 // TODO implement SHA
101 throw new UnsupportedOperationException(
102 "Unsupported authPassword scheme " + authPassword
.getAuthScheme());
107 // byte[] hashedPassword = hash(password, DigestUtils.PASSWORD_SCHEME_PBKDF2_SHA256);
108 if (hasCredential(LdapAttrs
.userPassword
.name(), DigestUtils
.charsToBytes(password
)))
113 Object storedValue
= getCredentials().get(key
);
114 if (storedValue
== null || value
== null)
116 if (!(value
instanceof String
|| value
instanceof byte[]))
118 if (storedValue
instanceof String
&& value
instanceof String
)
119 return storedValue
.equals(value
);
120 if (storedValue
instanceof byte[] && value
instanceof byte[]) {
121 String storedBase64
= new String((byte[]) storedValue
, US_ASCII
);
122 String passwordScheme
= null;
123 if (storedBase64
.charAt(0) == '{') {
124 int index
= storedBase64
.indexOf('}');
126 passwordScheme
= storedBase64
.substring(1, index
);
127 String storedValueBase64
= storedBase64
.substring(index
+ 1);
128 byte[] storedValueBytes
= Base64
.getDecoder().decode(storedValueBase64
);
129 char[] passwordValue
= DigestUtils
.bytesToChars((byte[]) value
);
131 if (DigestUtils
.PASSWORD_SCHEME_SHA
.equals(passwordScheme
)) {
132 valueBytes
= DigestUtils
.toPasswordScheme(passwordScheme
, passwordValue
, null, null, null);
133 } else if (DigestUtils
.PASSWORD_SCHEME_PBKDF2_SHA256
.equals(passwordScheme
)) {
134 // see https://www.thesubtlety.com/post/a-389-ds-pbkdf2-password-checker/
135 byte[] iterationsArr
= Arrays
.copyOfRange(storedValueBytes
, 0, 4);
136 BigInteger iterations
= new BigInteger(iterationsArr
);
137 byte[] salt
= Arrays
.copyOfRange(storedValueBytes
, iterationsArr
.length
,
138 iterationsArr
.length
+ 64);
139 byte[] keyArr
= Arrays
.copyOfRange(storedValueBytes
, iterationsArr
.length
+ salt
.length
,
140 storedValueBytes
.length
);
141 int keyLengthBits
= keyArr
.length
* 8;
142 valueBytes
= DigestUtils
.toPasswordScheme(passwordScheme
, passwordValue
, salt
,
143 iterations
.intValue(), keyLengthBits
);
145 throw new UnsupportedOperationException("Unknown password scheme " + passwordScheme
);
147 return Arrays
.equals(storedValueBytes
, valueBytes
);
151 // if (storedValue instanceof byte[] && value instanceof byte[]) {
152 // return Arrays.equals((byte[]) storedValue, (byte[]) value);
157 /** Hash the password */
158 byte[] sha1hash(char[] password
) {
159 byte[] hashedPassword
= ("{SHA}"
160 + Base64
.getEncoder().encodeToString(DigestUtils
.sha1(DigestUtils
.charsToBytes(password
))))
161 .getBytes(StandardCharsets
.UTF_8
);
162 return hashedPassword
;
165 // byte[] hash(char[] password, String passwordScheme) {
166 // if (passwordScheme == null)
167 // passwordScheme = DigestUtils.PASSWORD_SCHEME_SHA;
168 // byte[] hashedPassword = ("{" + passwordScheme + "}"
169 // + Base64.getEncoder().encodeToString(DigestUtils.toPasswordScheme(passwordScheme, password)))
170 // .getBytes(US_ASCII);
171 // return hashedPassword;
175 public LdapName
getDn() {
180 public synchronized Attributes
getAttributes() {
181 return isEditing() ?
getModifiedAttributes() : publishedAttributes
;
184 /** Should only be called from working copy thread. */
185 private synchronized Attributes
getModifiedAttributes() {
186 assert getWc() != null;
187 return getWc().getAttributes(getDn());
190 protected synchronized boolean isEditing() {
191 return getWc() != null && getModifiedAttributes() != null;
194 private synchronized UserDirectoryWorkingCopy
getWc() {
195 return userAdmin
.getWorkingCopy();
198 protected synchronized void startEditing() {
200 throw new UserDirectoryException("Cannot edit frozen view");
201 if (getUserAdmin().isReadOnly())
202 throw new UserDirectoryException("User directory is read-only");
203 assert getModifiedAttributes() == null;
204 getWc().startEditing(this);
205 // modifiedAttributes = (Attributes) publishedAttributes.clone();
208 public synchronized void publishAttributes(Attributes modifiedAttributes
) {
209 publishedAttributes
= modifiedAttributes
;
212 public DirectoryUser
getPublished() {
213 return new LdifUser(userAdmin
, dn
, publishedAttributes
, true);
217 public int hashCode() {
218 return dn
.hashCode();
222 public boolean equals(Object obj
) {
225 if (obj
instanceof LdifUser
) {
226 LdifUser that
= (LdifUser
) obj
;
227 return this.dn
.equals(that
.dn
);
233 public String
toString() {
234 return dn
.toString();
237 protected AbstractUserDirectory
getUserAdmin() {
241 private class AttributeDictionary
extends Dictionary
<String
, Object
> {
242 private final List
<String
> effectiveKeys
= new ArrayList
<String
>();
243 private final List
<String
> attrFilter
;
244 private final Boolean includeFilter
;
246 public AttributeDictionary(Boolean includeFilter
) {
247 this.attrFilter
= userAdmin
.getCredentialAttributeIds();
248 this.includeFilter
= includeFilter
;
250 NamingEnumeration
<String
> ids
= getAttributes().getIDs();
251 while (ids
.hasMore()) {
252 String id
= ids
.next();
253 if (includeFilter
&& attrFilter
.contains(id
))
254 effectiveKeys
.add(id
);
255 else if (!includeFilter
&& !attrFilter
.contains(id
))
256 effectiveKeys
.add(id
);
258 } catch (NamingException e
) {
259 throw new UserDirectoryException("Cannot initialise attribute dictionary", e
);
265 return effectiveKeys
.size();
269 public boolean isEmpty() {
270 return effectiveKeys
.size() == 0;
274 public Enumeration
<String
> keys() {
275 return Collections
.enumeration(effectiveKeys
);
279 public Enumeration
<Object
> elements() {
280 final Iterator
<String
> it
= effectiveKeys
.iterator();
281 return new Enumeration
<Object
>() {
284 public boolean hasMoreElements() {
289 public Object
nextElement() {
290 String key
= it
.next();
298 public Object
get(Object key
) {
300 Attribute attr
= getAttributes().get(key
.toString());
303 Object value
= attr
.get();
304 if (value
instanceof byte[]) {
305 if (key
.equals(LdapAttrs
.userPassword
.name()))
306 // TODO other cases (certificates, images)
308 value
= new String((byte[]) value
, StandardCharsets
.UTF_8
);
310 if (attr
.size() == 1)
312 // special case for object class
313 if (attr
.getID().equals(LdapAttrs
.objectClass
.name())) {
314 // TODO support multiple object classes
315 NamingEnumeration
<?
> en
= attr
.getAll();
317 attrs
: while (en
.hasMore()) {
318 String v
= en
.next().toString();
319 if (v
.equalsIgnoreCase(LdapObjs
.top
.name()))
323 if (v
.equalsIgnoreCase(userAdmin
.getUserObjectClass()))
324 return userAdmin
.getUserObjectClass();
325 else if (v
.equalsIgnoreCase(userAdmin
.getGroupObjectClass()))
326 return userAdmin
.getGroupObjectClass();
330 throw new IllegalStateException("Cannot find objectClass in " + value
);
332 NamingEnumeration
<?
> en
= attr
.getAll();
333 StringJoiner values
= new StringJoiner("\n");
334 while (en
.hasMore()) {
335 String v
= en
.next().toString();
338 return values
.toString();
342 } catch (NamingException e
) {
343 throw new IllegalStateException("Cannot get value for attribute " + key
, e
);
348 public Object
put(String key
, Object value
) {
350 // TODO persist to other sources (like PKCS12)
351 char[] password
= DigestUtils
.bytesToChars(value
);
352 byte[] hashedPassword
= sha1hash(password
);
353 return put(LdapAttrs
.userPassword
.name(), hashedPassword
);
355 if (key
.startsWith("X-")) {
356 return put(LdapAttrs
.authPassword
.name(), value
);
359 userAdmin
.checkEdit();
363 if (!(value
instanceof String
|| value
instanceof byte[]))
364 throw new IllegalArgumentException("Value must be String or byte[]");
366 if (includeFilter
&& !attrFilter
.contains(key
))
367 throw new IllegalArgumentException("Key " + key
+ " not included");
368 else if (!includeFilter
&& attrFilter
.contains(key
))
369 throw new IllegalArgumentException("Key " + key
+ " excluded");
372 Attribute attribute
= getModifiedAttributes().get(key
.toString());
373 // if (attribute == null) // block unit tests
374 attribute
= new BasicAttribute(key
.toString());
375 if (value
instanceof String
&& !isAsciiPrintable(((String
) value
)))
376 attribute
.add(((String
) value
).getBytes(StandardCharsets
.UTF_8
));
378 attribute
.add(value
);
379 Attribute previousAttribute
= getModifiedAttributes().put(attribute
);
380 if (previousAttribute
!= null)
381 return previousAttribute
.get();
384 } catch (NamingException e
) {
385 throw new UserDirectoryException("Cannot get value for attribute " + key
, e
);
390 public Object
remove(Object key
) {
391 userAdmin
.checkEdit();
395 if (includeFilter
&& !attrFilter
.contains(key
))
396 throw new IllegalArgumentException("Key " + key
+ " not included");
397 else if (!includeFilter
&& attrFilter
.contains(key
))
398 throw new IllegalArgumentException("Key " + key
+ " excluded");
401 Attribute attr
= getModifiedAttributes().remove(key
.toString());
406 } catch (NamingException e
) {
407 throw new UserDirectoryException("Cannot remove attribute " + key
, e
);
412 private static boolean isAsciiPrintable(String str
) {
416 int sz
= str
.length();
417 for (int i
= 0; i
< sz
; i
++) {
418 if (isAsciiPrintable(str
.charAt(i
)) == false) {
425 private static boolean isAsciiPrintable(char ch
) {
426 return ch
>= 32 && ch
< 127;