2 * The Shibboleth License, Version 1. Copyright (c) 2002 University Corporation for Advanced Internet Development, Inc.
3 * All rights reserved Redistribution and use in source and binary forms, with or without modification, are permitted
4 * provided that the following conditions are met: Redistributions of source code must retain the above copyright
5 * notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above
6 * copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials
7 * provided with the distribution, if any, must include the following acknowledgment: "This product includes software
8 * developed by the University Corporation for Advanced Internet Development <http://www.ucaid.edu> Internet2 Project.
9 * Alternately, this acknowledegement may appear in the software itself, if and wherever such third-party
10 * acknowledgments normally appear. Neither the name of Shibboleth nor the names of its contributors, nor Internet2, nor
11 * the University Corporation for Advanced Internet Development, Inc., nor UCAID may be used to endorse or promote
12 * products derived from this software without specific prior written permission. For written permission, please contact
13 * shibboleth@shibboleth.org Products derived from this software may not be called Shibboleth, Internet2, UCAID, or the
14 * University Corporation for Advanced Internet Development, nor may Shibboleth appear in their name, without prior
15 * written permission of the University Corporation for Advanced Internet Development. THIS SOFTWARE IS PROVIDED BY THE
16 * COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE
18 * DISCLAIMED AND THE ENTIRE RISK OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE. IN NO
19 * EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC.
20 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
23 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 package edu.internet2.middleware.shibboleth.common.provider;
28 import java.security.GeneralSecurityException;
29 import java.security.cert.CertPathBuilder;
30 import java.security.cert.CertPathValidator;
31 import java.security.cert.CertPathValidatorException;
32 import java.security.cert.CertStore;
33 import java.security.cert.CertificateParsingException;
34 import java.security.cert.CollectionCertStoreParameters;
35 import java.security.cert.PKIXBuilderParameters;
36 import java.security.cert.PKIXCertPathBuilderResult;
37 import java.security.cert.PKIXCertPathValidatorResult;
38 import java.security.cert.TrustAnchor;
39 import java.security.cert.X509CertSelector;
40 import java.security.cert.X509Certificate;
41 import java.util.ArrayList;
42 import java.util.Arrays;
43 import java.util.Collection;
44 import java.util.HashSet;
45 import java.util.Iterator;
46 import java.util.List;
48 import java.util.regex.Matcher;
49 import java.util.regex.Pattern;
51 import javax.security.auth.x500.X500Principal;
53 import org.apache.log4j.Logger;
54 import org.apache.xml.security.exceptions.XMLSecurityException;
55 import org.apache.xml.security.keys.KeyInfo;
56 import org.apache.xml.security.keys.content.KeyName;
57 import org.apache.xml.security.keys.content.X509Data;
58 import org.apache.xml.security.keys.content.x509.XMLX509Certificate;
60 import edu.internet2.middleware.shibboleth.common.Trust;
61 import edu.internet2.middleware.shibboleth.metadata.EntitiesDescriptor;
62 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
63 import edu.internet2.middleware.shibboleth.metadata.ExtendedEntitiesDescriptor;
64 import edu.internet2.middleware.shibboleth.metadata.ExtendedEntityDescriptor;
65 import edu.internet2.middleware.shibboleth.metadata.KeyAuthority;
66 import edu.internet2.middleware.shibboleth.metadata.KeyDescriptor;
67 import edu.internet2.middleware.shibboleth.metadata.RoleDescriptor;
70 * @author Walter Hoehn
72 public class ShibbolethTrust extends Trust {
74 private static Logger log = Logger.getLogger(ShibbolethTrust.class.getName());
75 private static Pattern regex = Pattern.compile(".*?CN=([^,/]+).*");
77 public boolean validate(RoleDescriptor descriptor, X509Certificate[] certificateChain, int keyUse) {
79 // If we can successfully validate with an inline key, that's fine
80 boolean defaultValidation = super.validate(descriptor, certificateChain, keyUse);
81 if (defaultValidation == true) { return true; }
83 // Make sure we have the data we need
84 if (descriptor == null || certificateChain == null || certificateChain.length < 1) {
85 log.error("Appropriate data was not supplied for trust evaluation.");
88 log.debug("Inline validation was unsuccessful. Attmping PKIX...");
89 // If not, try PKIX validation against the shib-custom metadata extensions
91 // First, we want to see if we can match a keyName from the metadata against the cert
92 // Iterator through all the keys in the metadata
93 Iterator keyDescriptors = descriptor.getKeyDescriptors();
94 while (keyDescriptors.hasNext()) {
95 // Look for a key descriptor with the right usage bits
96 KeyDescriptor keyDescriptor = (KeyDescriptor) keyDescriptors.next();
97 if (keyDescriptor.getUse() != KeyDescriptor.UNSPECIFIED && keyDescriptor.getUse() != keyUse) {
98 log.debug("Role contains a key descriptor, but the usage specification is not valid for this action.");
102 // We found one, see if we can match the metadata's keyName against the cert
103 KeyInfo keyInfo = keyDescriptor.getKeyInfo();
104 if (keyInfo.containsKeyName()) {
105 for (int i = 0; i < keyInfo.lengthKeyName(); i++) {
107 if (matchKeyName(certificateChain[0], keyInfo.itemKeyName(i))) {
108 // If we find a match, try to do path validation against any key authorities we might have
110 if (pkixValidate(certificateChain, descriptor.getEntityDescriptor())) { return true; }
112 } catch (XMLSecurityException e) {
113 log.error("Problem retrieving key name from metadata: " + e);
121 private boolean pkixValidate(X509Certificate[] certChain, EntityDescriptor entity) {
123 if (entity instanceof ExtendedEntityDescriptor) {
124 Iterator keyAuthorities = ((ExtendedEntityDescriptor) entity).getKeyAuthorities();
125 // if we have any key authorities, construct a flat list of trust anchors representing each and attempt to
126 // validate against them in turn
127 while (keyAuthorities.hasNext()) {
128 if (pkixValidate(certChain, (KeyAuthority) keyAuthorities.next())) { return true; }
132 // We couldn't do path validation based on metadata attached to the entity, we now need to walk up the chain of
133 // nested entities and attempt to validate at each group level
134 EntitiesDescriptor group = entity.getEntitiesDescriptor();
136 if (pkixValidate(certChain, group)) { return true; }
139 // We've walked the entire metadata chain with no success, so fail
143 private boolean pkixValidate(X509Certificate[] certChain, EntitiesDescriptor group) {
145 log.debug("Attemping to validate against parent group.");
146 if (group instanceof ExtendedEntitiesDescriptor) {
147 Iterator keyAuthorities = ((ExtendedEntitiesDescriptor) group).getKeyAuthorities();
148 // if we have any key authorities, construct a flat list of trust anchors representing each and attempt to
149 // validate against them in turn
150 while (keyAuthorities.hasNext()) {
151 if (pkixValidate(certChain, (KeyAuthority) keyAuthorities.next())) { return true; }
155 // If not, attempt to walk up the chain for validation
156 EntitiesDescriptor parent = group.getEntitiesDescriptor();
157 if (parent != null) {
158 if (pkixValidate(certChain, parent)) { return true; }
164 private boolean pkixValidate(X509Certificate[] certChain, KeyAuthority authority) {
166 Set anchors = new HashSet();
167 Iterator keyInfos = authority.getKeyInfos();
168 while (keyInfos.hasNext()) {
169 KeyInfo keyInfo = (KeyInfo) keyInfos.next();
170 if (keyInfo.containsX509Data()) {
172 for (int i = 0; i < keyInfo.lengthX509Data(); i++) {
173 X509Data data = keyInfo.itemX509Data(i);
174 if (data.containsCertificate()) {
175 for (int j = 0; j < data.lengthCertificate(); j++) {
176 XMLX509Certificate xmlCert = data.itemCertificate(j);
177 anchors.add(new TrustAnchor(xmlCert.getX509Certificate(), null));
181 } catch (XMLSecurityException e) {
182 log.error("Encountered an error constructing trust list from shibboleth metadata: " + e);
187 // alright, if we were able to create a trust list, attempt a pkix validation against the list
188 if (anchors.size() > 0) {
189 log.debug("Constructed a trust list from key authority. Attempting path validation...");
191 CertPathValidator validator = CertPathValidator.getInstance("PKIX");
193 X509CertSelector selector = new X509CertSelector();
194 selector.setCertificate(certChain[0]);
195 PKIXBuilderParameters params = new PKIXBuilderParameters(anchors, selector);
196 params.setMaxPathLength(authority.getVerifyDepth());
197 CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(Arrays
198 .asList(certChain)));
199 List stores = new ArrayList();
201 params.setCertStores(stores);
202 //TODO hmm... what about revocation
203 params.setRevocationEnabled(false);
205 CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
206 PKIXCertPathBuilderResult buildResult = (PKIXCertPathBuilderResult) builder.build(params);
208 PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) validator.validate(buildResult
209 .getCertPath(), params);
210 log.debug("Path successfully validated.");
213 } catch (CertPathValidatorException e) {
214 log.debug("Path failed to validate: " + e);
215 } catch (GeneralSecurityException e) {
216 log.error("Encountered an error during validation: " + e);
222 private static boolean matchKeyName(X509Certificate certificate, KeyName keyName) {
224 // First, try to match DN against metadata
226 if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253).equals(
227 new X500Principal(keyName.getKeyName()).getName(X500Principal.RFC2253))) {
228 log.debug("Matched against DN.");
231 } catch (IllegalArgumentException iae) {
232 // squelch this runtime exception, since
233 // this might be a valid case
236 // If that doesn't work, we try matching against
237 // some Subject Alt Names
239 Collection altNames = certificate.getSubjectAlternativeNames();
240 if (altNames != null) {
241 for (Iterator nameIterator = altNames.iterator(); nameIterator.hasNext();) {
242 List altName = (List) nameIterator.next();
243 if (altName.get(0).equals(new Integer(2)) || altName.get(0).equals(new Integer(6))) {
244 // 2 is DNS, 6 is URI
245 if (altName.get(0).equals(keyName.getKeyName())) {
246 log.debug("Matched against SubjectAltName.");
252 } catch (CertificateParsingException e1) {
253 log.error("Encountered an problem trying to extract Subject Alternate "
254 + "Name from supplied certificate: " + e1);
257 // If that doesn't work, try to match using
258 // SSL-style hostname matching
259 if (getHostNameFromDN(certificate.getSubjectX500Principal()).equals(keyName.getKeyName())) {
260 log.debug("Matched against hostname.");
267 private static String getHostNameFromDN(X500Principal dn) {
269 Matcher matches = regex.matcher(dn.getName(X500Principal.RFC2253));
270 if (!matches.find() || matches.groupCount() > 1) {
271 log.error("Unable to extract host name name from certificate subject DN.");
274 return matches.group(1);