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

matthew_swift
03.26.2009 e10a19e91d09aa4bf4dd1fabf048b46299899e35
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
/*
 * 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-2009 Sun Microsystems, Inc.
 *      Portions Copyright 2009 Parametric Technology Corporation (PTC)
 */
 
package org.opends.sdk.tools;
 
 
 
import java.io.File;
import java.io.FileInputStream;
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.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.Date;
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 org.opends.sdk.DN;
import org.opends.sdk.schema.Schema;
import org.opends.sdk.util.Validator;
 
 
 
/**
 * This class is in charge of checking whether the certificates that are
 * presented are trusted or not. This implementation tries to check also
 * that the subject DN of the certificate corresponds to the host passed
 * using the setHostName method. This implementation also checks to make
 * sure the certificate is in the validity period. The constructor tries
 * to use a default TrustManager from the system and if it cannot be
 * retrieved this class will only accept the certificates explicitly
 * accepted by the user (and specified by calling acceptCertificate).
 */
class TrustStoreTrustManager implements X509TrustManager
{
  static private final Logger LOG = Logger
      .getLogger(TrustStoreTrustManager.class.getName());
 
  private final X509TrustManager trustManager;
 
  private final KeyStore truststore;
 
  private final File truststoreFile;
 
  private final char[] truststorePassword;
 
  private final String hostname;
 
 
 
  /**
   * The default constructor.
   */
  TrustStoreTrustManager(String truststorePath,
      String truststorePassword, String hostname,
      boolean checkValidityDates) throws KeyStoreException,
      IOException, NoSuchAlgorithmException, CertificateException
  {
    Validator.ensureNotNull(truststorePath);
    this.truststoreFile = new File(truststorePath);
    if (truststorePassword != null)
    {
      this.truststorePassword = truststorePassword.toCharArray();
    }
    else
    {
      this.truststorePassword = null;
    }
    truststore = KeyStore.getInstance(KeyStore.getDefaultType());
 
    FileInputStream fos = new FileInputStream(truststoreFile);
    truststore.load(fos, this.truststorePassword);
    TrustManagerFactory tmf = TrustManagerFactory
        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
 
    tmf.init(truststore);
    X509TrustManager x509tm = null;
    for (TrustManager tm : tmf.getTrustManagers())
    {
      if (tm instanceof X509TrustManager)
      {
        x509tm = (X509TrustManager) tm;
        break;
      }
    }
    if (x509tm == null)
    {
      throw new NoSuchAlgorithmException();
    }
    this.trustManager = x509tm;
    this.hostname = hostname;
    // this.checkValidityDates = checkValidityDates;
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  public void checkClientTrusted(X509Certificate[] chain,
      String authType) throws CertificateException
  {
    verifyExpiration(chain);
    verifyHostName(chain);
    trustManager.checkClientTrusted(chain, authType);
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  public void checkServerTrusted(X509Certificate[] chain,
      String authType) throws CertificateException
  {
    verifyExpiration(chain);
    verifyHostName(chain);
    trustManager.checkClientTrusted(chain, authType);
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  public X509Certificate[] getAcceptedIssuers()
  {
    if (trustManager != null)
    {
      return trustManager.getAcceptedIssuers();
    }
    else
    {
      return new X509Certificate[0];
    }
  }
 
 
 
  private void verifyExpiration(X509Certificate[] chain)
      throws CertificateException
  {
    Date currentDate = new Date();
    for (X509Certificate c : chain)
    {
      try
      {
        c.checkValidity(currentDate);
      }
      catch (CertificateExpiredException cee)
      {
        LOG.log(Level.WARNING, "Refusing to trust security"
            + " certificate \"" + c.getSubjectDN().getName()
            + "\" because it" + " expired on "
            + String.valueOf(c.getNotAfter()));
 
        throw cee;
      }
      catch (CertificateNotYetValidException cnyve)
      {
        LOG.log(Level.WARNING, "Refusing to trust security"
            + " certificate \"" + c.getSubjectDN().getName()
            + "\" because it" + " is not valid until "
            + String.valueOf(c.getNotBefore()));
 
        throw cnyve;
      }
    }
  }
 
 
 
  /**
   * Verifies that the provided certificate chains subject DN
   * corresponds to the host name specified with the setHost method.
   *
   * @param chain
   *          the certificate chain to analyze.
   * @throws HostnameMismatchCertificateException
   *           if the subject DN of the certificate does not match with
   *           the host name specified with the method setHost.
   */
  private void verifyHostName(X509Certificate[] chain)
      throws HostnameMismatchCertificateException
  {
    if (hostname != null)
    {
      try
      {
        DN dn = DN.valueOf(
            chain[0].getSubjectX500Principal().getName(), Schema
                .getCoreSchema());
        String value = dn.iterator().next().iterator().next()
            .getAttributeValue().toString();
        if (!hostMatch(value, hostname))
        {
          throw new HostnameMismatchCertificateException(
              "Hostname mismatch between host name " + hostname
                  + " and subject DN: "
                  + chain[0].getSubjectX500Principal(), hostname,
              chain[0].getSubjectX500Principal().getName());
        }
      }
      catch (Throwable t)
      {
        LOG.log(Level.WARNING, "Error parsing subject dn: "
            + chain[0].getSubjectX500Principal(), t);
      }
    }
  }
 
 
 
  /**
   * Checks whether two host names match. It accepts the use of wildcard
   * in the host name.
   *
   * @param host1
   *          the first host name.
   * @param host2
   *          the second host name.
   * @return <CODE>true</CODE> if the host match and <CODE>false</CODE>
   *         otherwise.
   */
  private boolean hostMatch(String host1, String host2)
  {
    if (host1 == null)
    {
      throw new IllegalArgumentException(
          "The host1 parameter cannot be null");
    }
    if (host2 == null)
    {
      throw new IllegalArgumentException(
          "The host2 parameter cannot be null");
    }
    String[] h1 = host1.split("\\.");
    String[] h2 = host2.split("\\.");
 
    boolean hostMatch = h1.length == h2.length;
    for (int i = 0; i < h1.length && hostMatch; i++)
    {
      if (!h1[i].equals("*") && !h2[i].equals("*"))
      {
        hostMatch = h1[i].equalsIgnoreCase(h2[i]);
      }
    }
    return hostMatch;
  }
}