1 package org
.argeo
.osgi
.useradmin
;
3 import java
.io
.IOException
;
4 import java
.io
.UnsupportedEncodingException
;
5 import java
.net
.InetAddress
;
7 import java
.net
.URISyntaxException
;
8 import java
.net
.URLDecoder
;
9 import java
.util
.Dictionary
;
10 import java
.util
.Enumeration
;
11 import java
.util
.Hashtable
;
12 import java
.util
.LinkedHashMap
;
13 import java
.util
.LinkedList
;
14 import java
.util
.List
;
17 import javax
.naming
.Context
;
18 import javax
.naming
.NamingException
;
20 import org
.apache
.commons
.logging
.Log
;
21 import org
.apache
.commons
.logging
.LogFactory
;
22 import org
.argeo
.naming
.DnsBrowser
;
23 import org
.osgi
.framework
.Constants
;
25 /** Properties used to configure user admins. */
26 public enum UserAdminConf
{
27 /** Base DN (cannot be configured externally) */
28 baseDn("dc=example,dc=com"),
30 /** URI of the underlying resource (cannot be configured externally) */
31 uri("ldap://localhost:10389"),
33 /** User objectClass */
34 userObjectClass("inetOrgPerson"),
36 /** Relative base DN for users */
37 userBase("ou=People"),
39 /** Groups objectClass */
40 groupObjectClass("groupOfNames"),
42 /** Relative base DN for users */
43 groupBase("ou=Groups"),
45 /** Read-only source */
48 /** Authentication realm */
51 public final static String FACTORY_PID
= "org.argeo.osgi.useradmin.config";
52 private final static Log log
= LogFactory
.getLog(UserAdminConf
.class);
54 /** The default value. */
57 UserAdminConf(Object def
) {
61 public Object
getDefault() {
66 * For use as Java property.
68 * @deprecated use {@link #name()} instead
71 public String
property() {
75 public String
getValue(Dictionary
<String
, ?
> properties
) {
76 Object res
= getRawValue(properties
);
79 return res
.toString();
82 @SuppressWarnings("unchecked")
83 public <T
> T
getRawValue(Dictionary
<String
, ?
> properties
) {
84 Object res
= properties
.get(name());
90 /** @deprecated use {@link #valueOf(String)} instead */
92 public static UserAdminConf
local(String property
) {
93 return UserAdminConf
.valueOf(property
);
96 /** Hides host and credentials. */
97 public static URI
propertiesAsUri(Dictionary
<String
, ?
> properties
) {
98 StringBuilder query
= new StringBuilder();
100 boolean first
= true;
101 for (Enumeration
<String
> keys
= properties
.keys(); keys
.hasMoreElements();) {
102 String key
= keys
.nextElement();
103 // TODO clarify which keys are relevant (list only the enum?)
104 if (!key
.equals("service.factoryPid") && !key
.equals("cn") && !key
.equals("dn")
105 && !key
.equals(Constants
.SERVICE_PID
) && !key
.startsWith("java") && !key
.equals(baseDn
.name())
106 && !key
.equals(uri
.name())) {
111 query
.append(valueOf(key
).name());
112 query
.append('=').append(properties
.get(key
).toString());
116 String bDn
= (String
) properties
.get(baseDn
.name());
118 return new URI(null, null, bDn
!= null ?
'/' + bDn
: null, query
.length() != 0 ? query
.toString() : null,
120 } catch (URISyntaxException e
) {
121 throw new UserDirectoryException("Cannot create URI from properties", e
);
125 public static Dictionary
<String
, Object
> uriAsProperties(String uriStr
) {
127 Hashtable
<String
, Object
> res
= new Hashtable
<String
, Object
>();
128 URI u
= new URI(uriStr
);
129 String scheme
= u
.getScheme();
130 if (scheme
!= null && scheme
.equals("ipa")) {
131 u
= convertIpaConfig(u
);
132 scheme
= u
.getScheme();
134 String path
= u
.getPath();
135 String bDn
= path
.substring(path
.lastIndexOf('/') + 1, path
.length());
136 if (bDn
.endsWith(".ldif"))
137 bDn
= bDn
.substring(0, bDn
.length() - ".ldif".length());
139 String principal
= null;
140 String credentials
= null;
142 if (scheme
.equals("ldap") || scheme
.equals("ldaps")) {
143 // TODO additional checks
144 if (u
.getUserInfo() != null) {
145 String
[] userInfo
= u
.getUserInfo().split(":");
146 principal
= userInfo
.length
> 0 ? userInfo
[0] : null;
147 credentials
= userInfo
.length
> 1 ? userInfo
[1] : null;
149 } else if (scheme
.equals("file")) {
150 } else if (scheme
.equals("ipa")) {
152 throw new UserDirectoryException("Unsupported scheme " + scheme
);
153 Map
<String
, List
<String
>> query
= splitQuery(u
.getQuery());
154 for (String key
: query
.keySet()) {
155 UserAdminConf ldapProp
= UserAdminConf
.valueOf(key
);
156 List
<String
> values
= query
.get(key
);
157 if (values
.size() == 1) {
158 res
.put(ldapProp
.name(), values
.get(0));
160 throw new UserDirectoryException("Only single values are supported");
163 res
.put(baseDn
.name(), bDn
);
164 if (principal
!= null)
165 res
.put(Context
.SECURITY_PRINCIPAL
, principal
);
166 if (credentials
!= null)
167 res
.put(Context
.SECURITY_CREDENTIALS
, credentials
);
168 if (scheme
!= null) {
169 URI bareUri
= new URI(scheme
, null, u
.getHost(), u
.getPort(),
170 scheme
.equals("file") ? u
.getPath() : null, null, null);
171 res
.put(uri
.name(), bareUri
.toString());
174 } catch (Exception e
) {
175 throw new UserDirectoryException("Cannot convert " + uri
+ " to properties", e
);
179 private static URI
convertIpaConfig(URI uri
) {
180 String path
= uri
.getPath();
181 String kerberosRealm
;
182 if (path
== null || path
.length() <= 1) {
183 kerberosRealm
= kerberosDomainFromDns();
185 kerberosRealm
= path
.substring(1);
188 if (kerberosRealm
== null)
189 throw new UserDirectoryException("No Kerberos domain available for " + uri
);
190 try (DnsBrowser dnsBrowser
= new DnsBrowser()) {
191 String ldapHostsStr
= uri
.getHost();
192 if (ldapHostsStr
== null || ldapHostsStr
.trim().equals("")) {
193 List
<String
> ldapHosts
= dnsBrowser
.getSrvRecordsAsHosts("_ldap._tcp." + kerberosRealm
.toLowerCase());
194 if (ldapHosts
== null || ldapHosts
.size() == 0) {
195 throw new UserDirectoryException("Cannot configure LDAP for IPA " + uri
);
197 ldapHostsStr
= ldapHosts
.get(0);
200 URI convertedUri
= new URI(
201 "ldap://" + ldapHostsStr
+ "/" + IpaUtils
.domainToUserDirectoryConfigPath(kerberosRealm
));
202 if (log
.isDebugEnabled())
203 log
.debug("Converted " + uri
+ " to " + convertedUri
);
205 } catch (NamingException
| IOException
| URISyntaxException e
) {
206 throw new UserDirectoryException("cannot convert IPA uri " + uri
, e
);
210 private static String
kerberosDomainFromDns() {
211 String kerberosDomain
;
212 try (DnsBrowser dnsBrowser
= new DnsBrowser()) {
213 InetAddress localhost
= InetAddress
.getLocalHost();
214 String hostname
= localhost
.getHostName();
215 String dnsZone
= hostname
.substring(hostname
.indexOf('.') + 1);
216 kerberosDomain
= dnsBrowser
.getRecord("_kerberos." + dnsZone
, "TXT");
217 return kerberosDomain
;
218 } catch (Exception e
) {
219 throw new UserDirectoryException("Cannot determine Kerberos domain from DNS", e
);
224 private static Map
<String
, List
<String
>> splitQuery(String query
) throws UnsupportedEncodingException
{
225 final Map
<String
, List
<String
>> query_pairs
= new LinkedHashMap
<String
, List
<String
>>();
228 final String
[] pairs
= query
.split("&");
229 for (String pair
: pairs
) {
230 final int idx
= pair
.indexOf("=");
231 final String key
= idx
> 0 ? URLDecoder
.decode(pair
.substring(0, idx
), "UTF-8") : pair
;
232 if (!query_pairs
.containsKey(key
)) {
233 query_pairs
.put(key
, new LinkedList
<String
>());
235 final String value
= idx
> 0 && pair
.length() > idx
+ 1
236 ? URLDecoder
.decode(pair
.substring(idx
+ 1), "UTF-8") : null;
237 query_pairs
.get(key
).add(value
);
242 public static void main(String
[] args
) {
243 Dictionary
<String
, ?
> props
= uriAsProperties("ldap://" + "uid=admin,ou=system:secret@localhost:10389"
244 + "/dc=example,dc=com" + "?readOnly=false&userObjectClass=person");
245 System
.out
.println(props
);
246 System
.out
.println(propertiesAsUri(props
));
248 System
.out
.println(uriAsProperties("file://some/dir/dc=example,dc=com.ldif"));
250 props
= uriAsProperties(
251 "/dc=example,dc=com.ldif?readOnly=true" + "&userBase=ou=CoWorkers,ou=People&groupBase=ou=Roles");
252 System
.out
.println(props
);
253 System
.out
.println(propertiesAsUri(props
));