mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Jean-Noël Rouvignac
01.26.2016 a12eb578b2b06f6ba9d929f4a2c7b81e13eae7cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/*
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions Copyright [year] [name of copyright owner]".
 *
 * Copyright 2016 ForgeRock AS.
 */
package org.opends.admin.ads.util;
 
import static org.forgerock.opendj.config.client.ldap.LDAPManagementContext.*;
import static org.forgerock.opendj.ldap.LDAPConnectionFactory.*;
import static org.forgerock.opendj.ldap.requests.Requests.*;
import static org.forgerock.util.time.Duration.*;
import static org.opends.admin.ads.util.ConnectionUtils.*;
import static org.opends.admin.ads.util.PreferredConnection.Type.*;
import static org.opends.messages.AdminToolMessages.*;
 
import java.io.Closeable;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
import java.util.concurrent.TimeUnit;
 
import javax.naming.NamingException;
import javax.naming.NoPermissionException;
import javax.naming.ldap.InitialLdapContext;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
 
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.config.LDAPProfile;
import org.forgerock.opendj.ldap.Connection;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.LDAPConnectionFactory;
import org.forgerock.opendj.ldap.LdapException;
import org.forgerock.opendj.ldap.SSLContextBuilder;
import org.forgerock.opendj.ldap.requests.SimpleBindRequest;
import org.forgerock.opendj.server.config.client.RootCfgClient;
import org.forgerock.util.Options;
import org.opends.admin.ads.util.PreferredConnection.Type;
import org.opends.server.types.HostPort;
import org.opends.server.util.StaticUtils;
 
/**
 * Wraps a connection to a directory, either relying on JNDI or relying on OpenDJ Connection.
 * <p>
 * You can either:
 * <ul>
 *  <li>call {@code getLdapContext()} method to obtain an {@code InitialLdapContext} for JNDI.</li>
 *  <li>or call the {@code getConnection()} method to obtain a {@code Connection} object.</li>
 * </ul>
 */
public class ConnectionWrapper implements Closeable
{
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
  private final LDAPConnectionFactory connectionFactory;
  private final Connection connection;
  private final InitialLdapContext ldapContext;
  private final HostPort hostPort;
  private DN bindDn;
  private String bindPwd;
  private final int connectTimeout;
  private final TrustManager trustManager;
  private final KeyManager keyManager;
  private Type connectionType;
 
  /**
   * Creates a connection wrapper.
   *
   * @param ldapUrl
   *          the ldap URL containing the host name and port number to connect to
   * @param connectionType
   *          the type of connection (LDAP, LDAPS, START_TLS)
   * @param bindDn
   *          the bind DN
   * @param bindPwd
   *          the bind password
   * @param connectTimeout
   *          connect timeout to use for the connection
   * @param trustManager
   *          trust manager to use for a secure connection
   * @throws NamingException
   *           If an error occurs
   */
  public ConnectionWrapper(String ldapUrl, Type connectionType, String bindDn, String bindPwd, int connectTimeout,
      TrustManager trustManager) throws NamingException
  {
    this(toHostPort(ldapUrl), connectionType, bindDn, bindPwd, connectTimeout, trustManager, null);
  }
 
  /**
   * Converts an ldapUrl to a HostPort.
   *
   * @param ldapUrl
   *          the ldapUrl to convert
   * @return the host and port extracted from the ldapUrl
   * @throws NamingException
   *           if the ldapUrl is not a valid URL
   */
  public static HostPort toHostPort(String ldapUrl) throws NamingException
  {
    try
    {
      URI uri = new URI(ldapUrl);
      return new HostPort(uri.getHost(), uri.getPort());
    }
    catch (URISyntaxException e)
    {
      throw new NamingException(e.getLocalizedMessage() + ". LDAP URL was: \"" + ldapUrl + "\"");
    }
  }
 
