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.io.ByteArrayInputStream;
29 import java.security.GeneralSecurityException;
30 import java.security.cert.CertPathBuilder;
31 import java.security.cert.CertPathValidator;
32 import java.security.cert.CertPathValidatorException;
33 import java.security.cert.CertStore;
34 import java.security.cert.CertificateFactory;
35 import java.security.cert.CertificateParsingException;
36 import java.security.cert.CollectionCertStoreParameters;
37 import java.security.cert.PKIXBuilderParameters;
38 import java.security.cert.PKIXCertPathBuilderResult;
39 import java.security.cert.PKIXCertPathValidatorResult;
40 import java.security.cert.TrustAnchor;
41 import java.security.cert.X509CertSelector;
42 import java.security.cert.X509Certificate;
43 import java.util.ArrayList;
44 import java.util.Arrays;
45 import java.util.Collection;
46 import java.util.HashSet;
47 import java.util.Iterator;
48 import java.util.List;
50 import java.util.regex.Matcher;
51 import java.util.regex.Pattern;
53 import javax.security.auth.x500.X500Principal;
55 import org.apache.log4j.Logger;
56 import org.apache.xml.security.exceptions.XMLSecurityException;
57 import org.apache.xml.security.keys.KeyInfo;
58 import org.apache.xml.security.keys.content.KeyName;
59 import org.apache.xml.security.keys.content.X509Data;
60 import org.apache.xml.security.keys.content.x509.XMLX509CRL;
61 import org.apache.xml.security.keys.content.x509.XMLX509Certificate;
63 import edu.internet2.middleware.shibboleth.common.Trust;
64 import edu.internet2.middleware.shibboleth.metadata.EntitiesDescriptor;
65 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
66 import edu.internet2.middleware.shibboleth.metadata.ExtendedEntitiesDescriptor;
67 import edu.internet2.middleware.shibboleth.metadata.ExtendedEntityDescriptor;
68 import edu.internet2.middleware.shibboleth.metadata.KeyAuthority;
69 import edu.internet2.middleware.shibboleth.metadata.KeyDescriptor;
70 import edu.internet2.middleware.shibboleth.metadata.RoleDescriptor;
73 * <code>Trust</code> implementation that does PKIX validation against key authorities included in shibboleth-specific
74 * extensions to SAML 2 metadata.
76 * @author Walter Hoehn
78 public class ShibbolethTrust extends BasicTrust implements Trust {
80 private static Logger log = Logger.getLogger(ShibbolethTrust.class.getName());
81 private static Pattern regex = Pattern.compile(".*?CN=([^,/]+).*");
84 * @see edu.internet2.middleware.shibboleth.common.Trust#validate(edu.internet2.middleware.shibboleth.metadata.RoleDescriptor,
85 * java.security.cert.X509Certificate[], int)
87 public boolean validate(RoleDescriptor descriptor, X509Certificate[] certificateChain, int keyUse) {
89 // If we can successfully validate with an inline key, that's fine
90 boolean defaultValidation = super.validate(descriptor, certificateChain, keyUse);
91 if (defaultValidation == true) { return true; }
93 // Make sure we have the data we need
94 if (descriptor == null || certificateChain == null || certificateChain.length < 1) {
95 log.error("Appropriate data was not supplied for trust evaluation.");
98 log.debug("Inline validation was unsuccessful. Attmping PKIX...");
99 // If not, try PKIX validation against the shib-custom metadata extensions
101 // First, we want to see if we can match a keyName from the metadata against the cert
102 // Iterator through all the keys in the metadata
103 Iterator keyDescriptors = descriptor.getKeyDescriptors();
104 while (keyDescriptors.hasNext()) {
105 // Look for a key descriptor with the right usage bits
106 KeyDescriptor keyDescriptor = (KeyDescriptor) keyDescriptors.next();
107 if (keyDescriptor.getUse() != KeyDescriptor.UNSPECIFIED && keyDescriptor.getUse() != keyUse) {
108 log.debug("Role contains a key descriptor, but the usage specification is not valid for this action.");
112 // We found one, see if we can match the metadata's keyName against the cert
113 KeyInfo keyInfo = keyDescriptor.getKeyInfo();
114 if (keyInfo.containsKeyName()) {
115 for (int i = 0; i < keyInfo.lengthKeyName(); i++) {
117 if (matchKeyName(certificateChain[0], keyInfo.itemKeyName(i))) {
118 // If we find a match, try to do path validation against any key authorities we might have
120 if (pkixValidate(certificateChain, descriptor.getEntityDescriptor())) { return true; }
122 } catch (XMLSecurityException e) {
123 log.error("Problem retrieving key name from metadata: " + e);
131 private boolean pkixValidate(X509Certificate[] certChain, EntityDescriptor entity) {
133 if (entity instanceof ExtendedEntityDescriptor) {
134 Iterator keyAuthorities = ((ExtendedEntityDescriptor) entity).getKeyAuthorities();
135 // if we have any key authorities, construct a flat list of trust anchors representing each and attempt to
136 // validate against them in turn
137 while (keyAuthorities.hasNext()) {
138 if (pkixValidate(certChain, (KeyAuthority) keyAuthorities.next())) { return true; }
142 // We couldn't do path validation based on metadata attached to the entity, we now need to walk up the chain of
143 // nested entities and attempt to validate at each group level
144 EntitiesDescriptor group = entity.getEntitiesDescriptor();
146 if (pkixValidate(certChain, group)) { return true; }
149 // We've walked the entire metadata chain with no success, so fail
153 private boolean pkixValidate(X509Certificate[] certChain, EntitiesDescriptor group) {
155 log.debug("Attemping to validate against parent group.");
156 if (group instanceof ExtendedEntitiesDescriptor) {
157 Iterator keyAuthorities = ((ExtendedEntitiesDescriptor) group).getKeyAuthorities();
158 // if we have any key authorities, construct a flat list of trust anchors representing each and attempt to
159 // validate against them in turn
160 while (keyAuthorities.hasNext()) {
161 if (pkixValidate(certChain, (KeyAuthority) keyAuthorities.next())) { return true; }
165 // If not, attempt to walk up the chain for validation
166 EntitiesDescriptor parent = group.getEntitiesDescriptor();
167 if (parent != null) {
168 if (pkixValidate(certChain, parent)) { return true; }
174 private boolean pkixValidate(X509Certificate[] certChain, KeyAuthority authority) {
176 Set anchors = new HashSet();
177 Set crls = new HashSet();
178 Iterator keyInfos = authority.getKeyInfos();
179 while (keyInfos.hasNext()) {
180 KeyInfo keyInfo = (KeyInfo) keyInfos.next();
181 if (keyInfo.containsX509Data()) {
183 //Add all certificates in the authority as trust anchors
184 for (int i = 0; i < keyInfo.lengthX509Data(); i++) {
185 X509Data data = keyInfo.itemX509Data(i);
186 if (data.containsCertificate()) {
187 for (int j = 0; j < data.lengthCertificate(); j++) {
188 XMLX509Certificate xmlCert = data.itemCertificate(j);
189 anchors.add(new TrustAnchor(xmlCert.getX509Certificate(), null));
192 // Compile all CRLs in the authority
193 if (data.containsCRL()) {
194 for (int j = 0; j < data.lengthCRL(); j++) {
195 XMLX509CRL xmlCrl = data.itemCRL(j);
197 crls.add(CertificateFactory.getInstance("X.509").generateCRL(
198 new ByteArrayInputStream(xmlCrl.getCRLBytes())));
199 } catch (GeneralSecurityException e) {
200 log.error("Encountered an error parsing CRL from shibboleth metadata: " + e);
206 } catch (XMLSecurityException e) {
207 log.error("Encountered an error constructing trust list from shibboleth metadata: " + e);
212 // alright, if we were able to create a trust list, attempt a pkix validation against the list
213 if (anchors.size() > 0) {
214 log.debug("Constructed a trust list from key authority. Attempting path validation...");
216 CertPathValidator validator = CertPathValidator.getInstance("PKIX");
218 X509CertSelector selector = new X509CertSelector();
219 selector.setCertificate(certChain[0]);
220 PKIXBuilderParameters params = new PKIXBuilderParameters(anchors, selector);
221 params.setMaxPathLength(authority.getVerifyDepth());
222 List storeMaterial = new ArrayList(crls);
223 storeMaterial.addAll(Arrays.asList(certChain));
224 CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(storeMaterial));
225 List stores = new ArrayList();
227 params.setCertStores(stores);
228 if (crls.size() > 0) {
229 params.setRevocationEnabled(true);
231 params.setRevocationEnabled(false);
234 CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
235 PKIXCertPathBuilderResult buildResult = (PKIXCertPathBuilderResult) builder.build(params);
237 PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) validator.validate(buildResult
238 .getCertPath(), params);
239 log.debug("Path successfully validated.");
242 } catch (CertPathValidatorException e) {
243 log.debug("Path failed to validate: " + e);
244 } catch (GeneralSecurityException e) {
245 log.error("Encountered an error during validation: " + e);
251 private static boolean matchKeyName(X509Certificate certificate, KeyName keyName) {
253 // First, try to match DN against metadata
255 if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253).equals(
256 new X500Principal(keyName.getKeyName()).getName(X500Principal.RFC2253))) {
257 log.debug("Matched against DN.");
260 } catch (IllegalArgumentException iae) {
261 // squelch this runtime exception, since
262 // this might be a valid case
265 // If that doesn't work, we try matching against
266 // some Subject Alt Names
268 Collection altNames = certificate.getSubjectAlternativeNames();
269 if (altNames != null) {
270 for (Iterator nameIterator = altNames.iterator(); nameIterator.hasNext();) {
271 List altName = (List) nameIterator.next();
272 if (altName.get(0).equals(new Integer(2)) || altName.get(0).equals(new Integer(6))) {
273 // 2 is DNS, 6 is URI
274 if (altName.get(0).equals(keyName.getKeyName())) {
275 log.debug("Matched against SubjectAltName.");
281 } catch (CertificateParsingException e1) {
282 log.error("Encountered an problem trying to extract Subject Alternate "
283 + "Name from supplied certificate: " + e1);
286 // If that doesn't work, try to match using
287 // SSL-style hostname matching
288 if (getHostNameFromDN(certificate.getSubjectX500Principal()).equals(keyName.getKeyName())) {
289 log.debug("Matched against hostname.");
296 private static String getHostNameFromDN(X500Principal dn) {
298 Matcher matches = regex.matcher(dn.getName(X500Principal.RFC2253));
299 if (!matches.find() || matches.groupCount() > 1) {
300 log.error("Unable to extract host name name from certificate subject DN.");
303 return matches.group(1);