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

Jean-Noel Rouvignac
18.26.2015 ca669ae54f86dbeea277280690584d9f591c7571
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
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at legal-notices/CDDLv1_0.txt.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2007-2010 Sun Microsystems, Inc.
 *      Portions Copyright 2014-2015 ForgeRock AS
 */
 
package org.opends.admin.ads;
 
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
 
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
 
import org.opends.admin.ads.ADSContext.ServerProperty;
import org.opends.server.admin.ManagedObjectNotFoundException;
import org.opends.server.admin.client.ManagementContext;
import org.opends.server.admin.client.ldap.JNDIDirContextAdaptor;
import org.opends.server.admin.client.ldap.LDAPManagementContext;
import org.opends.server.admin.std.client.*;
import org.opends.server.admin.std.meta.BackendCfgDefn;
import org.opends.server.admin.std.meta.LDIFBackendCfgDefn;
import org.opends.server.config.ConfigConstants;
import org.opends.server.crypto.CryptoManagerImpl;
import org.opends.server.types.CryptoManagerException;
import org.opends.server.types.DN;
 
/**
 * This is the only class in the org.opends.admin.ads package that uses the
 * classes from OpenDS.jar (in particular the administration client framework
 * API).  Before calling this class OpenDS.jar must be
 * loaded.  The goal is basically to centralize in one single place the
 * dependencies of this package on OpenDS.jar.  This is done in order the
 * QuickSetup code to be able to use some of the functionalities provided
 * by the ADSContext classes before OpenDS.jar is downloaded.
 */
public class ADSContextHelper
{
  /**
   * Default constructor.
   */
  public ADSContextHelper()
  {
  }
  /**
   * Removes the administration suffix.
   * @param ctx the DirContext to be used.
   * @param backendName the name of the backend where the administration
   * suffix is stored.
   * @throws ADSContextException if the administration suffix could not be
   * removed.
   */
  public void removeAdministrationSuffix(InitialLdapContext ctx,
      String backendName) throws ADSContextException
  {
    try
    {
      ManagementContext mCtx = LDAPManagementContext.createFromContext(
          JNDIDirContextAdaptor.adapt(ctx));
      RootCfgClient root = mCtx.getRootConfiguration();
      BackendCfgClient backend = null;
      try
      {
        backend = root.getBackend(backendName);
      }
      catch (ManagedObjectNotFoundException monfe)
      {
        // It does not exist.
      }
      if (backend != null)
      {
        SortedSet<DN> suffixes = backend.getBaseDN();
        if (suffixes != null
            && suffixes.remove(DN.valueOf(ADSContext.getAdministrationSuffixDN())))
        {
          if (suffixes.size() > 0)
          {
            backend.setBaseDN(suffixes);
            backend.commit();
          }
          else
          {
            root.removeBackend(backendName);
          }
        }
      }
    }
    catch (Throwable t)
    {
      throw new ADSContextException(
          ADSContextException.ErrorType.ERROR_UNEXPECTED, t);
    }
  }
 
  /**
   * Creates the Administration Suffix.
   * @param ctx the DirContext to be used.
   * @param backendName the name of the backend where the administration
   * suffix is stored.
   * @throws ADSContextException if the administration suffix could not be
   * created.
   */
  public void createAdministrationSuffix(InitialLdapContext ctx,
      String backendName)
  throws ADSContextException
  {
    try
    {
      ManagementContext mCtx = LDAPManagementContext.createFromContext(
          JNDIDirContextAdaptor.adapt(ctx));
      RootCfgClient root = mCtx.getRootConfiguration();
      LDIFBackendCfgClient backend = null;
      try
      {
        backend = (LDIFBackendCfgClient)root.getBackend(backendName);
      }
      catch (ManagedObjectNotFoundException e)
      {
      }
      catch (ClassCastException cce)
      {
        throw new ADSContextException(
            ADSContextException.ErrorType.UNEXPECTED_ADS_BACKEND_TYPE, cce);
      }
 
      if (backend == null)
      {
        LDIFBackendCfgDefn provider = LDIFBackendCfgDefn.getInstance();
        backend = root.createBackend(provider, backendName, null);
        backend.setEnabled(true);
        backend.setLDIFFile(ADSContext.getAdminLDIFFile());
        backend.setBackendId(backendName);
        backend.setWritabilityMode(BackendCfgDefn.WritabilityMode.ENABLED);
        backend.setIsPrivateBackend(true);
      }
      SortedSet<DN> suffixes = backend.getBaseDN();
      if (suffixes == null)
      {
        suffixes = new TreeSet<DN>();
      }
      DN newDN = DN.valueOf(ADSContext.getAdministrationSuffixDN());
      if (!suffixes.contains(newDN))
      {
        suffixes.add(newDN);
        backend.setBaseDN(suffixes);
        backend.commit();
      }
    }
    catch (Throwable t)
    {
      throw new ADSContextException(
          ADSContextException.ErrorType.ERROR_UNEXPECTED, t);
    }
  }
 
