History

My first initial commit with all of mine experimental changes.

Dmitry Kabak (userdima committed 13 years ago

Commit d37b88d1 parent 3f5b46618352 files · +2598093 −-8690Browse files

Showing the changes to java/pkg/sun/security/provider/certpath/Builder.java (1 of 18352 files). Show all

Unified · Split

java/pkg/sun/security/provider/certpath/Builder.java+485−0
@@ -0,0 +1,485 @@
1+/*
2+ * Copyright (c) 2000, 2009, Oracle and/or its affiliates. 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. Oracle designates this
8+ * particular file as subject to the "Classpath" exception as provided
9+ * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22+ * or visit www.oracle.com if you need additional information or have any
23+ * questions.
24+ */
25+
26+package sun.security.provider.certpath;
27+
28+import java.io.IOException;
29+import java.security.AccessController;
30+import java.security.GeneralSecurityException;
31+import java.security.cert.*;
32+import java.util.*;
33+
34+import javax.security.auth.x500.X500Principal;
35+
36+import sun.security.action.GetBooleanAction;
37+import sun.security.util.Debug;
38+import sun.security.x509.GeneralNames;
39+import sun.security.x509.GeneralNameInterface;
40+import sun.security.x509.GeneralSubtrees;
41+import sun.security.x509.NameConstraintsExtension;
42+import sun.security.x509.SubjectAlternativeNameExtension;
43+import sun.security.x509.X500Name;
44+import sun.security.x509.X509CertImpl;
45+
46+/**
47+ * Abstract class representing a builder, which is able to retrieve
48+ * matching certificates and is able to verify a particular certificate.
49+ *
50+ * @since 1.4
51+ * @author Sean Mullan
52+ * @author Yassir Elley
53+ */
54+
55+public abstract class Builder {
56+
57+ private static final Debug debug = Debug.getInstance("certpath");
58+ private Set<String> matchingPolicies;
59+ final PKIXBuilderParameters buildParams;
60+ final X500Principal targetSubjectDN;
61+ final Date date;
62+ final X509CertSelector targetCertConstraints;
63+
64+ /**
65+ * Flag indicating whether support for the caIssuers field of the
66+ * Authority Information Access extension shall be enabled. Currently
67+ * disabled by default for compatibility reasons.
68+ */
69+ final static boolean USE_AIA = AccessController.doPrivileged
70+ (new GetBooleanAction("com.sun.security.enableAIAcaIssuers"));
71+
72+ /**
73+ * Initialize the builder with the input parameters.
74+ *
75+ * @param params the parameter set used to build a certification path
76+ */
77+ Builder(PKIXBuilderParameters buildParams, X500Principal targetSubjectDN) {
78+ this.buildParams = buildParams;
79+ this.targetSubjectDN = targetSubjectDN;
80+ // Initialize date if not specified
81+ Date paramsDate = buildParams.getDate();
82+ this.date = paramsDate != null ? paramsDate : new Date();
83+ this.targetCertConstraints =
84+ (X509CertSelector) buildParams.getTargetCertConstraints();
85+ }
86+
87+ /**
88+ * Retrieves certificates from the list of certStores using the buildParams
89+ * and the currentState as a filter
90+ *
91+ * @param currentState the current State
92+ * @param certStores list of CertStores
93+ */
94+ abstract Collection<X509Certificate> getMatchingCerts
95+ (State currentState, List<CertStore> certStores)
96+ throws CertStoreException, CertificateException, IOException;
97+
98+ /**
99+ * Verifies the cert against the currentState, using the certPathList
100+ * generated thus far to help with loop detection
101+ *
102+ * @param cert the certificate to be verified
103+ * @param currentState the current state against which the cert is verified
104+ * @param certPathList the certPathList generated thus far
105+ */
106+ abstract void verifyCert(X509Certificate cert, State currentState,
107+ List<X509Certificate> certPathList) throws GeneralSecurityException;
108+
109+ /**
110+ * Verifies whether the input certificate completes the path.
111+ * When building forward, a trust anchor will complete the path.
112+ * When building reverse, the target certificate will complete the path.
113+ *
114+ * @param cert the certificate to test
115+ * @return a boolean value indicating whether the cert completes the path.
116+ */
117+ abstract boolean isPathCompleted(X509Certificate cert);
118+
119+ /**
120+ * Adds the certificate to the certPathList
121+ *
122+ * @param cert the certificate to be added
123+ * @param certPathList the certification path list
124+ */
125+ abstract void addCertToPath(X509Certificate cert,
126+ LinkedList<X509Certificate> certPathList);
127+
128+ /**
129+ * Removes final certificate from the certPathList
130+ *
131+ * @param certPathList the certification path list
132+ */
133+ abstract void removeFinalCertFromPath
134+ (LinkedList<X509Certificate> certPathList);
135+
136+ /**
137+ * get distance of one GeneralName from another
138+ *
139+ * @param base GeneralName at base of subtree
140+ * @param test GeneralName to be tested against base
141+ * @param incomparable the value to return if the names are
142+ * incomparable
143+ * @return distance of test name from base, where 0
144+ * means exact match, 1 means test is an immediate
145+ * child of base, 2 means test is a grandchild, etc.
146+ * -1 means test is a parent of base, -2 means test
147+ * is a grandparent, etc.
148+ */
149+ static int distance(GeneralNameInterface base,
150+ GeneralNameInterface test, int incomparable) {
151+ switch (base.constrains(test)) {
152+ case GeneralNameInterface.NAME_DIFF_TYPE:
153+ if (debug != null) {
154+ debug.println("Builder.distance(): Names are different types");
155+ }
156+ case GeneralNameInterface.NAME_SAME_TYPE:
157+ if (debug != null) {
158+ debug.println("Builder.distance(): Names are same type but " +
159+ "in different subtrees");
160+ }
161+ return incomparable;
162+ case GeneralNameInterface.NAME_MATCH:
163+ return 0;
164+ case GeneralNameInterface.NAME_WIDENS:
165+ break;
166+ case GeneralNameInterface.NAME_NARROWS:
167+ break;
168+ default: // should never occur
169+ return incomparable;
170+ }
171+
172+ /* names are in same subtree */
173+ return test.subtreeDepth() - base.subtreeDepth();
174+ }
175+
176+ /**
177+ * get hop distance of one GeneralName from another in links where
178+ * the names need not have an ancestor/descendant relationship.
179+ * For example, the hop distance from ou=D,ou=C,o=B,c=US to
180+ * ou=F,ou=E,ou=C,o=B,c=US is 3: D->C, C->E, E->F. The hop distance
181+ * from ou=C,o=B,c=US to ou=D,ou=C,o=B,c=US is -1: C->D
182+ *
183+ * @param base GeneralName
184+ * @param test GeneralName to be tested against base
185+ * @param incomparable the value to return if the names are
186+ * incomparable
187+ * @return distance of test name from base measured in hops in the
188+ * namespace hierarchy, where 0 means exact match. Result
189+ * is positive if path is some number of up hops followed by
190+ * some number of down hops; result is negative if path is
191+ * some number of down hops.
192+ */
193+ static int hops(GeneralNameInterface base, GeneralNameInterface test,
194+ int incomparable) {
195+ int baseRtest = base.constrains(test);
196+ switch (baseRtest) {
197+ case GeneralNameInterface.NAME_DIFF_TYPE:
198+ if (debug != null) {
199+ debug.println("Builder.hops(): Names are different types");
200+ }
201+ return incomparable;
202+ case GeneralNameInterface.NAME_SAME_TYPE:
203+ /* base and test are in different subtrees */
204+ break;
205+ case GeneralNameInterface.NAME_MATCH:
206+ /* base matches test */
207+ return 0;
208+ case GeneralNameInterface.NAME_WIDENS:
209+ /* base is ancestor of test */
210+ return (test.subtreeDepth()-base.subtreeDepth());
211+ case GeneralNameInterface.NAME_NARROWS:
212+ /* base is descendant of test */
213+ return (test.subtreeDepth()-base.subtreeDepth());
214+ default: // should never occur
215+ return incomparable;
216+ }
217+
218+ /* names are in different subtrees */
219+ if (base.getType() != GeneralNameInterface.NAME_DIRECTORY) {
220+ if (debug != null) {
221+ debug.println("Builder.hops(): hopDistance not implemented " +
222+ "for this name type");
223+ }
224+ return incomparable;
225+ }
226+ X500Name baseName = (X500Name)base;
227+ X500Name testName = (X500Name)test;
228+ X500Name commonName = baseName.commonAncestor(testName);
229+ if (commonName == null) {
230+ if (debug != null) {
231+ debug.println("Builder.hops(): Names are in different " +
232+ "namespaces");
233+ }
234+ return incomparable;
235+ } else {
236+ int commonDistance = commonName.subtreeDepth();
237+ int baseDistance = baseName.subtreeDepth();
238+ int testDistance = testName.subtreeDepth();
239+ return (baseDistance + testDistance - (2 * commonDistance));
240+ }
241+ }
242+
243+ /**
244+ * Determine how close a given certificate gets you toward
245+ * a given target.
246+ *
247+ * @param constraints Current NameConstraints; if null,
248+ * then caller must verify NameConstraints
249+ * independently, realizing that this certificate
250+ * may not actually lead to the target at all.
251+ * @param cert Candidate certificate for chain
252+ * @param target GeneralNameInterface name of target
253+ * @return distance from this certificate to target:
254+ * <ul>
255+ * <li>-1 means certificate could be CA for target, but
256+ * there are no NameConstraints limiting how close
257+ * <li> 0 means certificate subject or subjectAltName
258+ * matches target
259+ * <li> 1 means certificate is permitted to be CA for
260+ * target.
261+ * <li> 2 means certificate is permitted to be CA for
262+ * parent of target.
263+ * <li>&gt;0 in general, means certificate is permitted
264+ * to be a CA for this distance higher in the naming
265+ * hierarchy than the target, plus 1.
266+ * </ul>
267+ * <p>Note that the subject and/or subjectAltName of the
268+ * candidate cert does not have to be an ancestor of the
269+ * target in order to be a CA that can issue a certificate to
270+ * the target. In these cases, the target distance is calculated
271+ * by inspecting the NameConstraints extension in the candidate
272+ * certificate. For example, suppose the target is an X.500 DN with
273+ * a value of "CN=mullan,OU=ireland,O=sun,C=us" and the
274+ * NameConstraints extension in the candidate certificate
275+ * includes a permitted component of "O=sun,C=us", which implies
276+ * that the candidate certificate is allowed to issue certs in
277+ * the "O=sun,C=us" namespace. The target distance is 3
278+ * ((distance of permitted NC from target) + 1).
279+ * The (+1) is added to distinguish the result from the case
280+ * which returns (0).
281+ * @throws IOException if certificate does not get closer
282+ */
283+ static int targetDistance(NameConstraintsExtension constraints,
284+ X509Certificate cert, GeneralNameInterface target)
285+ throws IOException {
286+
287+ /* ensure that certificate satisfies existing name constraints */
288+ if (constraints != null && !constraints.verify(cert)) {
289+ throw new IOException("certificate does not satisfy existing name "
290+ + "constraints");
291+ }
292+
293+ X509CertImpl certImpl;
294+ try {
295+ certImpl = X509CertImpl.toImpl(cert);
296+ } catch (CertificateException e) {
297+ throw (IOException)new IOException("Invalid certificate").initCause(e);
298+ }
299+ /* see if certificate subject matches target */
300+ X500Name subject = X500Name.asX500Name(certImpl.getSubjectX500Principal());
301+ if (subject.equals(target)) {
302+ /* match! */
303+ return 0;
304+ }
305+
306+ SubjectAlternativeNameExtension altNameExt =
307+ certImpl.getSubjectAlternativeNameExtension();
308+ if (altNameExt != null) {
309+ GeneralNames altNames =
310+ (GeneralNames)altNameExt.get(altNameExt.SUBJECT_NAME);
311+ /* see if any alternative name matches target */
312+ if (altNames != null) {
313+ for (int j = 0, n = altNames.size(); j < n; j++) {
314+ GeneralNameInterface altName = altNames.get(j).getName();
315+ if (altName.equals(target)) {
316+ return 0;
317+ }
318+ }
319+ }
320+ }
321+
322+
323+ /* no exact match; see if certificate can get us to target */
324+
325+ /* first, get NameConstraints out of certificate */
326+ NameConstraintsExtension ncExt = certImpl.getNameConstraintsExtension();
327+ if (ncExt == null) {
328+ return -1;
329+ }
330+
331+ /* merge certificate's NameConstraints with current NameConstraints */
332+ if (constraints != null) {
333+ constraints.merge(ncExt);
334+ } else {
335+ // Make sure we do a clone here, because we're probably
336+ // going to modify this object later and we don't want to
337+ // be sharing it with a Certificate object!
338+ constraints = (NameConstraintsExtension) ncExt.clone();
339+ }
340+
341+ if (debug != null) {
342+ debug.println("Builder.targetDistance() merged constraints: "
343+ + String.valueOf(constraints));
344+ }
345+ /* reduce permitted by excluded */
346+ GeneralSubtrees permitted = (GeneralSubtrees)
347+ constraints.get(constraints.PERMITTED_SUBTREES);
348+ GeneralSubtrees excluded = (GeneralSubtrees)
349+ constraints.get(constraints.EXCLUDED_SUBTREES);
350+ if (permitted != null) {
351+ permitted.reduce(excluded);
352+ }
353+ if (debug != null) {
354+ debug.println("Builder.targetDistance() reduced constraints: "
355+ + permitted);
356+ }
357+ /* see if new merged constraints allow target */
358+ if (!constraints.verify(target)) {
359+ throw new IOException("New certificate not allowed to sign "
360+ + "certificate for target");
361+ }
362+ /* find distance to target, if any, in permitted */
363+ if (permitted == null) {
364+ /* certificate is unconstrained; could sign for anything */
365+ return -1;
366+ }
367+ for (int i = 0, n = permitted.size(); i < n; i++) {
368+ GeneralNameInterface perName = permitted.get(i).getName().getName();
369+ int distance = distance(perName, target, -1);
370+ if (distance >= 0) {
371+ return (distance + 1);
372+ }
373+ }
374+ /* no matching type in permitted; cert holder could certify target */
375+ return -1;
376+ }
377+
378+ /**
379+ * This method can be used as an optimization to filter out
380+ * certificates that do not have policies which are valid.
381+ * It returns the set of policies (String OIDs) that should exist in
382+ * the certificate policies extension of the certificate that is
383+ * needed by the builder. The logic applied is as follows:
384+ * <p>
385+ * 1) If some initial policies have been set *and* policy mappings are
386+ * inhibited, then acceptable certificates are those that include
387+ * the ANY_POLICY OID or with policies that intersect with the
388+ * initial policies.
389+ * 2) If no initial policies have been set *or* policy mappings are
390+ * not inhibited then we don't have much to work with. All we know is
391+ * that a certificate must have *some* policy because if it didn't
392+ * have any policy then the policy tree would become null (and validation
393+ * would fail).
394+ *
395+ * @return the Set of policies any of which must exist in a
396+ * cert's certificate policies extension in order for a cert to be selected.
397+ */
398+ Set<String> getMatchingPolicies() {
399+ if (matchingPolicies != null) {
400+ Set<String> initialPolicies = buildParams.getInitialPolicies();
401+ if ((!initialPolicies.isEmpty()) &&
402+ (!initialPolicies.contains(PolicyChecker.ANY_POLICY)) &&
403+ (buildParams.isPolicyMappingInhibited()))
404+ {
405+ initialPolicies.add(PolicyChecker.ANY_POLICY);
406+ matchingPolicies = initialPolicies;
407+ } else {
408+ // we just return an empty set to make sure that there is
409+ // at least a certificate policies extension in the cert
410+ matchingPolicies = Collections.<String>emptySet();
411+ }
412+ }
413+ return matchingPolicies;
414+ }
415+
416+ /**
417+ * Search the specified CertStores and add all certificates matching
418+ * selector to resultCerts. Self-signed certs are not useful here
419+ * and therefore ignored.
420+ *
421+ * If the targetCert criterion of the selector is set, only that cert
422+ * is examined and the CertStores are not searched.
423+ *
424+ * If checkAll is true, all CertStores are searched for matching certs.
425+ * If false, the method returns as soon as the first CertStore returns
426+ * a matching cert(s).
427+ *
428+ * Returns true iff resultCerts changed (a cert was added to the collection)
429+ */
430+ boolean addMatchingCerts(X509CertSelector selector,
431+ Collection<CertStore> certStores,
432+ Collection<X509Certificate> resultCerts, boolean checkAll) {
433+ X509Certificate targetCert = selector.getCertificate();
434+ if (targetCert != null) {
435+ // no need to search CertStores
436+ if (selector.match(targetCert) && !X509CertImpl.isSelfSigned
437+ (targetCert, buildParams.getSigProvider())) {
438+ if (debug != null) {
439+ debug.println("Builder.addMatchingCerts: adding target cert");
440+ }
441+ return resultCerts.add(targetCert);
442+ }
443+ return false;
444+ }
445+ boolean add = false;
446+ for (CertStore store : certStores) {
447+ try {
448+ Collection<? extends Certificate> certs =
449+ store.getCertificates(selector);
450+ for (Certificate cert : certs) {
451+ if (!X509CertImpl.isSelfSigned
452+ ((X509Certificate)cert, buildParams.getSigProvider())) {
453+ if (resultCerts.add((X509Certificate)cert)) {
454+ add = true;
455+ }
456+ }
457+ }
458+ if (!checkAll && add) {
459+ return true;
460+ }
461+ } catch (CertStoreException cse) {
462+ // if getCertificates throws a CertStoreException, we ignore
463+ // it and move on to the next CertStore
464+ if (debug != null) {
465+ debug.println("Builder.addMatchingCerts, non-fatal " +
466+ "exception retrieving certs: " + cse);
467+ cse.printStackTrace();
468+ }
469+ }
470+ }
471+ return add;
472+ }
473+
474+ /**
475+ * Returns true if CertStore is local. Currently, returns true if
476+ * type is Collection or if it has been initialized with
477+ * CollectionCertStoreParameters. A new API method should be added
478+ * to CertStore that returns local or remote.
479+ */
480+ static boolean isLocalCertStore(CertStore certStore) {
481+ return (certStore.getType().equals("Collection") ||
482+ certStore.getCertStoreParameters() instanceof
483+ CollectionCertStoreParameters);
484+ }
485+}

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t