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

matthew_swift
07.38.2009 b69e03bcf756fdeba95b86454445424237d2aefd
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
/*
 * 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
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE
 * or https://OpenDS.dev.java.net/OpenDS.LICENSE.
 * 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
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE.  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 Sun Microsystems, Inc.
 */
 
package com.sun.opends.sdk.tools;
 
 
 
import static com.sun.opends.sdk.messages.Messages.*;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
 
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
 
import com.sun.opends.sdk.util.Message;
import com.sun.opends.sdk.util.MessageBuilder;
import com.sun.opends.sdk.util.Validator;
 
 
 
/**
 * A trust manager which prompts the user for the length of time that
 * they would like to trust a server certificate.
 */
final class PromptingTrustManager implements X509TrustManager
{
  static private final Logger LOG = Logger
      .getLogger(PromptingTrustManager.class.getName());
 
  static private final String DEFAULT_PATH = System
      .getProperty("user.home")
      + File.separator + ".opends" + File.separator + "keystore";
 
  static private final char[] DEFAULT_PASSWORD = "OpenDS".toCharArray();
 
 
 
  /**
   * Enumeration description server certificate trust option.
   */
  private static enum TrustOption
  {
    UNTRUSTED(1, INFO_LDAP_CONN_PROMPT_SECURITY_TRUST_OPTION_NO.get()), SESSION(
        2, INFO_LDAP_CONN_PROMPT_SECURITY_TRUST_OPTION_SESSION.get()), PERMANENT(
        3, INFO_LDAP_CONN_PROMPT_SECURITY_TRUST_OPTION_ALWAYS.get()), CERTIFICATE_DETAILS(
        4, INFO_LDAP_CONN_PROMPT_SECURITY_CERTIFICATE_DETAILS.get());
 
    private Integer choice;
 
    private Message msg;
 
 
 
    /**
     * Private constructor.
     *
     * @param i
     *          the menu return value.
     * @param msg
     *          the message message.
     */
    private TrustOption(int i, Message msg)
    {
      choice = i;
      this.msg = msg;
    }
 
 
 
    /**
     * Returns the choice number.
     *
     * @return the attribute name.
     */
    Integer getChoice()
    {
      return choice;
    }
 
 
 
    /**
     * Return the menu message.
     *
     * @return the menu message.
     */
    Message getMenuMessage()
    {
      return msg;
    }
  }
 
 
 
  private final KeyStore inMemoryTrustStore;
 
  private final KeyStore onDiskTrustStore;
 
  private final X509TrustManager inMemoryTrustManager;
 
  private final X509TrustManager onDiskTrustManager;
 
  private final X509TrustManager nestedTrustManager;
 
  private final ConsoleApplication app;
 
 
 
  PromptingTrustManager(ConsoleApplication app,
      X509TrustManager sourceTrustManager) throws KeyStoreException,
      IOException, NoSuchAlgorithmException, CertificateException
  {
    this(app, DEFAULT_PATH, sourceTrustManager);
  }
 
 
 
  PromptingTrustManager(ConsoleApplication app,
      String acceptedStorePath, X509TrustManager sourceTrustManager)
      throws KeyStoreException, IOException, NoSuchAlgorithmException,
      CertificateException
  {
    Validator.ensureNotNull(app, acceptedStorePath);
    this.app = app;
    this.nestedTrustManager = sourceTrustManager;
    inMemoryTrustStore = KeyStore
        .getInstance(KeyStore.getDefaultType());
    onDiskTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
 
    File onDiskTrustStorePath = new File(acceptedStorePath);
    inMemoryTrustStore.load(null, null);
    if (!onDiskTrustStorePath.exists())
    {
      onDiskTrustStore.load(null, null);
    }
    else
    {
      FileInputStream fos = new FileInputStream(onDiskTrustStorePath);
      onDiskTrustStore.load(fos, DEFAULT_PASSWORD);
    }
    TrustManagerFactory tmf = TrustManagerFactory
        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
 
    tmf.init(inMemoryTrustStore);
    X509TrustManager x509tm = null;
    for (TrustManager tm : tmf.getTrustManagers())
    {
      if (tm instanceof X509TrustManager)
      {
        x509tm = (X509TrustManager) tm;
        break;
      }
    }
    if (x509tm == null)
    {
      throw new NoSuchAlgorithmException();
    }
    this.inMemoryTrustManager = x509tm;
 
    tmf.init(onDiskTrustStore);
    x509tm = null;
    for (TrustManager tm : tmf.getTrustManagers())
    {
      if (tm instanceof X509TrustManager)
      {
        x509tm = (X509TrustManager) tm;
        break;
      }
    }
    if (x509tm == null)
    {
      throw new NoSuchAlgorithmException();
    }
    this.onDiskTrustManager = x509tm;
  }
 
 
 
  public void checkClientTrusted(X509Certificate[] x509Certificates,
      String s) throws CertificateException
  {
    try
    {
      inMemoryTrustManager.checkClientTrusted(x509Certificates, s);
    }
    catch (Exception ce1)
    {
      try
      {
        onDiskTrustManager.checkClientTrusted(x509Certificates, s);
      }
      catch (Exception ce2)
      {
        if (nestedTrustManager != null)
        {
          try
          {
            nestedTrustManager.checkClientTrusted(x509Certificates, s);
          }
          catch (Exception ce3)
          {
            checkManuallyTrusted(x509Certificates, ce3);
          }
        }
        else
        {
          checkManuallyTrusted(x509Certificates, ce1);
        }
      }
    }
  }
 
 
 