  /**
   * Creates a connection wrapper.
   *
   * @param hostPort
   *          the host name and port number to connect to
   * @param connectionType
   *          the type of connection (LDAP, LDAPS, START_TLS)
   * @param bindDn
   *          the bind DN
   * @param bindPwd
   *          the bind password
   * @param connectTimeout
   *          connect timeout to use for the connection
   * @param trustManager
   *          trust manager to use for a secure connection
   * @throws NamingException
   *           If an error occurs
   */
  public ConnectionWrapper(HostPort hostPort, Type connectionType, String bindDn, String bindPwd, int connectTimeout,
      TrustManager trustManager) throws NamingException
  {
    this(hostPort, connectionType, bindDn, bindPwd, connectTimeout, trustManager, null);
  }
 
  /**
   * Creates a connection wrapper by copying the provided one.
   *
   * @param other
   *          the {@link ConnectionWrapper} to copy
   * @throws NamingException
   *           If an error occurs
   */
  public ConnectionWrapper(ConnectionWrapper other) throws NamingException
  {
    this(other.hostPort, other.connectionType, other.bindDn.toString(), other.bindPwd, other.connectTimeout,
        other.trustManager, other.keyManager);
  }
 
  /**
   * Creates a connection wrapper.
   *
   * @param hostPort
   *          the host name and port number to connect to
   * @param connectionType
   *          the type of connection (LDAP, LDAPS, START_TLS)
   * @param bindDn
   *          the bind DN
   * @param bindPwd
   *          the bind password
   * @param connectTimeout
   *          connect timeout to use for the connection
   * @param trustManager
   *          trust manager to use for a secure connection
   * @param keyManager
   *          key manager to use for a secure connection
   * @throws NamingException
   *           If an error occurs
   */
  public ConnectionWrapper(HostPort hostPort, PreferredConnection.Type connectionType, String bindDn, String bindPwd,
      int connectTimeout, TrustManager trustManager, KeyManager keyManager) throws NamingException
  {
    this.hostPort = hostPort;
    this.connectionType = connectionType;
    this.bindDn = DN.valueOf(bindDn);
    this.bindPwd = bindPwd;
    this.connectTimeout = connectTimeout;
    this.trustManager = trustManager;
    this.keyManager = keyManager;
 
    final Options options = toOptions(connectionType, bindDn, bindPwd, connectTimeout, trustManager, keyManager);
    ldapContext = createAdministrativeContext(options);
    connectionFactory = new LDAPConnectionFactory(hostPort.getHost(), hostPort.getPort(), options);
    connection = buildConnection();
  }
 
  private static Options toOptions(Type connectionType, String bindDn, String bindPwd, long connectTimeout,
      TrustManager trustManager, KeyManager keyManager) throws NamingException
  {
    final boolean isStartTls = START_TLS.equals(connectionType);
    final boolean isLdaps = LDAPS.equals(connectionType);
 
    Options options = Options.defaultOptions()
        .set(CONNECT_TIMEOUT, duration(connectTimeout, TimeUnit.MILLISECONDS));
    if (isLdaps || isStartTls)
    {
      options.set(SSL_CONTEXT, getSSLContext(trustManager, keyManager))
             .set(SSL_USE_STARTTLS, isStartTls);
    }
    SimpleBindRequest request = bindDn != null && bindPwd != null
        ? newSimpleBindRequest(bindDn, bindPwd.toCharArray())
        : newSimpleBindRequest(); // anonymous bind
    options.set(AUTHN_BIND_REQUEST, request);
    return options;
  }
 
  private static SSLContext getSSLContext(TrustManager trustManager, KeyManager keyManager) throws NamingException
  {
    try
    {
      return new SSLContextBuilder()
          .setTrustManager(trustManager != null ? trustManager : new BlindTrustManager())
          .setKeyManager(keyManager).getSSLContext();
    }
    catch (GeneralSecurityException e)
    {
      throw new NamingException("Unable to perform SSL initialization:" + e.getMessage());
    }
  }
 
  /**
   * Returns the bind DN used by this connection.
   *
   * @return the bind DN used by this connection.
   */
  public DN getBindDn()
  {
    return bindDn;
  }
 
  /**
   * Returns the bind password used by this connection.
   *
   * @return the bind password used by this connection.
   */
  public String getBindPassword()
  {
    return bindPwd;
  }
 
