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
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
/*
 * 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 2006-2008 Sun Microsystems, Inc.
 *      Portions Copyright 2011-2015 ForgeRock AS
 */
package org.opends.server.extensions;
import org.forgerock.i18n.LocalizableMessage;
 
 
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.util.List;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
 
import org.opends.server.admin.server.ConfigurationChangeListener;
import org.opends.server.admin.std.server.FileBasedKeyManagerProviderCfg;
import org.opends.server.api.KeyManagerProvider;
import org.forgerock.opendj.config.server.ConfigException;
import org.opends.server.core.DirectoryServer;
import org.forgerock.opendj.config.server.ConfigChangeResult;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.DN;
import org.opends.server.types.InitializationException;
import org.forgerock.opendj.ldap.ResultCode;
 
import org.forgerock.i18n.slf4j.LocalizedLogger;
import static org.opends.messages.ExtensionMessages.*;
 
import static org.opends.server.util.StaticUtils.*;
 
 
 
/**
 * This class defines a key manager provider that will access keys stored in a
 * file located on the Directory Server filesystem.
 */
public class FileBasedKeyManagerProvider
       extends KeyManagerProvider<FileBasedKeyManagerProviderCfg>
       implements ConfigurationChangeListener<FileBasedKeyManagerProviderCfg>
{
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
 
 
  // The DN of the configuration entry for this key manager provider.
  private DN configEntryDN;
 
  // The PIN needed to access the keystore.
  private char[] keyStorePIN;
 
  // The configuration for this key manager provider.
  private FileBasedKeyManagerProviderCfg currentConfig;
 
  // The path to the key store backing file.
  private String keyStoreFile;
 
  // The key store type to use.
  private String keyStoreType;
 
 
 
  /**
   * Creates a new instance of this file-based key manager provider.  The
   * <CODE>initializeKeyManagerProvider</CODE> method must be called on the
   * resulting object before it may be used.
   */
  public FileBasedKeyManagerProvider()
  {
    // No implementation is required.
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override
  public void initializeKeyManagerProvider(
      FileBasedKeyManagerProviderCfg configuration)
      throws ConfigException, InitializationException {
    // Store the DN of the configuration entry and register as a change
    // listener.
    currentConfig = configuration;
    configEntryDN = configuration.dn();
    configuration.addFileBasedChangeListener(this);
 
 
    // Get the path to the key store file.
    keyStoreFile = configuration.getKeyStoreFile();
    try {
      File f = getFileForPath(keyStoreFile);
      if (!f.exists() || !f.isFile()) {
        throw new InitializationException(ERR_FILE_KEYMANAGER_NO_SUCH_FILE.get(keyStoreFile, configEntryDN));
      }
    } catch (SecurityException e) {
      logger.traceException(e);
 
      LocalizableMessage message = ERR_FILE_KEYMANAGER_CANNOT_DETERMINE_FILE.get(
          configEntryDN, getExceptionMessage(e));
      throw new InitializationException(message, e);
    }
 
    // Get the keystore type. If none is specified, then use the
    // default type.
    if (configuration.getKeyStoreType() != null) {
      try {
        KeyStore.getInstance(configuration.getKeyStoreType());
        keyStoreType = configuration.getKeyStoreType();
      } catch (KeyStoreException kse) {
        logger.traceException(kse);
 
        LocalizableMessage message = ERR_FILE_KEYMANAGER_INVALID_TYPE.
            get(configuration.getKeyStoreType(), configEntryDN, getExceptionMessage(kse));
        throw new InitializationException(message);
      }
    } else {
      keyStoreType = KeyStore.getDefaultType();
    }
 
    // Get the PIN needed to access the contents of the keystore file.
    //
    // We will offer several places to look for the PIN, and we will
    // do so in the following order:
    //
    // - In a specified Java property
    // - In a specified environment variable
    // - In a specified file on the server filesystem.
    // - As the value of a configuration attribute.
    //
    // In any case, the PIN must be in the clear.
    keyStorePIN = null;
 
    if (configuration.getKeyStorePinProperty() != null) {
      String propertyName = configuration.getKeyStorePinProperty();
      String pinStr = System.getProperty(propertyName);
 
      if (pinStr == null) {
        LocalizableMessage message = ERR_FILE_KEYMANAGER_PIN_PROPERTY_NOT_SET.get(
            propertyName, configEntryDN);
        throw new InitializationException(message);
      }
 
      keyStorePIN = pinStr.toCharArray();
    } else if (configuration.getKeyStorePinEnvironmentVariable() != null) {
      String enVarName = configuration
          .getKeyStorePinEnvironmentVariable();
      String pinStr = System.getenv(enVarName);
 
      if (pinStr == null) {
        LocalizableMessage message = ERR_FILE_KEYMANAGER_PIN_ENVAR_NOT_SET.get(
            enVarName, configEntryDN);
        throw new InitializationException(message);
      }
 
      keyStorePIN = pinStr.toCharArray();
    } else if (configuration.getKeyStorePinFile() != null) {
      String fileName = configuration.getKeyStorePinFile();
      File pinFile = getFileForPath(fileName);
 
      if (!pinFile.exists()) {
        LocalizableMessage message = ERR_FILE_KEYMANAGER_PIN_NO_SUCH_FILE.get(
            fileName, configEntryDN);
        throw new InitializationException(message);
      }
 
      String pinStr;
      try {
        BufferedReader br = new BufferedReader(
            new FileReader(pinFile));
        pinStr = br.readLine();
        br.close();
      } catch (IOException ioe) {
        LocalizableMessage message = ERR_FILE_KEYMANAGER_PIN_FILE_CANNOT_READ.
            get(fileName, configEntryDN, getExceptionMessage(ioe));
        throw new InitializationException(message, ioe);
      }
 
      if (pinStr == null) {
        LocalizableMessage message = ERR_FILE_KEYMANAGER_PIN_FILE_EMPTY.get(fileName, configEntryDN);
        throw new InitializationException(message);
      }
 
      keyStorePIN = pinStr.toCharArray();
    } else if (configuration.getKeyStorePin() != null) {
      keyStorePIN = configuration.getKeyStorePin().toCharArray();
    }
  }
 
 
 
  /**
   * Performs any finalization that may be necessary for this key
   * manager provider.
   */
  public void finalizeKeyManagerProvider()
  {
    currentConfig.removeFileBasedChangeListener(this);
  }
 
 
 
  /**
   * Retrieves a set of <CODE>KeyManager</CODE> objects that may be used for
   * interactions requiring access to a key manager.
   *
   * @return  A set of <CODE>KeyManager</CODE> objects that may be used for
   *          interactions requiring access to a key manager.
   *
   * @throws  DirectoryException  If a problem occurs while attempting to obtain
   *                              the set of key managers.
   */
  public KeyManager[] getKeyManagers()
         throws DirectoryException
  {
    KeyStore keyStore;
    try
    {
      keyStore = KeyStore.getInstance(keyStoreType);
 
      FileInputStream inputStream =
           new FileInputStream(getFileForPath(keyStoreFile));
      keyStore.load(inputStream, keyStorePIN);
      inputStream.close();
    }
    catch (Exception e)
    {
      logger.traceException(e);
 
      LocalizableMessage message = ERR_FILE_KEYMANAGER_CANNOT_LOAD.get(
          keyStoreFile, getExceptionMessage(e));
      throw new DirectoryException(DirectoryServer.getServerErrorResultCode(),
                                   message, e);
    }
 
 
    try
    {
      String keyManagerAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
      KeyManagerFactory keyManagerFactory =
           KeyManagerFactory.getInstance(keyManagerAlgorithm);
      keyManagerFactory.init(keyStore, keyStorePIN);
      return keyManagerFactory.getKeyManagers();
    }
    catch (Exception e)
    {
      logger.traceException(e);
 
      LocalizableMessage message = ERR_FILE_KEYMANAGER_CANNOT_CREATE_FACTORY.get(
          keyStoreFile, getExceptionMessage(e));
      throw new DirectoryException(DirectoryServer.getServerErrorResultCode(),
                                   message, e);
    }
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override
  public boolean isConfigurationAcceptable(
                        FileBasedKeyManagerProviderCfg configuration,
                        List<LocalizableMessage> unacceptableReasons)
  {
    return isConfigurationChangeAcceptable(configuration, unacceptableReasons);
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  public boolean isConfigurationChangeAcceptable(
                      FileBasedKeyManagerProviderCfg configuration,
                      List<LocalizableMessage> unacceptableReasons)
  {
    boolean configAcceptable = true;
    DN cfgEntryDN = configuration.dn();
 
 
    // Get the path to the key store file.
    String newKeyStoreFile = configuration.getKeyStoreFile();
    try
    {
      File f = getFileForPath(newKeyStoreFile);
      if (!f.exists() || !f.isFile())
      {
        unacceptableReasons.add(ERR_FILE_KEYMANAGER_NO_SUCH_FILE.get(newKeyStoreFile, cfgEntryDN));
        configAcceptable = false;
      }
    }
    catch (Exception e)
    {
      logger.traceException(e);
 
      unacceptableReasons.add(ERR_FILE_KEYMANAGER_CANNOT_DETERMINE_FILE.get(cfgEntryDN, getExceptionMessage(e)));
      configAcceptable = false;
    }
 
    // Get the keystore type. If none is specified, then use the default type.
    if (configuration.getKeyStoreType() != null)
    {
      try
      {
        KeyStore.getInstance(configuration.getKeyStoreType());
      }
      catch (KeyStoreException kse)
      {
        logger.traceException(kse);
 
        unacceptableReasons.add(ERR_FILE_KEYMANAGER_INVALID_TYPE.get(
            configuration.getKeyStoreType(), cfgEntryDN, getExceptionMessage(kse)));
        configAcceptable = false;
      }
    }
 
    // Get the PIN needed to access the contents of the keystore file.
    //
    // We will offer several places to look for the PIN, and we will
    // do so in the following order:
    //
    // - In a specified Java property
    // - In a specified environment variable
    // - In a specified file on the server filesystem.
    // - As the value of a configuration attribute.
    //
    // In any case, the PIN must be in the clear.
    // It is acceptable to have no PIN (OPENDJ-18)
    if (configuration.getKeyStorePinProperty() != null)
    {
      String propertyName = configuration.getKeyStorePinProperty();
      String pinStr = System.getProperty(propertyName);
 
      if (pinStr == null)
      {
        unacceptableReasons.add(ERR_FILE_KEYMANAGER_PIN_PROPERTY_NOT_SET.get(propertyName, cfgEntryDN));
        configAcceptable = false;
      }
    }
    else if (configuration.getKeyStorePinEnvironmentVariable() != null)
    {
      String enVarName = configuration.getKeyStorePinEnvironmentVariable();
      String pinStr    = System.getenv(enVarName);
 
      if (pinStr == null)
      {
        unacceptableReasons.add(ERR_FILE_KEYMANAGER_PIN_ENVAR_NOT_SET.get(enVarName, cfgEntryDN));
        configAcceptable = false;
      }
    }
    else if (configuration.getKeyStorePinFile() != null)
    {
      String fileName = configuration.getKeyStorePinFile();
      File   pinFile  = getFileForPath(fileName);
 
      if (!pinFile.exists())
      {
        unacceptableReasons.add(ERR_FILE_KEYMANAGER_PIN_NO_SUCH_FILE.get(fileName, cfgEntryDN));
        configAcceptable = false;
      }
      else
      {
        String pinStr = null;
        BufferedReader br = null;
        try {
          br = new BufferedReader(new FileReader(pinFile));
          pinStr = br.readLine();
        }
        catch (IOException ioe)
        {
          unacceptableReasons.add(ERR_FILE_KEYMANAGER_PIN_FILE_CANNOT_READ.get(
              fileName, cfgEntryDN, getExceptionMessage(ioe)));
          configAcceptable = false;
        }
        finally
        {
          close(br);
        }
 
        if (pinStr == null)
        {
          unacceptableReasons.add(ERR_FILE_KEYMANAGER_PIN_FILE_EMPTY.get(fileName, cfgEntryDN));
          configAcceptable = false;
        }
      }
    }
    else if (configuration.getKeyStorePin() != null)
    {
      String pinStr = configuration.getKeyStorePin();
      if (pinStr == null)
      {
        unacceptableReasons.add(ERR_FILE_KEYMANAGER_CANNOT_DETERMINE_PIN_FROM_ATTR.get(cfgEntryDN, null));
        configAcceptable = false;
      }
    }
 
    return configAcceptable;
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  public ConfigChangeResult applyConfigurationChange(
                                 FileBasedKeyManagerProviderCfg configuration)
  {
    final ConfigChangeResult ccr = new ConfigChangeResult();
 
 
    // Get the path to the key store file.
    String newKeyStoreFile = configuration.getKeyStoreFile();
    try
    {
      File f = getFileForPath(newKeyStoreFile);
      if (!f.exists() || !f.isFile())
      {
        ccr.setResultCode(DirectoryServer.getServerErrorResultCode());
        ccr.addMessage(ERR_FILE_KEYMANAGER_NO_SUCH_FILE.get(newKeyStoreFile, configEntryDN));
      }
    }
    catch (Exception e)
    {
      logger.traceException(e);
 
      ccr.setResultCode(DirectoryServer.getServerErrorResultCode());
      ccr.addMessage(ERR_FILE_KEYMANAGER_CANNOT_DETERMINE_FILE.get(
          configEntryDN, getExceptionMessage(e)));
    }
 
    // Get the keystore type. If none is specified, then use the default type.
    String newKeyStoreType = KeyStore.getDefaultType();
    if (configuration.getKeyStoreType() != null)
    {
      try
      {
        KeyStore.getInstance(configuration.getKeyStoreType());
        newKeyStoreType = configuration.getKeyStoreType();
      }
      catch (KeyStoreException kse)
      {
        logger.traceException(kse);
 
        ccr.setResultCode(DirectoryServer.getServerErrorResultCode());
        ccr.addMessage(ERR_FILE_KEYMANAGER_INVALID_TYPE.get(
            configuration.getKeyStoreType(), configEntryDN, getExceptionMessage(kse)));
      }
    }
 
    // Get the PIN needed to access the contents of the keystore file.
    //
    // We will offer several places to look for the PIN, and we will
    // do so in the following order:
    //
    // - In a specified Java property
    // - In a specified environment variable
    // - In a specified file on the server filesystem.
    // - As the value of a configuration attribute.
    //
    // In any case, the PIN must be in the clear.
    char[] newPIN = null;
 
    if (configuration.getKeyStorePinProperty() != null)
    {
      String propertyName = configuration.getKeyStorePinProperty();
      String pinStr = System.getProperty(propertyName);
 
      if (pinStr == null)
      {
        ccr.setResultCode(DirectoryServer.getServerErrorResultCode());
        ccr.addMessage(ERR_FILE_KEYMANAGER_PIN_PROPERTY_NOT_SET.get(
            propertyName, configEntryDN));
      }
      else
      {
        newPIN = pinStr.toCharArray();
      }
    }
    else if (configuration.getKeyStorePinEnvironmentVariable() != null)
    {
      String enVarName = configuration.getKeyStorePinEnvironmentVariable();
      String pinStr    = System.getenv(enVarName);
 
      if (pinStr == null)
      {
        ccr.setResultCode(DirectoryServer.getServerErrorResultCode());
        ccr.addMessage(ERR_FILE_KEYMANAGER_PIN_ENVAR_NOT_SET.get(enVarName, configEntryDN));
      }
      else
      {
        newPIN = pinStr.toCharArray();
      }
    }
    else if (configuration.getKeyStorePinFile() != null)
    {
      String fileName = configuration.getKeyStorePinFile();
      File   pinFile  = getFileForPath(fileName);
 
      if (!pinFile.exists())
      {
        ccr.setResultCode(DirectoryServer.getServerErrorResultCode());
        ccr.addMessage(ERR_FILE_KEYMANAGER_PIN_NO_SUCH_FILE.get(fileName, configEntryDN));
      }
      else
      {
        String pinStr = null;
        BufferedReader br = null;
        try {
          br = new BufferedReader(new FileReader(pinFile));
          pinStr = br.readLine();
        }
        catch (IOException ioe)
        {
          ccr.setResultCode(DirectoryServer.getServerErrorResultCode());
          ccr.addMessage(ERR_FILE_KEYMANAGER_PIN_FILE_CANNOT_READ.get(
              fileName, configEntryDN, getExceptionMessage(ioe)));
        }
        finally
        {
          close(br);
        }
 
        if (pinStr == null)
        {
          ccr.setResultCode(DirectoryServer.getServerErrorResultCode());
          ccr.addMessage(ERR_FILE_KEYMANAGER_PIN_FILE_EMPTY.get(fileName, configEntryDN));
        }
        else
        {
          newPIN = pinStr.toCharArray();
        }
      }
    }
    else if (configuration.getKeyStorePin() != null)
    {
      newPIN = configuration.getKeyStorePin().toCharArray();
    }
 
    if (ccr.getResultCode() == ResultCode.SUCCESS)
    {
      currentConfig = configuration;
      keyStorePIN   = newPIN;
      keyStoreFile  = newKeyStoreFile;
      keyStoreType  = newKeyStoreType;
    }
 
    return ccr;
  }
}