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

Jean-Noel Rouvignac
17.23.2015 a2c984366f119a651851cb4aa8f16466d3ae4e96
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
/*
 * 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 2008-2010 Sun Microsystems, Inc.
 *      Portions Copyright 2013-2015 ForgeRock AS
 */
package org.opends.server.util;
 
import java.io.*;
import java.security.*;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import org.forgerock.i18n.LocalizableMessage;
import static org.opends.messages.UtilityMessages.*;
 
/**
 * This class provides an interface for generating self-signed certificates and
 * certificate signing requests, and for importing, exporting, and deleting
 * certificates from a key store.  It supports JKS, PKCS11, and PKCS12 key store
 * types.
 * <BR><BR>
   This code uses the Platform class to perform all of the certificate
    management.
 */
@org.opends.server.types.PublicAPI(
     stability=org.opends.server.types.StabilityLevel.VOLATILE,
     mayInstantiate=true,
     mayExtend=false,
     mayInvoke=true)
public final class CertificateManager {
 
  /**
   * The key store type value that should be used for the "JKS" key store.
   */
  public static final String KEY_STORE_TYPE_JKS = "JKS";
 
  /**
   * The key store type value that should be used for the "JCEKS" key store.
   */
  public static final String KEY_STORE_TYPE_JCEKS = "JCEKS";
 
  /**
   * The key store type value that should be used for the "PKCS11" key store.
   */
  public static final String KEY_STORE_TYPE_PKCS11 = "PKCS11";
 
  /**
   * The key store type value that should be used for the "PKCS12" key store.
   */
  public static final String KEY_STORE_TYPE_PKCS12 = "PKCS12";
 
  /**
   * The key store path value that must be used in conjunction with the PKCS11
   * key store type.
   */
  public static final String KEY_STORE_PATH_PKCS11 = "NONE";
 
  //Error message strings.
  private static final String KEYSTORE_PATH_MSG = "key store path";
  private static final String KEYSTORE_TYPE_MSG = "key store type";
  private static final String SUBJECT_DN_MSG = "subject DN";
  private static final String CERT_ALIAS_MSG = "certificate alias";
  private static final String CERT_REQUEST_FILE_MSG =
                                                    "certificate request file";
  // The parsed key store backing this certificate manager.
  private KeyStore keyStore;
 
  // The path to the key store that we should be using.
  private final String keyStorePath;
 
  // The name of the key store type we are using.
  private final String keyStoreType;
 
  private final char[] password;
 
  private Boolean realAliases;
 
  /**
   * Always return true.
   *
   * @return  This always returns true;
   */
  public static boolean mayUseCertificateManager() {
    return true;
  }
 
 
 
  /**
   * Creates a new certificate manager instance with the provided information.
   *
   * @param  keyStorePath  The path to the key store file, or "NONE" if the key
   *                       store type is "PKCS11".  For the other key store
   *                       types, the file does not need to exist if a new
   *                       self-signed certificate or certificate signing
   *                       request is to be generated, although the directory
   *                       containing the file must exist.  The key store file
   *                       must exist if import or export operations are to be
   *                       performed.
   * @param  keyStoreType  The key store type to use.  It should be one of
   *                       {@code KEY_STORE_TYPE_JKS},
   *                       {@code KEY_STORE_TYPE_JCEKS},
   *                       {@code KEY_STORE_TYPE_PKCS11}, or
   *                       {@code KEY_STORE_TYPE_PKCS12}.
   * @param  keyStorePassword   The password required to access the key store.
   *                         It must not be {@code null}.
   * @throws IllegalArgumentException If an argument is invalid or {@code null}.
   *
   */
  public CertificateManager(String keyStorePath, String keyStoreType,
                            String keyStorePassword)
  throws IllegalArgumentException {
    ensureValid(keyStorePath, KEYSTORE_PATH_MSG);
    ensureValid(keyStoreType, KEYSTORE_TYPE_MSG);
    if (keyStoreType.equals(KEY_STORE_TYPE_PKCS11)) {
      if (! keyStorePath.equals(KEY_STORE_PATH_PKCS11)) {
        LocalizableMessage msg =
          ERR_CERTMGR_INVALID_PKCS11_PATH.get(KEY_STORE_PATH_PKCS11);
        throw new IllegalArgumentException(msg.toString());
      }
    } else if (keyStoreType.equals(KEY_STORE_TYPE_JKS) ||
        keyStoreType.equals(KEY_STORE_TYPE_JCEKS) ||
        keyStoreType.equals(KEY_STORE_TYPE_PKCS12)) {
      File keyStoreFile = new File(keyStorePath);
      if (keyStoreFile.exists()) {
        if (! keyStoreFile.isFile()) {
          LocalizableMessage msg = ERR_CERTMGR_INVALID_KEYSTORE_PATH.get(keyStorePath);
          throw new IllegalArgumentException(msg.toString());
        }
      } else {
        final File keyStoreDirectory = keyStoreFile.getParentFile();
        if ((keyStoreDirectory == null) || (! keyStoreDirectory.exists()) ||
            (! keyStoreDirectory.isDirectory())) {
          LocalizableMessage msg = ERR_CERTMGR_INVALID_PARENT.get(keyStorePath);
          throw new IllegalArgumentException(msg.toString());
        }
      }
    } else {
      LocalizableMessage msg =  ERR_CERTMGR_INVALID_STORETYPE.get(
          KEY_STORE_TYPE_JKS, KEY_STORE_TYPE_JCEKS,
          KEY_STORE_TYPE_PKCS11, KEY_STORE_TYPE_PKCS12);
      throw new IllegalArgumentException(msg.toString());
    }
    this.keyStorePath = keyStorePath;
    this.keyStoreType = keyStoreType;
    this.password =
        keyStorePassword == null ? null : keyStorePassword.toCharArray();
    keyStore = null;
  }
 
 
 
