1 package org
.argeo
.util
.directory
.ldap
;
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
.Iterator
;
14 import java
.util
.List
;
15 import java
.util
.Objects
;
16 import java
.util
.StringJoiner
;
18 import javax
.naming
.NamingEnumeration
;
19 import javax
.naming
.NamingException
;
20 import javax
.naming
.directory
.Attribute
;
21 import javax
.naming
.directory
.Attributes
;
22 import javax
.naming
.directory
.BasicAttribute
;
23 import javax
.naming
.ldap
.LdapName
;
25 import org
.argeo
.util
.directory
.DirectoryDigestUtils
;
26 import org
.argeo
.util
.naming
.LdapAttrs
;
27 import org
.argeo
.util
.naming
.LdapObjs
;
29 /** An entry in an LDAP (or LDIF) directory. */
30 public class DefaultLdapEntry
implements LdapEntry
{
31 private final AbstractLdapDirectory directory
;
33 private final LdapName dn
;
35 // private Attributes publishedAttributes;
37 // Temporarily expose the fields
38 private AttributeDictionary properties
;
39 private AttributeDictionary credentials
;
41 protected DefaultLdapEntry(AbstractLdapDirectory directory
, LdapName dn
) {
42 Objects
.requireNonNull(directory
);
43 Objects
.requireNonNull(dn
);
44 this.directory
= directory
;
46 // this.publishedAttributes = attributes;
47 // properties = new AttributeDictionary(false);
48 // credentials = new AttributeDictionary(true);
52 public LdapName
getDn() {
56 public synchronized Attributes
getAttributes() {
58 // if (publishedAttributes == null)
59 // publishedAttributes = getDirectory().getDirectoryDao().doGetAttributes(dn);
60 return isEditing() ?
getModifiedAttributes() : getDirectory().getDirectoryDao().doGetAttributes(dn
);
64 public List
<LdapName
> getReferences(String attributeId
) {
65 Attribute memberAttribute
= getAttributes().get(attributeId
);
66 if (memberAttribute
== null)
67 return new ArrayList
<LdapName
>();
69 List
<LdapName
> roles
= new ArrayList
<LdapName
>();
70 NamingEnumeration
<?
> values
= memberAttribute
.getAll();
71 while (values
.hasMore()) {
72 LdapName dn
= new LdapName(values
.next().toString());
76 } catch (NamingException e
) {
77 throw new IllegalStateException("Cannot get members", e
);
82 /** Should only be called from working copy thread. */
83 protected synchronized Attributes
getModifiedAttributes() {
84 assert getWc() != null;
85 return getWc().getModifiedData().get(getDn());
88 protected synchronized boolean isEditing() {
89 return getWc() != null && getModifiedAttributes() != null;
92 private synchronized LdapEntryWorkingCopy
getWc() {
93 return directory
.getWorkingCopy();
96 protected synchronized void startEditing() {
98 // throw new IllegalStateException("Cannot edit frozen view");
99 if (directory
.isReadOnly())
100 throw new IllegalStateException("User directory is read-only");
101 assert getModifiedAttributes() == null;
102 getWc().startEditing(this);
103 // modifiedAttributes = (Attributes) publishedAttributes.clone();
106 public synchronized void publishAttributes(Attributes modifiedAttributes
) {
107 // publishedAttributes = modifiedAttributes;
114 public Dictionary
<String
, Object
> getProperties() {
115 if (properties
== null)
116 properties
= new AttributeDictionary(false);
120 public Dictionary
<String
, Object
> getCredentials() {
121 if (credentials
== null)
122 credentials
= new AttributeDictionary(true);
130 public boolean hasCredential(String key
, Object value
) {
132 // TODO check other sources (like PKCS12)
133 // String pwd = new String((char[]) value);
134 // authPassword (RFC 312 https://tools.ietf.org/html/rfc3112)
135 char[] password
= DirectoryDigestUtils
.bytesToChars(value
);
137 if (getDirectory().getForcedPassword() != null
138 && getDirectory().getForcedPassword().equals(new String(password
)))
141 AuthPassword authPassword
= AuthPassword
.matchAuthValue(getAttributes(), password
);
142 if (authPassword
!= null) {
143 if (authPassword
.getAuthScheme().equals(SharedSecret
.X_SHARED_SECRET
)) {
144 SharedSecret onceToken
= new SharedSecret(authPassword
);
145 if (onceToken
.isExpired()) {
146 // AuthPassword.remove(getAttributes(), onceToken);
149 // boolean wasRemoved = AuthPassword.remove(getAttributes(), onceToken);
152 // TODO delete expired tokens?
154 // TODO implement SHA
155 throw new UnsupportedOperationException(
156 "Unsupported authPassword scheme " + authPassword
.getAuthScheme());
161 // byte[] hashedPassword = hash(password, DigestUtils.PASSWORD_SCHEME_PBKDF2_SHA256);
162 if (hasCredential(LdapAttrs
.userPassword
.name(), DirectoryDigestUtils
.charsToBytes(password
)))
167 Object storedValue
= getCredentials().get(key
);
168 if (storedValue
== null || value
== null)
170 if (!(value
instanceof String
|| value
instanceof byte[]))
172 if (storedValue
instanceof String
&& value
instanceof String
)
173 return storedValue
.equals(value
);
174 if (storedValue
instanceof byte[] && value
instanceof byte[]) {
175 String storedBase64
= new String((byte[]) storedValue
, US_ASCII
);
176 String passwordScheme
= null;
177 if (storedBase64
.charAt(0) == '{') {
178 int index
= storedBase64
.indexOf('}');
180 passwordScheme
= storedBase64
.substring(1, index
);
181 String storedValueBase64
= storedBase64
.substring(index
+ 1);
182 byte[] storedValueBytes
= Base64
.getDecoder().decode(storedValueBase64
);
183 char[] passwordValue
= DirectoryDigestUtils
.bytesToChars((byte[]) value
);
185 if (DirectoryDigestUtils
.PASSWORD_SCHEME_SHA
.equals(passwordScheme
)) {
186 valueBytes
= DirectoryDigestUtils
.toPasswordScheme(passwordScheme
, passwordValue
, null, null,
188 } else if (DirectoryDigestUtils
.PASSWORD_SCHEME_PBKDF2_SHA256
.equals(passwordScheme
)) {
189 // see https://www.thesubtlety.com/post/a-389-ds-pbkdf2-password-checker/
190 byte[] iterationsArr
= Arrays
.copyOfRange(storedValueBytes
, 0, 4);
191 BigInteger iterations
= new BigInteger(iterationsArr
);
192 byte[] salt
= Arrays
.copyOfRange(storedValueBytes
, iterationsArr
.length
,
193 iterationsArr
.length
+ 64);
194 byte[] keyArr
= Arrays
.copyOfRange(storedValueBytes
, iterationsArr
.length
+ salt
.length
,
195 storedValueBytes
.length
);
196 int keyLengthBits
= keyArr
.length
* 8;
197 valueBytes
= DirectoryDigestUtils
.toPasswordScheme(passwordScheme
, passwordValue
, salt
,
198 iterations
.intValue(), keyLengthBits
);
200 throw new UnsupportedOperationException("Unknown password scheme " + passwordScheme
);
202 return Arrays
.equals(storedValueBytes
, valueBytes
);
206 // if (storedValue instanceof byte[] && value instanceof byte[]) {
207 // return Arrays.equals((byte[]) storedValue, (byte[]) value);
212 /** Hash the password */
213 private static byte[] sha1hash(char[] password
) {
214 byte[] hashedPassword
= ("{SHA}" + Base64
.getEncoder()
215 .encodeToString(DirectoryDigestUtils
.sha1(DirectoryDigestUtils
.charsToBytes(password
))))
216 .getBytes(StandardCharsets
.UTF_8
);
217 return hashedPassword
;
220 public AbstractLdapDirectory
getDirectory() {
224 public LdapDirectoryDao
getDirectoryDao() {
225 return directory
.getDirectoryDao();
229 public int hashCode() {
230 return dn
.hashCode();
234 public boolean equals(Object obj
) {
237 if (obj
instanceof LdapEntry
) {
238 LdapEntry that
= (LdapEntry
) obj
;
239 return this.dn
.equals(that
.getDn());
245 public String
toString() {
246 return dn
.toString();
249 private static boolean isAsciiPrintable(String str
) {
253 int sz
= str
.length();
254 for (int i
= 0; i
< sz
; i
++) {
255 if (isAsciiPrintable(str
.charAt(i
)) == false) {
262 private static boolean isAsciiPrintable(char ch
) {
263 return ch
>= 32 && ch
< 127;
266 protected class AttributeDictionary
extends Dictionary
<String
, Object
> {
267 private final List
<String
> effectiveKeys
= new ArrayList
<String
>();
268 private final List
<String
> attrFilter
;
269 private final Boolean includeFilter
;
271 public AttributeDictionary(Boolean credentials
) {
272 this.attrFilter
= getDirectory().getCredentialAttributeIds();
273 this.includeFilter
= credentials
;
275 NamingEnumeration
<String
> ids
= getAttributes().getIDs();
276 while (ids
.hasMore()) {
277 String id
= ids
.next();
278 if (credentials
&& attrFilter
.contains(id
))
279 effectiveKeys
.add(id
);
280 else if (!credentials
&& !attrFilter
.contains(id
))
281 effectiveKeys
.add(id
);
283 } catch (NamingException e
) {
284 throw new IllegalStateException("Cannot initialise attribute dictionary", e
);
287 effectiveKeys
.add(LdapAttrs
.objectClasses
.name());
292 return effectiveKeys
.size();
296 public boolean isEmpty() {
297 return effectiveKeys
.size() == 0;
301 public Enumeration
<String
> keys() {
302 return Collections
.enumeration(effectiveKeys
);
306 public Enumeration
<Object
> elements() {
307 final Iterator
<String
> it
= effectiveKeys
.iterator();
308 return new Enumeration
<Object
>() {
311 public boolean hasMoreElements() {
316 public Object
nextElement() {
317 String key
= it
.next();
325 public Object
get(Object key
) {
327 Attribute attr
= !key
.equals(LdapAttrs
.objectClasses
.name()) ?
getAttributes().get(key
.toString())
328 : getAttributes().get(LdapAttrs
.objectClass
.name());
331 Object value
= attr
.get();
332 if (value
instanceof byte[]) {
333 if (key
.equals(LdapAttrs
.userPassword
.name()))
334 // TODO other cases (certificates, images)
336 value
= new String((byte[]) value
, StandardCharsets
.UTF_8
);
338 if (attr
.size() == 1)
340 // special case for object class
341 if (key
.equals(LdapAttrs
.objectClass
.name())) {
342 // TODO support multiple object classes
343 NamingEnumeration
<?
> en
= attr
.getAll();
345 attrs
: while (en
.hasMore()) {
346 String v
= en
.next().toString();
347 if (v
.equalsIgnoreCase(LdapObjs
.top
.name()))
351 if (v
.equalsIgnoreCase(getDirectory().getUserObjectClass()))
352 return getDirectory().getUserObjectClass();
353 else if (v
.equalsIgnoreCase(getDirectory().getGroupObjectClass()))
354 return getDirectory().getGroupObjectClass();
358 throw new IllegalStateException("Cannot find objectClass in " + value
);
360 NamingEnumeration
<?
> en
= attr
.getAll();
361 StringJoiner values
= new StringJoiner("\n");
362 while (en
.hasMore()) {
363 String v
= en
.next().toString();
366 return values
.toString();
370 } catch (NamingException e
) {
371 throw new IllegalStateException("Cannot get value for attribute " + key
, e
);
376 public Object
put(String key
, Object value
) {
377 Objects
.requireNonNull(value
, "Value for key " + key
+ " is null");
380 // FIXME remove this "feature", a key should be specified
381 // TODO persist to other sources (like PKCS12)
382 char[] password
= DirectoryDigestUtils
.bytesToChars(value
);
383 byte[] hashedPassword
= sha1hash(password
);
384 return put(LdapAttrs
.userPassword
.name(), hashedPassword
);
386 if (key
.startsWith("X-")) {
387 return put(LdapAttrs
.authPassword
.name(), value
);
391 getDirectory().checkEdit();
395 // object classes special case.
396 if (key
.equals(LdapAttrs
.objectClasses
.name())) {
397 Attribute attribute
= new BasicAttribute(LdapAttrs
.objectClass
.name());
398 String
[] objectClasses
= value
.toString().split("\n");
399 for (String objectClass
: objectClasses
) {
400 if (objectClass
.trim().equals(""))
402 attribute
.add(objectClass
);
404 Attribute previousAttribute
= getModifiedAttributes().put(attribute
);
405 if (previousAttribute
!= null)
406 return previousAttribute
.get();
411 if (!(value
instanceof String
|| value
instanceof byte[]))
412 throw new IllegalArgumentException("Value must be String or byte[]");
414 if (includeFilter
&& !attrFilter
.contains(key
))
415 throw new IllegalArgumentException("Key " + key
+ " not included");
416 else if (!includeFilter
&& attrFilter
.contains(key
))
417 throw new IllegalArgumentException("Key " + key
+ " excluded");
419 Attribute attribute
= getModifiedAttributes().get(key
.toString());
420 // if (attribute == null) // block unit tests
421 attribute
= new BasicAttribute(key
.toString());
422 if (value
instanceof String
&& !isAsciiPrintable(((String
) value
)))
423 attribute
.add(((String
) value
).getBytes(StandardCharsets
.UTF_8
));
425 attribute
.add(value
);
426 Attribute previousAttribute
= getModifiedAttributes().put(attribute
);
427 if (previousAttribute
!= null)
428 return previousAttribute
.get();
431 } catch (NamingException e
) {
432 throw new IllegalStateException("Cannot get value for attribute " + key
, e
);
437 public Object
remove(Object key
) {
438 getDirectory().checkEdit();
442 if (includeFilter
&& !attrFilter
.contains(key
))
443 throw new IllegalArgumentException("Key " + key
+ " not included");
444 else if (!includeFilter
&& attrFilter
.contains(key
))
445 throw new IllegalArgumentException("Key " + key
+ " excluded");
448 Attribute attr
= getModifiedAttributes().remove(key
.toString());
453 } catch (NamingException e
) {
454 throw new IllegalStateException("Cannot remove attribute " + key
, e
);