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

Matthew Swift
30.42.2012 7934d276c1dfdc3224c391c23f574d244c5b0a10
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
/*
 * 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 2010 Sun Microsystems, Inc.
 *      Portions copyright 2012 ForgeRock AS.
 */
 
package org.forgerock.opendj.ldap;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
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.forgerock.opendj.ldap.schema.Schema;
 
import com.forgerock.opendj.util.Validator;
 
/**
 * This class contains methods for creating common types of trust manager.
 */
public final class TrustManagers {
 
    /**
     * An X509TrustManager which rejects certificate chains whose subject DN
     * does not match a specified host name.
     */
    private static final class CheckHostName implements X509TrustManager {
 
        private final X509TrustManager trustManager;
 
        private final String hostNamePattern;
 
        private CheckHostName(final X509TrustManager trustManager, final String hostNamePattern) {
            this.trustManager = trustManager;
            this.hostNamePattern = hostNamePattern;
        }
 
        /**
         * {@inheritDoc}
         */
        public void checkClientTrusted(final X509Certificate[] chain, final String authType)
                throws CertificateException {
            verifyHostName(chain);
            trustManager.checkClientTrusted(chain, authType);
        }
 
        /**
         * {@inheritDoc}
         */
        public void checkServerTrusted(final X509Certificate[] chain, final String authType)
                throws CertificateException {
            verifyHostName(chain);
            trustManager.checkServerTrusted(chain, authType);
        }
 
        /**
         * {@inheritDoc}
         */
        public X509Certificate[] getAcceptedIssuers() {
            return trustManager.getAcceptedIssuers();
        }
 
        /**
         * Checks whether a host name matches the provided pattern. It accepts
         * the use of wildcards in the pattern, e.g. {@code *.example.com}.
         *
         * @param hostName
         *            The host name.
         * @param pattern
         *            The host name pattern, which may contain wild cards.
         * @return {@code true} if the host name matched the pattern, otherwise
         *         {@code false}.
         */
        private boolean hostNameMatchesPattern(final String hostName, final String pattern) {
            final String[] nameElements = hostName.split("\\.");
            final String[] patternElements = pattern.split("\\.");
 
            boolean hostMatch = nameElements.length == patternElements.length;
            for (int i = 0; i < nameElements.length && hostMatch; i++) {
                final String ne = nameElements[i];
                final String pe = patternElements[i];
                if (!pe.equals("*")) {
                    hostMatch = ne.equalsIgnoreCase(pe);
                }
            }
            return hostMatch;
        }
 
        private void verifyHostName(final X509Certificate[] chain) throws CertificateException {
            try {
                // TODO: NPE if root DN.
                final DN dn =
                        DN.valueOf(chain[0].getSubjectX500Principal().getName(), Schema
                                .getCoreSchema());
                final String value =
                        dn.iterator().next().iterator().next().getAttributeValue().toString();
                if (!hostNameMatchesPattern(value, hostNamePattern)) {
                    throw new CertificateException(
                            "The host name contained in the certificate chain subject DN \'"
                                    + chain[0].getSubjectX500Principal()
                                    + "' does not match the host name \'" + hostNamePattern + "'");
                }
            } catch (final Throwable t) {
                LOG.log(Level.WARNING, "Error parsing subject dn: "
                        + chain[0].getSubjectX500Principal(), t);
            }
        }
    }
 
    /**
     * An X509TrustManager which rejects certificates which have expired or are
     * not yet valid.
     */
    private static final class CheckValidatyDates implements X509TrustManager {
 
        private final X509TrustManager trustManager;
 
        private CheckValidatyDates(final X509TrustManager trustManager) {
            this.trustManager = trustManager;
        }
 
        /**
         * {@inheritDoc}
         */
        public void checkClientTrusted(final X509Certificate[] chain, final String authType)
                throws CertificateException {
            verifyExpiration(chain);
            trustManager.checkClientTrusted(chain, authType);
        }
 
        /**
         * {@inheritDoc}
         */
        public void checkServerTrusted(final X509Certificate[] chain, final String authType)
                throws CertificateException {
            verifyExpiration(chain);
            trustManager.checkServerTrusted(chain, authType);
        }
 
        /**
         * {@inheritDoc}
         */
        public X509Certificate[] getAcceptedIssuers() {
            return trustManager.getAcceptedIssuers();
        }
 
        private void verifyExpiration(final X509Certificate[] chain) throws CertificateException {
            final Date currentDate = new Date();
            for (final X509Certificate c : chain) {
                try {
                    c.checkValidity(currentDate);
                } catch (final CertificateExpiredException e) {
                    LOG.log(Level.WARNING, "Refusing to trust security" + " certificate \""
                            + c.getSubjectDN().getName() + "\" because it" + " expired on "
                            + String.valueOf(c.getNotAfter()));
 
                    throw e;
                } catch (final CertificateNotYetValidException e) {
                    LOG.log(Level.WARNING, "Refusing to trust security" + " certificate \""
                            + c.getSubjectDN().getName() + "\" because it" + " is not valid until "
                            + String.valueOf(c.getNotBefore()));
 
                    throw e;
                }
            }
        }
    }
 
    /**
     * An X509TrustManager which does not trust any certificates.
     */
    private static final class DistrustAll implements X509TrustManager {
        // Single instance.
        private static final DistrustAll INSTANCE = new DistrustAll();
 
        // Prevent instantiation.
        private DistrustAll() {
            // Nothing to do.
        }
 
        /**
         * {@inheritDoc}
         */
        public void checkClientTrusted(final X509Certificate[] chain, final String authType)
                throws CertificateException {
            throw new CertificateException();
        }
 
