blob: c51215f3049f8854d1a9d533c866f1d7002cd1e8 [file] [log] [blame]
J. Duke319a3b92007-12-01 00:00:00 +00001/*
2 * Copyright 2002-2006 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
25
26package sun.security.validator;
27
28import java.io.IOException;
29import java.util.*;
30
31import java.security.*;
32import java.security.cert.*;
33
34import javax.security.auth.x500.X500Principal;
35
36import sun.security.x509.X509CertImpl;
37import sun.security.x509.NetscapeCertTypeExtension;
38import sun.security.util.DerValue;
39import sun.security.util.DerInputStream;
40import sun.security.util.DerOutputStream;
41import sun.security.util.ObjectIdentifier;
42
43/**
44 * A simple validator implementation. It is based on code from the JSSE
45 * X509TrustManagerImpl. This implementation is designed for compatibility with
46 * deployed certificates and previous J2SE versions. It will never support
47 * more advanced features and will be deemphasized in favor of the PKIX
48 * validator going forward.
49 *
50 * @author Andreas Sterbenz
51 */
52public final class SimpleValidator extends Validator {
53
54 // Constants for the OIDs we need
55
56 final static String OID_BASIC_CONSTRAINTS = "2.5.29.19";
57
58 final static String OID_NETSCAPE_CERT_TYPE = "2.16.840.1.113730.1.1";
59
60 final static String OID_KEY_USAGE = "2.5.29.15";
61
62 final static String OID_EXTENDED_KEY_USAGE = "2.5.29.37";
63
64 final static String OID_EKU_ANY_USAGE = "2.5.29.37.0";
65
66 final static ObjectIdentifier OBJID_NETSCAPE_CERT_TYPE =
67 NetscapeCertTypeExtension.NetscapeCertType_Id;
68
69 private final static String NSCT_SSL_CA =
70 NetscapeCertTypeExtension.SSL_CA;
71
72 private final static String NSCT_CODE_SIGNING_CA =
73 NetscapeCertTypeExtension.OBJECT_SIGNING_CA;
74
75 /**
76 * The trusted certificates as:
77 * Map (X500Principal)subject of trusted cert -> List of X509Certificate
78 * The list is used because there may be multiple certificates
79 * with an identical subject DN.
80 */
81 private Map<X500Principal, List<X509Certificate>> trustedX500Principals;
82
83 /**
84 * Set of the trusted certificates. Present only for
85 * getTrustedCertificates().
86 */
87 private Collection<X509Certificate> trustedCerts;
88
89 SimpleValidator(String variant, Collection<X509Certificate> trustedCerts) {
90 super(TYPE_SIMPLE, variant);
91 this.trustedCerts = trustedCerts;
92 trustedX500Principals =
93 new HashMap<X500Principal, List<X509Certificate>>();
94 for (X509Certificate cert : trustedCerts) {
95 X500Principal principal = cert.getSubjectX500Principal();
96 List<X509Certificate> list = trustedX500Principals.get(principal);
97 if (list == null) {
98 // this actually should be a set, but duplicate entries
99 // are not a problem and we can avoid the Set overhead
100 list = new ArrayList<X509Certificate>(2);
101 trustedX500Principals.put(principal, list);
102 }
103 list.add(cert);
104 }
105 }
106
107 public Collection<X509Certificate> getTrustedCertificates() {
108 return trustedCerts;
109 }
110
111 /**
112 * Perform simple validation of chain. The arguments otherCerts and
113 * parameter are ignored.
114 */
115 X509Certificate[] engineValidate(X509Certificate[] chain,
116 Collection<X509Certificate> otherCerts, Object parameter)
117 throws CertificateException {
118 if ((chain == null) || (chain.length == 0)) {
119 throw new CertificateException
120 ("null or zero-length certificate chain");
121 }
122
123 // make sure chain includes a trusted cert
124 chain = buildTrustedChain(chain);
125
126 Date date = validationDate;
127 if (date == null) {
128 date = new Date();
129 }
130 // verify top down, starting at the certificate issued by
131 // the trust anchor
132 for (int i = chain.length - 2; i >= 0; i--) {
133 X509Certificate issuerCert = chain[i + 1];
134 X509Certificate cert = chain[i];
135
136
137 // no validity check for code signing certs
138 if ((variant.equals(VAR_CODE_SIGNING) == false)
139 && (variant.equals(VAR_JCE_SIGNING) == false)) {
140 cert.checkValidity(date);
141 }
142
143 // check name chaining
144 if (cert.getIssuerX500Principal().equals(
145 issuerCert.getSubjectX500Principal()) == false) {
146 throw new ValidatorException
147 (ValidatorException.T_NAME_CHAINING, cert);
148 }
149
150 // check signature
151 try {
152 cert.verify(issuerCert.getPublicKey());
153 } catch (GeneralSecurityException e) {
154 throw new ValidatorException
155 (ValidatorException.T_SIGNATURE_ERROR, cert, e);
156 }
157
158 // check extensions for CA certs
159 if (i != 0) {
160 checkExtensions(cert, i);
161 }
162 }
163
164 return chain;
165 }
166
167 private void checkExtensions(X509Certificate cert, int index)
168 throws CertificateException {
169 Set<String> critSet = cert.getCriticalExtensionOIDs();
170 if (critSet == null) {
171 critSet = Collections.<String>emptySet();
172 }
173
174 // Check the basic constraints extension
175 checkBasicConstraints(cert, critSet, index);
176
177 // Check the key usage and extended key usage extensions
178 checkKeyUsage(cert, critSet);
179
180 // check Netscape certificate type extension
181 checkNetscapeCertType(cert, critSet);
182
183 if (!critSet.isEmpty()) {
184 throw new ValidatorException
185 ("Certificate contains unknown critical extensions: " + critSet,
186 ValidatorException.T_CA_EXTENSIONS, cert);
187 }
188 }
189
190 private void checkNetscapeCertType(X509Certificate cert,
191 Set<String> critSet) throws CertificateException {
192 if (variant.equals(VAR_GENERIC)) {
193 // nothing
194 } else if (variant.equals(VAR_TLS_CLIENT)
195 || variant.equals(VAR_TLS_SERVER)) {
196 if (getNetscapeCertTypeBit(cert, NSCT_SSL_CA) == false) {
197 throw new ValidatorException
198 ("Invalid Netscape CertType extension for SSL CA "
199 + "certificate",
200 ValidatorException.T_CA_EXTENSIONS, cert);
201 }
202 critSet.remove(OID_NETSCAPE_CERT_TYPE);
203 } else if (variant.equals(VAR_CODE_SIGNING)
204 || variant.equals(VAR_JCE_SIGNING)) {
205 if (getNetscapeCertTypeBit(cert, NSCT_CODE_SIGNING_CA) == false) {
206 throw new ValidatorException
207 ("Invalid Netscape CertType extension for code "
208 + "signing CA certificate",
209 ValidatorException.T_CA_EXTENSIONS, cert);
210 }
211 critSet.remove(OID_NETSCAPE_CERT_TYPE);
212 } else {
213 throw new CertificateException("Unknown variant " + variant);
214 }
215 }
216
217 /**
218 * Get the value of the specified bit in the Netscape certificate type
219 * extension. If the extension is not present at all, we return true.
220 */
221 static boolean getNetscapeCertTypeBit(X509Certificate cert, String type) {
222 try {
223 NetscapeCertTypeExtension ext;
224 if (cert instanceof X509CertImpl) {
225 X509CertImpl certImpl = (X509CertImpl)cert;
226 ObjectIdentifier oid = OBJID_NETSCAPE_CERT_TYPE;
227 ext = (NetscapeCertTypeExtension)certImpl.getExtension(oid);
228 if (ext == null) {
229 return true;
230 }
231 } else {
232 byte[] extVal = cert.getExtensionValue(OID_NETSCAPE_CERT_TYPE);
233 if (extVal == null) {
234 return true;
235 }
236 DerInputStream in = new DerInputStream(extVal);
237 byte[] encoded = in.getOctetString();
238 encoded = new DerValue(encoded).getUnalignedBitString()
239 .toByteArray();
240 ext = new NetscapeCertTypeExtension(encoded);
241 }
242 Boolean val = (Boolean)ext.get(type);
243 return val.booleanValue();
244 } catch (IOException e) {
245 return false;
246 }
247 }
248
249 private void checkBasicConstraints(X509Certificate cert,
250 Set<String> critSet, int index) throws CertificateException {
251
252 critSet.remove(OID_BASIC_CONSTRAINTS);
253 int constraints = cert.getBasicConstraints();
254 // reject, if extension missing or not a CA (constraints == -1)
255 if (constraints < 0) {
256 throw new ValidatorException("End user tried to act as a CA",
257 ValidatorException.T_CA_EXTENSIONS, cert);
258 }
259 if (index - 1 > constraints) {
260 throw new ValidatorException("Violated path length constraints",
261 ValidatorException.T_CA_EXTENSIONS, cert);
262 }
263 }
264
265 /*
266 * Verify the key usage and extended key usage for intermediate
267 * certificates.
268 */
269 private void checkKeyUsage(X509Certificate cert, Set<String> critSet)
270 throws CertificateException {
271
272 critSet.remove(OID_KEY_USAGE);
273 // EKU irrelevant in CA certificates
274 critSet.remove(OID_EXTENDED_KEY_USAGE);
275
276 // check key usage extension
277 boolean[] keyUsageInfo = cert.getKeyUsage();
278 if (keyUsageInfo != null) {
279 // keyUsageInfo[5] is for keyCertSign.
280 if ((keyUsageInfo.length < 6) || (keyUsageInfo[5] == false)) {
281 throw new ValidatorException
282 ("Wrong key usage: expected keyCertSign",
283 ValidatorException.T_CA_EXTENSIONS, cert);
284 }
285 }
286 }
287
288 /**
289 * Build a trusted certificate chain. This method always returns a chain
290 * with a trust anchor as the final cert in the chain. If no trust anchor
291 * could be found, a CertificateException is thrown.
292 */
293 private X509Certificate[] buildTrustedChain(X509Certificate[] chain)
294 throws CertificateException {
295 List<X509Certificate> c = new ArrayList<X509Certificate>(chain.length);
296 // scan chain starting at EE cert
297 // if a trusted certificate is found, append it and return
298 for (int i = 0; i < chain.length; i++) {
299 X509Certificate cert = chain[i];
300 X509Certificate trustedCert = getTrustedCertificate(cert);
301 if (trustedCert != null) {
302 c.add(trustedCert);
303 return c.toArray(CHAIN0);
304 }
305 c.add(cert);
306 }
307 // check if we can append a trusted cert
308 X509Certificate cert = chain[chain.length - 1];
309 X500Principal subject = cert.getSubjectX500Principal();
310 X500Principal issuer = cert.getIssuerX500Principal();
311 if (subject.equals(issuer) == false) {
312 List<X509Certificate> list = trustedX500Principals.get(issuer);
313 if (list != null) {
314 X509Certificate trustedCert = list.iterator().next();
315 c.add(trustedCert);
316 return c.toArray(CHAIN0);
317 }
318 }
319 // no trusted cert found, error
320 throw new ValidatorException(ValidatorException.T_NO_TRUST_ANCHOR);
321 }
322
323 /**
324 * Return a trusted certificate that matches the input certificate,
325 * or null if no such certificate can be found. This method also handles
326 * cases where a CA re-issues a trust anchor with the same public key and
327 * same subject and issuer names but a new validity period, etc.
328 */
329 private X509Certificate getTrustedCertificate(X509Certificate cert) {
330 Principal certSubjectName = cert.getSubjectX500Principal();
331 List<X509Certificate> list = trustedX500Principals.get(certSubjectName);
332 if (list == null) {
333 return null;
334 }
335
336 Principal certIssuerName = cert.getIssuerX500Principal();
337 PublicKey certPublicKey = cert.getPublicKey();
338
339 for (X509Certificate mycert : list) {
340 if (mycert.equals(cert)) {
341 return cert;
342 }
343 if (!mycert.getIssuerX500Principal().equals(certIssuerName)) {
344 continue;
345 }
346 if (!mycert.getPublicKey().equals(certPublicKey)) {
347 continue;
348 }
349
350 // All tests pass, this must be the one to use...
351 return mycert;
352 }
353 return null;
354 }
355
356}