  public void checkServerTrusted(X509Certificate[] x509Certificates,
      String s) throws CertificateException
  {
    try
    {
      inMemoryTrustManager.checkServerTrusted(x509Certificates, s);
    }
    catch (Exception ce1)
    {
      try
      {
        onDiskTrustManager.checkServerTrusted(x509Certificates, s);
      }
      catch (Exception ce2)
      {
        if (nestedTrustManager != null)
        {
          try
          {
            nestedTrustManager.checkServerTrusted(x509Certificates, s);
          }
          catch (Exception ce3)
          {
            checkManuallyTrusted(x509Certificates, ce3);
          }
        }
        else
        {
          checkManuallyTrusted(x509Certificates, ce1);
        }
      }
    }
  }
 
 
 
  public X509Certificate[] getAcceptedIssuers()
  {
    if (nestedTrustManager != null)
    {
      return nestedTrustManager.getAcceptedIssuers();
    }
    return new X509Certificate[0];
  }
 
 
 
  /**
   * Indicate if the certificate chain can be trusted.
   *
   * @param chain
   *          The certificate chain to validate certificate.
   */
  private void checkManuallyTrusted(X509Certificate[] chain,
      Exception exception) throws CertificateException
  {
    app.println();
    app
        .println(INFO_LDAP_CONN_PROMPT_SECURITY_SERVER_CERTIFICATE
            .get());
    app.println();
    for (int i = 0; i < chain.length; i++)
    {
      // Certificate DN
      app.println(INFO_LDAP_CONN_SECURITY_SERVER_CERTIFICATE_USER_DN
          .get(chain[i].getSubjectDN().toString()));
 
      // certificate validity
      app.println(INFO_LDAP_CONN_SECURITY_SERVER_CERTIFICATE_VALIDITY
          .get(chain[i].getNotBefore().toString(), chain[i]
              .getNotAfter().toString()));
 
      // certificate Issuer
      app.println(INFO_LDAP_CONN_SECURITY_SERVER_CERTIFICATE_ISSUER
          .get(chain[i].getIssuerDN().toString()));
 
      app.println();
      app.println();
    }
 
    app.println();
    app.println(INFO_LDAP_CONN_PROMPT_SECURITY_TRUST_OPTION.get());
    app.println();
 
    Map<String, TrustOption> menuOptions = new HashMap<String, TrustOption>();
    for (TrustOption t : TrustOption.values())
    {
      menuOptions.put(t.getChoice().toString(), t);
 
      MessageBuilder builder = new MessageBuilder();
      builder.append(t.getChoice());
      builder.append(") ");
      builder.append(t.getMenuMessage());
      app.println(builder.toMessage(), 2 /* Indent options */);
    }
 
    TrustOption defaultTrustMethod = TrustOption.SESSION;
    Message promptMsg = INFO_MENU_PROMPT_SINGLE_DEFAULT
        .get(defaultTrustMethod.getChoice().toString());
 
    while (true)
    {
      app.println();
      String choice;
      try
      {
        choice = app.readInput(promptMsg, defaultTrustMethod
            .getChoice().toString());
      }
      catch (CLIException e)
      {
        // What can we do here?
        throw new CertificateException(exception);
      }
      finally
      {
        app.println();
      }
 
      TrustOption option = menuOptions.get(choice.trim());
      if (option == null)
      {
        app.println(ERR_MENU_BAD_CHOICE_SINGLE.get());
        app.println();
        continue;
      }
 
      switch (option)
      {
      case UNTRUSTED:
        if (exception instanceof CertificateException)
        {
          throw (CertificateException) exception;
        }
        else
        {
          throw new CertificateException(exception);
        }
      case CERTIFICATE_DETAILS:
        for (X509Certificate aChain : chain)
        {
          app.println();
          app.println(INFO_LDAP_CONN_SECURITY_SERVER_CERTIFICATE
              .get(aChain.toString()));
          app.println();
        }
        break;
      default: // SESSION / PERMANENT.
        // Update the trust manager with the new certificate
        acceptCertificate(chain, option == TrustOption.PERMANENT);
        return;
      }
    }
  }
 
 
 
  /**
   * This method is called when the user accepted a certificate.
   *
   * @param chain
   *          the certificate chain accepted by the user. certificate.
   */
  void acceptCertificate(X509Certificate[] chain, boolean permanent)
  {
    if (permanent)
    {
      LOG.log(Level.INFO, "Permanently accepting certificate chain to "
          + "truststore");
    }
    else
    {
      LOG.log(Level.INFO,
          "Accepting certificate chain for this session");
    }
 
    for (X509Certificate aChain : chain)
    {
      try
      {
        String alias = aChain.getSubjectDN().getName();
        inMemoryTrustStore.setCertificateEntry(alias, aChain);
        if (permanent)
        {
          onDiskTrustStore.setCertificateEntry(alias, aChain);
        }
      }
      catch (Exception e)
      {
        LOG.log(Level.WARNING, "Error setting certificate to store: "
            + e + "\nCert: " + aChain.toString());
      }
    }
 
    if (permanent)
    {
      try
      {
        File truststoreFile = new File(DEFAULT_PATH);
        if (!truststoreFile.exists())
        {
          createFile(truststoreFile);
        }
        FileOutputStream fos = new FileOutputStream(truststoreFile);
        onDiskTrustStore.store(fos, DEFAULT_PASSWORD);
        fos.close();
      }
      catch (Exception e)
      {
        LOG.log(Level.WARNING, "Error saving store to disk: " + e);
      }
    }
  }
 
 
 
  private boolean createFile(File f) throws IOException
  {
    boolean success = false;
    if (f != null)
    {
      File parent = f.getParentFile();
      if (!parent.exists())
      {
        parent.mkdirs();
      }
      success = f.createNewFile();
    }
    return success;
  }
}