        /**
         * {@inheritDoc}
         */
        public void checkServerTrusted(final X509Certificate[] chain, final String authType)
                throws CertificateException {
            throw new CertificateException();
        }
 
        /**
         * {@inheritDoc}
         */
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }
 
    /**
     * An X509TrustManager which trusts all certificates.
     */
    private static final class TrustAll implements X509TrustManager {
 
        // Single instance.
        private static final TrustAll INSTANCE = new TrustAll();
 
        // Prevent instantiation.
        private TrustAll() {
            // Nothing to do.
        }
 
        /**
         * {@inheritDoc}
         */
        public void checkClientTrusted(final X509Certificate[] chain, final String authType)
                throws CertificateException {
        }
 
        /**
         * {@inheritDoc}
         */
        public void checkServerTrusted(final X509Certificate[] chain, final String authType)
                throws CertificateException {
        }
 
        /**
         * {@inheritDoc}
         */
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }
 
    private static final Logger LOG = Logger.getLogger(TrustManagers.class.getName());
 
    /**
     * Wraps the provided {@code X509TrustManager} by adding additional
     * validation which rejects certificate chains whose subject DN does not
     * match the specified host name pattern. The pattern may contain
     * wild-cards, for example {@code *.example.com}.
     *
     * @param hostNamePattern
     *            A host name pattern which the RDN value contained in
     *            certificate subject DNs must match.
     * @param trustManager
     *            The trust manager to be wrapped.
     * @return The wrapped trust manager.
     * @throws NullPointerException
     *             If {@code trustManager} or {@code hostNamePattern} was
     *             {@code null}.
     */
    public static X509TrustManager checkHostName(final String hostNamePattern,
            final X509TrustManager trustManager) {
        Validator.ensureNotNull(trustManager, hostNamePattern);
        return new CheckHostName(trustManager, hostNamePattern);
    }
 
    /**
     * Creates a new {@code X509TrustManager} which will use the named trust
     * store file to determine whether to trust a certificate. It will use the
     * default trust store format for the JVM (e.g. {@code JKS}) and will not
     * use a password to open the trust store.
     *
     * @param file
     *            The trust store file name.
     * @return A new {@code X509TrustManager} which will use the named trust
     *         store file to determine whether to trust a certificate.
     * @throws GeneralSecurityException
     *             If the trust store could not be loaded, perhaps due to
     *             incorrect format, or missing algorithms.
     * @throws IOException
     *             If the trust store file could not be found or could not be
     *             read.
     * @throws NullPointerException
     *             If {@code file} was {@code null}.
     */
    public static X509TrustManager checkUsingTrustStore(final String file)
            throws GeneralSecurityException, IOException {
        return checkUsingTrustStore(file, null, null);
    }
 
    /**
     * Creates a new {@code X509TrustManager} which will use the named trust
     * store file to determine whether to trust a certificate. It will use the
     * provided trust store format and password.
     *
     * @param file
     *            The trust store file name.
     * @param password
     *            The trust store password, which may be {@code null}.
     * @param format
     *            The trust store format, which may be {@code null} to indicate
     *            that the default trust store format for the JVM (e.g.
     *            {@code JKS}) should be used.
     * @return A new {@code X509TrustManager} which will use the named trust
     *         store file to determine whether to trust a certificate.
     * @throws GeneralSecurityException
     *             If the trust store could not be loaded, perhaps due to
     *             incorrect format, or missing algorithms.
     * @throws IOException
     *             If the trust store file could not be found or could not be
     *             read.
     * @throws NullPointerException
     *             If {@code file} was {@code null}.
     */
    public static X509TrustManager checkUsingTrustStore(final String file, final char[] password,
            final String format) throws GeneralSecurityException, IOException {
        Validator.ensureNotNull(file);
 
        final File trustStoreFile = new File(file);
        final String trustStoreFormat = format != null ? format : KeyStore.getDefaultType();
 
        final KeyStore keyStore = KeyStore.getInstance(trustStoreFormat);
 
        FileInputStream fos = null;
        try {
            fos = new FileInputStream(trustStoreFile);
            keyStore.load(fos, password);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (final IOException ignored) {
                    // Ignore.
                }
            }
        }
 
        final TrustManagerFactory tmf =
                TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);
 
        X509TrustManager x509tm = null;
        for (final TrustManager tm : tmf.getTrustManagers()) {
            if (tm instanceof X509TrustManager) {
                x509tm = (X509TrustManager) tm;
                break;
            }
        }
 
        if (x509tm == null) {
            throw new NoSuchAlgorithmException();
        }
 
        return x509tm;
    }
 
    /**
     * Wraps the provided {@code X509TrustManager} by adding additional
     * validation which rejects certificate chains containing certificates which
     * have expired or are not yet valid.
     *
     * @param trustManager
     *            The trust manager to be wrapped.
     * @return The wrapped trust manager.
     * @throws NullPointerException
     *             If {@code trustManager} was {@code null}.
     */
    public static X509TrustManager checkValidityDates(final X509TrustManager trustManager) {
        Validator.ensureNotNull(trustManager);
        return new CheckValidatyDates(trustManager);
    }
 
    /**
     * Returns an {@code X509TrustManager} which does not trust any
     * certificates.
     *
     * @return An {@code X509TrustManager} which does not trust any
     *         certificates.
     */
    public static X509TrustManager distrustAll() {
        return DistrustAll.INSTANCE;
    }
 
    /**
     * Returns an {@code X509TrustManager} which trusts all certificates.
     *
     * @return An {@code X509TrustManager} which trusts all certificates.
     */
    public static X509TrustManager trustAll() {
        return TrustAll.INSTANCE;
    }
 
    // Prevent insantiation.
    private TrustManagers() {
        // Nothing to do.
    }
 
}