1 package org
.argeo
.osgi
.useradmin
;
3 import java
.io
.UnsupportedEncodingException
;
4 import java
.nio
.ByteBuffer
;
5 import java
.nio
.CharBuffer
;
6 import java
.nio
.charset
.Charset
;
7 import java
.util
.ArrayList
;
8 import java
.util
.Arrays
;
9 import java
.util
.Collections
;
10 import java
.util
.Dictionary
;
11 import java
.util
.Enumeration
;
12 import java
.util
.HashSet
;
13 import java
.util
.Iterator
;
14 import java
.util
.List
;
17 import javax
.naming
.NamingEnumeration
;
18 import javax
.naming
.NamingException
;
19 import javax
.naming
.directory
.Attribute
;
20 import javax
.naming
.directory
.Attributes
;
21 import javax
.naming
.directory
.BasicAttribute
;
22 import javax
.naming
.ldap
.LdapName
;
24 import org
.apache
.commons
.codec
.binary
.Base64
;
25 import org
.apache
.commons
.codec
.digest
.DigestUtils
;
27 /** Directory user implementation */
28 class LdifUser
implements DirectoryUser
{
29 private final AbstractUserDirectory userAdmin
;
31 private final LdapName dn
;
33 private final boolean frozen
;
34 private Attributes publishedAttributes
;
36 private final AttributeDictionary properties
;
37 private final AttributeDictionary credentials
;
39 LdifUser(AbstractUserDirectory userAdmin
, LdapName dn
, Attributes attributes
) {
40 this(userAdmin
, dn
, attributes
, false);
43 private LdifUser(AbstractUserDirectory userAdmin
, LdapName dn
,
44 Attributes attributes
, boolean frozen
) {
45 this.userAdmin
= userAdmin
;
47 this.publishedAttributes
= attributes
;
48 properties
= new AttributeDictionary(false);
49 credentials
= new AttributeDictionary(true);
54 public String
getName() {
59 public int getType() {
64 public Dictionary
<String
, Object
> getProperties() {
69 public Dictionary
<String
, Object
> getCredentials() {
74 public boolean hasCredential(String key
, Object value
) {
76 // TODO check other sources (like PKCS12)
77 char[] password
= toChars(value
);
78 byte[] hashedPassword
= hash(password
);
79 return hasCredential(LdifName
.userPassword
.name(), hashedPassword
);
82 Object storedValue
= getCredentials().get(key
);
83 if (storedValue
== null || value
== null)
85 if (!(value
instanceof String
|| value
instanceof byte[]))
87 if (storedValue
instanceof String
&& value
instanceof String
)
88 return storedValue
.equals(value
);
89 if (storedValue
instanceof byte[] && value
instanceof byte[])
90 return Arrays
.equals((byte[]) storedValue
, (byte[]) value
);
94 /** Hash and clear the password */
95 private byte[] hash(char[] password
) {
96 byte[] hashedPassword
= ("{SHA}" + Base64
97 .encodeBase64String(DigestUtils
.sha1(toBytes(password
))))
99 Arrays
.fill(password
, '\u0000');
100 return hashedPassword
;
103 private byte[] toBytes(char[] chars
) {
104 CharBuffer charBuffer
= CharBuffer
.wrap(chars
);
105 ByteBuffer byteBuffer
= Charset
.forName("UTF-8").encode(charBuffer
);
106 byte[] bytes
= Arrays
.copyOfRange(byteBuffer
.array(),
107 byteBuffer
.position(), byteBuffer
.limit());
108 Arrays
.fill(charBuffer
.array(), '\u0000'); // clear sensitive data
109 Arrays
.fill(byteBuffer
.array(), (byte) 0); // clear sensitive data
113 private char[] toChars(Object obj
) {
114 if (obj
instanceof char[])
116 if (!(obj
instanceof byte[]))
117 throw new IllegalArgumentException(obj
.getClass()
118 + " is not a byte array");
119 ByteBuffer fromBuffer
= ByteBuffer
.wrap((byte[]) obj
);
120 CharBuffer toBuffer
= Charset
.forName("UTF-8").decode(fromBuffer
);
121 char[] res
= Arrays
.copyOfRange(toBuffer
.array(), toBuffer
.position(),
123 Arrays
.fill(fromBuffer
.array(), (byte) 0); // clear sensitive data
124 Arrays
.fill((byte[]) obj
, (byte) 0); // clear sensitive data
125 Arrays
.fill(toBuffer
.array(), '\u0000'); // clear sensitive data
130 public LdapName
getDn() {
135 public synchronized Attributes
getAttributes() {
136 return isEditing() ?
getModifiedAttributes() : publishedAttributes
;
139 /** Should only be called from working copy thread. */
140 private synchronized Attributes
getModifiedAttributes() {
141 assert getWc() != null;
142 return getWc().getAttributes(getDn());
145 protected synchronized boolean isEditing() {
146 return getWc() != null && getModifiedAttributes() != null;
149 private synchronized UserDirectoryWorkingCopy
getWc() {
150 return userAdmin
.getWorkingCopy();
153 protected synchronized void startEditing() {
155 throw new UserDirectoryException("Cannot edit frozen view");
156 if (getUserAdmin().isReadOnly())
157 throw new UserDirectoryException("User directory is read-only");
158 assert getModifiedAttributes() == null;
159 getWc().startEditing(this);
160 // modifiedAttributes = (Attributes) publishedAttributes.clone();
163 public synchronized void publishAttributes(Attributes modifiedAttributes
) {
164 publishedAttributes
= modifiedAttributes
;
167 public DirectoryUser
getPublished() {
168 return new LdifUser(userAdmin
, dn
, publishedAttributes
, true);
172 public int hashCode() {
173 return dn
.hashCode();
177 public boolean equals(Object obj
) {
180 if (obj
instanceof LdifUser
) {
181 LdifUser that
= (LdifUser
) obj
;
182 return this.dn
.equals(that
.dn
);
188 public String
toString() {
189 return dn
.toString();
192 protected AbstractUserDirectory
getUserAdmin() {
196 private class AttributeDictionary
extends Dictionary
<String
, Object
> {
197 private final List
<String
> effectiveKeys
= new ArrayList
<String
>();
198 private final List
<String
> attrFilter
;
199 private final Boolean includeFilter
;
201 public AttributeDictionary(Boolean includeFilter
) {
202 this.attrFilter
= userAdmin
.getCredentialAttributeIds();
203 this.includeFilter
= includeFilter
;
205 NamingEnumeration
<String
> ids
= getAttributes().getIDs();
206 while (ids
.hasMore()) {
207 String id
= ids
.next();
208 if (includeFilter
&& attrFilter
.contains(id
))
209 effectiveKeys
.add(id
);
210 else if (!includeFilter
&& !attrFilter
.contains(id
))
211 effectiveKeys
.add(id
);
213 } catch (NamingException e
) {
214 throw new UserDirectoryException(
215 "Cannot initialise attribute dictionary", e
);
221 return effectiveKeys
.size();
225 public boolean isEmpty() {
226 return effectiveKeys
.size() == 0;
230 public Enumeration
<String
> keys() {
231 return Collections
.enumeration(effectiveKeys
);
235 public Enumeration
<Object
> elements() {
236 final Iterator
<String
> it
= effectiveKeys
.iterator();
237 return new Enumeration
<Object
>() {
240 public boolean hasMoreElements() {
245 public Object
nextElement() {
246 String key
= it
.next();
254 public Object
get(Object key
) {
256 Attribute attr
= getAttributes().get(key
.toString());
259 Object value
= attr
.get();
260 if (value
instanceof byte[]) {
261 if (key
.equals(LdifName
.userPassword
.name()))
262 // TODO other cases (certificates, images)
264 value
= new String((byte[]) value
, Charset
.forName("UTF-8"));
266 if (attr
.size() == 1)
268 if (!attr
.getID().equals(LdifName
.objectClass
.name()))
270 // special case for object class
271 NamingEnumeration
<?
> en
= attr
.getAll();
272 Set
<String
> objectClasses
= new HashSet
<String
>();
273 while (en
.hasMore()) {
274 String objectClass
= en
.next().toString();
275 objectClasses
.add(objectClass
);
278 if (objectClasses
.contains(userAdmin
.getUserObjectClass()))
279 return userAdmin
.getUserObjectClass();
280 else if (objectClasses
281 .contains(userAdmin
.getGroupObjectClass()))
282 return userAdmin
.getGroupObjectClass();
285 } catch (NamingException e
) {
286 throw new UserDirectoryException(
287 "Cannot get value for attribute " + key
, e
);
292 public Object
put(String key
, Object value
) {
294 // TODO persist to other sources (like PKCS12)
295 char[] password
= toChars(value
);
296 byte[] hashedPassword
= hash(password
);
297 return put(LdifName
.userPassword
.name(), hashedPassword
);
300 userAdmin
.checkEdit();
304 if (!(value
instanceof String
|| value
instanceof byte[]))
305 throw new IllegalArgumentException(
306 "Value must be String or byte[]");
308 if (includeFilter
&& !attrFilter
.contains(key
))
309 throw new IllegalArgumentException("Key " + key
311 else if (!includeFilter
&& attrFilter
.contains(key
))
312 throw new IllegalArgumentException("Key " + key
+ " excluded");
315 Attribute attribute
= getModifiedAttributes().get(
317 attribute
= new BasicAttribute(key
.toString());
318 if (value
instanceof String
319 && !isAsciiPrintable(((String
) value
)))
321 attribute
.add(((String
) value
).getBytes("UTF-8"));
322 } catch (UnsupportedEncodingException e
) {
323 throw new UserDirectoryException("Cannot encode "
327 attribute
.add(value
);
328 Attribute previousAttribute
= getModifiedAttributes().put(
330 if (previousAttribute
!= null)
331 return previousAttribute
.get();
334 } catch (NamingException e
) {
335 throw new UserDirectoryException(
336 "Cannot get value for attribute " + key
, e
);
341 public Object
remove(Object key
) {
342 userAdmin
.checkEdit();
346 if (includeFilter
&& !attrFilter
.contains(key
))
347 throw new IllegalArgumentException("Key " + key
349 else if (!includeFilter
&& attrFilter
.contains(key
))
350 throw new IllegalArgumentException("Key " + key
+ " excluded");
353 Attribute attr
= getModifiedAttributes().remove(key
.toString());
358 } catch (NamingException e
) {
359 throw new UserDirectoryException("Cannot remove attribute "
365 private static boolean isAsciiPrintable(String str
) {
369 int sz
= str
.length();
370 for (int i
= 0; i
< sz
; i
++) {
371 if (isAsciiPrintable(str
.charAt(i
)) == false) {
378 private static boolean isAsciiPrintable(char ch
) {
379 return ch
>= 32 && ch
< 127;