  /**
   * Returns the LDAP URL used by this connection.
   *
   * @return the LDAP URL used by this connection.
   */
  public String getLdapUrl()
  {
    return ConnectionUtils.getLdapUrl(ldapContext);
  }
 
  /**
   * Returns whether this connection uses SSL.
   *
   * @return {@code true} if this connection uses SSL {@code false} otherwise.
   */
  public boolean isSSL()
  {
    // FIXME the code down below is what the code was doing in the control-panel / dsreplication
    // We might as well just return this.connectionType == LDAPS;
    try
    {
      return ConnectionUtils.getLdapUrl(ldapContext).toLowerCase().startsWith("ldaps");
    }
    catch (Throwable t)
    {
      // This is really strange. Seems like a bug somewhere.
      logger.warn(LocalizableMessage.raw("Error getting if is SSL " + t, t));
      return false;
    }
  }
 
  /**
   * Returns whether this connection uses StartTLS.
   *
   * @return {@code true} if this connection uses StartTLS {@code false} otherwise.
   */
  public boolean isStartTLS()
  {
    // FIXME the code down below is what the code was doing in the control-panel / dsreplication
    // We might as well just return this.connectionType == START_TLS;
    return ConnectionUtils.isStartTLS(ldapContext);
  }
 
  private InitialLdapContext createAdministrativeContext(Options options) throws NamingException
  {
    final InitialLdapContext ctx = createAdministrativeContext0(options);
    if (!connectedAsAdministrativeUser(ctx))
    {
      throw new NoPermissionException(ERR_NOT_ADMINISTRATIVE_USER.get().toString());
    }
    return ctx;
  }
 
  private InitialLdapContext createAdministrativeContext0(Options options) throws NamingException
  {
    boolean useSSL = options.get(SSL_CONTEXT) != null;
    final String ldapUrl = getLDAPUrl(getHostPort(), useSSL);
    final String bindDnStr = bindDn.toString();
    switch (connectionType)
    {
    case LDAPS:
      return createLdapsContext(ldapUrl, bindDnStr, bindPwd, connectTimeout, null, trustManager, keyManager);
    case START_TLS:
      return createStartTLSContext(ldapUrl, bindDnStr, bindPwd, connectTimeout, null, trustManager, keyManager, null);
    case LDAP:
      return createLdapContext(ldapUrl, bindDnStr, bindPwd, connectTimeout, null);
    default:
      throw new RuntimeException("Not implemented for connection type: " + connectionType);
    }
  }
 
  private Connection buildConnection() throws NamingException
  {
    try
    {
      return connectionFactory.getConnection();
    }
    catch (LdapException e)
    {
      throw new NamingException("Unable to get a connection from connection factory:" + e.getMessage());
    }
  }
 
  /**
   * Returns the connection.
   *
   * @return the connection
   */
  public Connection getConnection()
  {
    return connection;
  }
 
  /**
   * Returns the connection type used by this connection wrapper.
   *
   * @return the connection type used by this connection wrapper
   */
  public PreferredConnection.Type getConnectionType()
  {
    // FIXME the code down below is what the code was doing in the control-panel / dsreplication
    // We might as well just return this.connectionType;
    if (isSSL())
    {
      return LDAPS;
    }
    else if (isStartTLS())
    {
      return START_TLS;
    }
    else
    {
      return LDAP;
    }
  }
 
  /**
   * Returns the ldap context (JNDI).
   *
   * @return the ldap context
   */
  public InitialLdapContext getLdapContext()
  {
    return ldapContext;
  }
 
  /**
   * Returns the host name and port number of this connection.
   *
   * @return the hostPort of this connection
   */
  public HostPort getHostPort()
  {
    return hostPort;
  }
 
  /**
   * Returns the root configuration client by using the inrnal Connection.
   *
   * @return the root configuration client
   */
  public RootCfgClient getRootConfiguration()
  {
    return newManagementContext(getConnection(), LDAPProfile.getInstance()).getRootConfiguration();
  }
 
  @Override
  public void close()
  {
    StaticUtils.close(connectionFactory, connection);
    StaticUtils.close(ldapContext);
  }
}