  /**
   * Indicates whether the provided alias is in use in the key store.
   *
   * @param  alias  The alias for which to make the determination.  It must not
   *                be {@code null} or empty.
   *
   * @return  {@code true} if the key store exist and already contains a
   *          certificate with the given alias, or {@code false} if not.
   *
   * @throws  KeyStoreException  If a problem occurs while attempting to
   *                             interact with the key store.
   */
  public boolean aliasInUse(final String alias)
  throws KeyStoreException {
    ensureValid(alias, CERT_ALIAS_MSG);
    KeyStore keyStore = getKeyStore();
    return keyStore != null && keyStore.containsAlias(alias);
  }
 
 
 
  /**
   * Retrieves the aliases of the certificates in the specified key store.
   *
   * @return  The aliases of the certificates in the specified key store, or
   *          {@code null} if the key store does not exist.
   *
   * @throws  KeyStoreException  If a problem occurs while attempting to
   *                             interact with the key store.
   */
  public String[] getCertificateAliases() throws KeyStoreException {
    Enumeration<String> aliasEnumeration = null;
    KeyStore keyStore = getKeyStore();
    if (keyStore == null)
      return null;
    aliasEnumeration = keyStore.aliases();
    if (aliasEnumeration == null)
      return new String[0];
    ArrayList<String> aliasList = new ArrayList<String>();
    while (aliasEnumeration.hasMoreElements())
      aliasList.add(aliasEnumeration.nextElement());
    String[] aliases = new String[aliasList.size()];
    return aliasList.toArray(aliases);
  }
 
 
 
  /**
   * Retrieves the certificate with the specified alias from the key store.
   *
   * @param  alias  The alias of the certificate to retrieve.  It must not be
   *                {@code null} or empty.
   *
   * @return  The requested certificate, or {@code null} if the specified
   *          certificate does not exist.
   *
   * @throws  KeyStoreException  If a problem occurs while interacting with the
   *                             key store, or the key store does not exist..
   */
  public Certificate  getCertificate(String alias)
  throws KeyStoreException {
    ensureValid(alias, CERT_ALIAS_MSG);
    KeyStore ks = getKeyStore();
    if (ks == null) {
      LocalizableMessage msg = ERR_CERTMGR_KEYSTORE_NONEXISTANT.get();
      throw new KeyStoreException(msg.toString());
    }
    return ks.getCertificate(alias);
  }
 
 
  /**
   * Generates a self-signed certificate using the provided information.
   *
   * @param  alias      The nickname to use for the certificate in the key
   *                    store.  For the server certificate, it should generally
   *                    be "server-cert".  It must not be {@code null} or empty.
   * @param  subjectDN  The subject DN to use for the certificate.  It must not
   *                    be {@code null} or empty.
   * @param  validity   The length of time in days that the certificate should
   *                    be valid, starting from the time the certificate is
   *                    generated.  It must be a positive integer value.
   * @throws  KeyStoreException  If a problem occurs while actually attempting
   *                             to generate the certificate in the key store.
   *@throws IllegalArgumentException If the validity parameter is not a
   *                                 positive integer, or the alias is already
   *                                 in the keystore.
   */
  public void generateSelfSignedCertificate(String alias, String subjectDN,
                                            int validity)
  throws KeyStoreException, IllegalArgumentException {
    ensureValid(alias, CERT_ALIAS_MSG);
    ensureValid(subjectDN, SUBJECT_DN_MSG);
    if (validity <= 0) {
      LocalizableMessage msg = ERR_CERTMGR_VALIDITY.get(validity);
      throw new IllegalArgumentException(msg.toString());
    }
    if (aliasInUse(alias)) {
      LocalizableMessage msg = ERR_CERTMGR_ALIAS_ALREADY_EXISTS.get(alias);
      throw new IllegalArgumentException(msg.toString());
    }
    keyStore = null;
    Platform.generateSelfSignedCertificate(getKeyStore(), keyStoreType,
        keyStorePath, alias, password, subjectDN, validity);
  }
 
 
 