  /**
  Register instance key-pair public-key certificate provided in
  serverProperties: generate a key-id attribute if one is not provided (as
  expected); add an instance key public-key certificate entry for the key
  certificate; and associate the certificate entry with the server entry via
  the key ID attribute.
  @param ctx the InitialLdapContext on the server we want to update.
  @param serverProperties Properties of the server being registered to which
  the instance key entry belongs.
  @param serverEntryDn The server's ADS entry DN.
  @throws ADSContextException In case some JNDI operation fails or there is a
  problem getting the instance public key certificate ID.
   */
  public void registerInstanceKeyCertificate(
      InitialLdapContext ctx, Map<ServerProperty, Object> serverProperties,
      LdapName serverEntryDn)
  throws ADSContextException {
    assert serverProperties.containsKey(
        ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE);
    if (! serverProperties.containsKey(
        ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE)) {
      return;
    }
 
    /* the key ID might be supplied in serverProperties (although, I am unaware
   of any such case). */
    String keyID = (String)serverProperties.get(ServerProperty.INSTANCE_KEY_ID);
 
    /* these attributes are used both to search for an existing certificate
   entry and, if one does not exist, add a new certificate entry */
    final BasicAttributes keyAttrs = new BasicAttributes();
    final Attribute oc = new BasicAttribute("objectclass");
    oc.add("top"); oc.add("ds-cfg-instance-key");
    keyAttrs.put(oc);
    if (null != keyID) {
      keyAttrs.put(new BasicAttribute(
          ServerProperty.INSTANCE_KEY_ID.getAttributeName(), keyID));
    }
    keyAttrs.put(new BasicAttribute(
        ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE.getAttributeName()
        + ";binary",
        serverProperties.get(
            ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE)));
 
    /* search for public-key certificate entry in ADS DIT */
    final String attrIDs[] = { "ds-cfg-key-id" };
    NamingEnumeration<SearchResult> results = null;
    try
    {
      results = ctx.search(ADSContext.getInstanceKeysContainerDN(), keyAttrs,
         attrIDs);
      boolean found = false;
      while (results.hasMore()) {
        final Attribute keyIdAttr =
          results.next().getAttributes().get(attrIDs[0]);
        if (null != keyIdAttr) {
          /* attribute ds-cfg-key-id is the entry is a MUST in the schema */
          keyID = (String)keyIdAttr.get();
        }
        found = true;
      }
      /* TODO: It is possible (but unexpected) that the caller specifies a
   ds-cfg-key-id value for which there is a certificate entry in ADS, but
   the certificate value does not match that supplied by the caller. The
   above search would not return the entry, but the below attempt to add
   an new entry with the supplied ds-cfg-key-id will fail (throw a
   NameAlreadyBoundException) */
      if (!found) {
        /* create key ID, if it was not supplied in serverProperties */
        if (null == keyID) {
          keyID = CryptoManagerImpl.getInstanceKeyID(
              (byte[])serverProperties.get(
                  ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE));
          keyAttrs.put(new BasicAttribute(
              ServerProperty.INSTANCE_KEY_ID.getAttributeName(), keyID));
        }
 
        /* add public-key certificate entry */
        final LdapName keyDn = new LdapName((new StringBuilder())
            .append(ServerProperty.INSTANCE_KEY_ID.getAttributeName())
            .append("=").append(Rdn.escapeValue(keyID)).append(",")
            .append(ADSContext.getInstanceKeysContainerDN()).toString());
        ctx.createSubcontext(keyDn, keyAttrs).close();
      }
 
      if (serverEntryDn != null)
      {
        /* associate server entry with certificate entry via key ID attribute */
        ctx.modifyAttributes(serverEntryDn,
          InitialLdapContext.REPLACE_ATTRIBUTE,
          (new BasicAttributes(
              ServerProperty.INSTANCE_KEY_ID.getAttributeName(), keyID)));
      }
    }
    catch (NamingException ne)
    {
      throw new ADSContextException(
          ADSContextException.ErrorType.ERROR_UNEXPECTED, ne);
    }
    catch (CryptoManagerException cme)
    {
      throw new ADSContextException(
          ADSContextException.ErrorType.ERROR_UNEXPECTED, cme);
    }
    finally
    {
      handleCloseNamingEnumeration(results);
    }
  }
 
 
  /**
  Unregister instance key-pair public-key certificate provided in
  serverProperties.
  @param ctx the connection to the server.
  @param serverProperties Properties of the server being unregistered to which
  the instance key entry belongs.
  @param serverEntryDn The server's ADS entry DN.
  @throws ADSContextException In case some JNDI operation fails.
  */
  public void unregisterInstanceKeyCertificate(
      InitialLdapContext ctx, Map<ServerProperty, Object> serverProperties,
      LdapName serverEntryDn)
  throws ADSContextException {
    assert serverProperties.containsKey(
        ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE);
    if (! serverProperties.containsKey(
        ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE)) {
      return;
    }
 
    /* these attributes are used both to search for an existing certificate
     entry and, if one does not exist, add a new certificate entry */
    final BasicAttributes keyAttrs = new BasicAttributes();
    final Attribute oc = new BasicAttribute("objectclass");
    oc.add("top"); oc.add("ds-cfg-instance-key");
    keyAttrs.put(oc);
    keyAttrs.put(new BasicAttribute(
        ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE.getAttributeName()
        + ";binary",
        serverProperties.get(
            ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE)));
 
    /* search for public-key certificate entry in ADS DIT */
    final String attrIDs[] = { "ds-cfg-key-id" };
    NamingEnumeration<SearchResult> results = null;
    try
    {
      results = ctx.search(
          ADSContext.getInstanceKeysContainerDN(), keyAttrs, attrIDs);
      while (results.hasMore()) {
        SearchResult res = results.next();
        ctx.destroySubcontext(res.getNameInNamespace());
      }
    }
    catch (NameNotFoundException nnfe)
    {
    }
    catch (NamingException ne)
    {
      throw new ADSContextException(
          ADSContextException.ErrorType.ERROR_UNEXPECTED, ne);
    }
    finally
    {
      handleCloseNamingEnumeration(results);
    }
  }
 
  /**
   * Returns the crypto instance key objectclass name as defined in
   * ConfigConstants.
   * @return the crypto instance key objectclass name as defined in
   * ConfigConstants.
   */
  public String getOcCryptoInstanceKey()
  {
    return ConfigConstants.OC_CRYPTO_INSTANCE_KEY;
  }
 
  /**
   * Returns the crypto key compromised time attribute name as defined in
   * ConfigConstants.
   * @return the crypto key compromised time attribute name as defined in
   * ConfigConstants.
   */
  public String getAttrCryptoKeyCompromisedTime()
  {
    return ConfigConstants.ATTR_CRYPTO_KEY_COMPROMISED_TIME;
  }
 
  private void handleCloseNamingEnumeration(NamingEnumeration<?> ne)
  throws ADSContextException
  {
    if (ne != null)
    {
      try
      {
        ne.close();
      }
      catch (NamingException ex)
      {
        throw new ADSContextException(
            ADSContextException.ErrorType.ERROR_UNEXPECTED, ex);
      }
    }
  }
}