  /**
   * Adds the provided certificate to the key store.  This may be used to
   * associate an externally-signed certificate with an existing private key
   * with the given alias.
   *
   * @param  alias            The alias to use for the certificate.  It must not
   *                          be {@code null} or empty.
   * @param  certificateFile  The file containing the encoded certificate.  It
   *                          must not be {@code null}, and the file must exist.
 
   * @throws  KeyStoreException  If a problem occurs while interacting with the
   *                             key store.
   *
   *@throws IllegalArgumentException If the certificate file is not valid.
   */
  public void addCertificate(String alias, File certificateFile)
  throws  KeyStoreException, IllegalArgumentException {
    ensureValid(alias, CERT_ALIAS_MSG);
    ensureFileValid(certificateFile, CERT_REQUEST_FILE_MSG);
    if ((! certificateFile.exists()) ||
        (! certificateFile.isFile())) {
      LocalizableMessage msg = ERR_CERTMGR_INVALID_CERT_FILE.get(
          certificateFile.getAbsolutePath());
      throw new IllegalArgumentException(msg.toString());
    }
    keyStore = null;
    Platform.addCertificate(getKeyStore(), keyStoreType, keyStorePath, alias,
        password, certificateFile.getAbsolutePath());
  }
 
 
  /**
   * Removes the specified certificate from the key store.
   *
   * @param  alias  The alias to use for the certificate to remove.  It must not
   *                be {@code null} or an empty string, and it must exist in
   *                the key store.
   *
   * @throws  KeyStoreException  If a problem occurs while interacting with the
   *                             key store.
   *@throws IllegalArgumentException If the alias is in use and cannot be
   *                                 deleted.
   */
  public void removeCertificate(String alias)
  throws KeyStoreException, IllegalArgumentException {
    ensureValid(alias, CERT_ALIAS_MSG);
    if (!aliasInUse(alias)) {
      LocalizableMessage msg = ERR_CERTMGR_ALIAS_CAN_NOT_DELETE.get(alias);
      throw new IllegalArgumentException(msg.toString());
    }
    keyStore = null;
    Platform.deleteAlias(getKeyStore(), keyStorePath, alias, password);
  }
 
 
  /**
   * Retrieves a handle to the key store.
   *
   * @return  The handle to the key store, or {@code null} if the key store
   *          doesn't exist.
   *
   * @throws  KeyStoreException  If a problem occurs while trying to open the
   *                             key store.
   */
  private KeyStore getKeyStore()
  throws KeyStoreException
  {
      if (keyStore != null)
      {
          return keyStore;
      }
 
      // For JKS and PKCS12 key stores, we should make sure the file exists, and
      // we'll need an input stream that we can use to read it.  For PKCS11 key
      // stores there won't be a file and the input stream should be null.
      FileInputStream keyStoreInputStream = null;
      if (keyStoreType.equals(KEY_STORE_TYPE_JKS) ||
          keyStoreType.equals(KEY_STORE_TYPE_JCEKS) ||
          keyStoreType.equals(KEY_STORE_TYPE_PKCS12))
      {
          final File keyStoreFile = new File(keyStorePath);
          if (! keyStoreFile.exists())
          {
              return null;
          }
 
          try
          {
              keyStoreInputStream = new FileInputStream(keyStoreFile);
          }
          catch (final Exception e)
          {
              throw new KeyStoreException(String.valueOf(e), e);
          }
      }
 
 
      final KeyStore keyStore = KeyStore.getInstance(keyStoreType);
      try
      {
          keyStore.load(keyStoreInputStream, password);
          return this.keyStore = keyStore;
      }
      catch (final Exception e)
      {
          throw new KeyStoreException(String.valueOf(e), e);
      }
      finally
      {
          if (keyStoreInputStream != null)
          {
              try
              {
                  keyStoreInputStream.close();
              }
              catch (final Throwable t)
              {
              }
          }
      }
  }
 
  /**
   * Returns whether this certificate manager contains 'real' aliases or not.
   * For instance, the certificate manager can contain a PKCS12 certificate
   * with no alias.
   * @return whether this certificate manager contains 'real' aliases or not.
   * @throws KeyStoreException if there is a problem accessing the key store.
   */
  public boolean hasRealAliases() throws KeyStoreException
  {
    if (realAliases == null)
    {
      String[] aliases = getCertificateAliases();
      if (aliases == null || aliases.length == 0)
      {
        realAliases = Boolean.FALSE;
      }
      else if (aliases.length > 1)
      {
        realAliases = Boolean.TRUE;
      }
      else
      {
        CertificateManager certManager2 = new CertificateManager(keyStorePath,
            keyStoreType, new String(password));
        String[] aliases2 = certManager2.getCertificateAliases();
        if (aliases2 != null && aliases2.length == 1)
        {
          realAliases = aliases[0].equalsIgnoreCase(aliases2[0]);
        }
        else
        {
          realAliases = Boolean.FALSE;
        }
      }
    }
    return realAliases;
  }
 
  private static void ensureFileValid(File arg, String msgStr) {
    if(arg == null) {
      LocalizableMessage msg = ERR_CERTMGR_FILE_NAME_INVALID.get(msgStr);
      throw new NullPointerException(msg.toString());
    }
  }
 
  private static void ensureValid(String arg, String msgStr) {
    if(arg == null || arg.length() == 0) {
     LocalizableMessage msg = ERR_CERTMGR_VALUE_INVALID.get(msgStr);
      throw new NullPointerException(msg.toString());
    }
  }
}