2 * Copyright [2005] [University Corporation for Advanced Internet Development, Inc.]
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package edu.internet2.middleware.shibboleth.common.provider;
19 import java.io.ByteArrayInputStream;
20 import java.io.IOException;
21 import java.security.GeneralSecurityException;
22 import java.security.cert.CertPathBuilder;
23 import java.security.cert.CertPathValidator;
24 import java.security.cert.CertPathValidatorException;
25 import java.security.cert.CertStore;
26 import java.security.cert.CertificateFactory;
27 import java.security.cert.CertificateParsingException;
28 import java.security.cert.CollectionCertStoreParameters;
29 import java.security.cert.PKIXBuilderParameters;
30 import java.security.cert.PKIXCertPathBuilderResult;
31 import java.security.cert.PKIXCertPathValidatorResult;
32 import java.security.cert.TrustAnchor;
33 import java.security.cert.X509CRL;
34 import java.security.cert.X509CertSelector;
35 import java.security.cert.X509Certificate;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Collection;
39 import java.util.HashSet;
40 import java.util.Iterator;
41 import java.util.List;
44 import javax.security.auth.x500.X500Principal;
46 import org.apache.log4j.Logger;
47 import org.apache.xml.security.exceptions.XMLSecurityException;
48 import org.apache.xml.security.keys.KeyInfo;
49 import org.apache.xml.security.keys.content.KeyName;
50 import org.apache.xml.security.keys.content.X509Data;
51 import org.apache.xml.security.keys.content.x509.XMLX509CRL;
52 import org.apache.xml.security.keys.content.x509.XMLX509Certificate;
53 import org.apache.xmlbeans.XmlException;
54 import org.bouncycastle.asn1.ASN1InputStream;
55 import org.bouncycastle.asn1.DERObject;
56 import org.bouncycastle.asn1.DERObjectIdentifier;
57 import org.bouncycastle.asn1.DERSequence;
58 import org.bouncycastle.asn1.DERSet;
59 import org.bouncycastle.asn1.DERString;
60 import org.opensaml.SAMLException;
61 import org.opensaml.SAMLSignedObject;
62 import org.w3c.dom.Element;
63 import org.w3c.dom.Node;
65 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
66 import edu.internet2.middleware.shibboleth.common.Trust;
67 import edu.internet2.middleware.shibboleth.metadata.EntitiesDescriptor;
68 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
69 import edu.internet2.middleware.shibboleth.metadata.ExtendedEntitiesDescriptor;
70 import edu.internet2.middleware.shibboleth.metadata.ExtendedEntityDescriptor;
71 import edu.internet2.middleware.shibboleth.metadata.KeyAuthority;
72 import edu.internet2.middleware.shibboleth.metadata.KeyDescriptor;
73 import edu.internet2.middleware.shibboleth.metadata.RoleDescriptor;
74 import edu.internet2.middleware.shibboleth.serviceprovider.PluggableConfigurationComponent;
77 * <code>Trust</code> implementation that does PKIX validation against key authorities included in shibboleth-specific
78 * extensions to SAML 2 metadata.
80 * @author Walter Hoehn
82 public class ShibbolethTrust extends BasicTrust implements Trust, PluggableConfigurationComponent {
84 private static Logger log = Logger.getLogger(ShibbolethTrust.class.getName());
85 private static final String CN_OID = "2.5.4.3";
88 * @see edu.internet2.middleware.shibboleth.common.Trust#validate(java.security.cert.X509Certificate,
89 * java.security.cert.X509Certificate[], edu.internet2.middleware.shibboleth.metadata.RoleDescriptor)
91 public boolean validate(X509Certificate certificateEE, X509Certificate[] certificateChain, RoleDescriptor descriptor) {
93 return validate(certificateEE, certificateChain, descriptor, true);
97 * @see edu.internet2.middleware.shibboleth.common.Trust#validate(org.opensaml.SAMLSignedObject,
98 * edu.internet2.middleware.shibboleth.metadata.RoleDescriptor)
100 public boolean validate(SAMLSignedObject token, RoleDescriptor descriptor) {
102 if (super.validate(token, descriptor)) return true;
104 /* Certificates supplied with the signed object */
105 ArrayList/* <X509Certificate> */certificates = new ArrayList/* <X509Certificate> */();
106 X509Certificate certificateEE = null;
108 /* Iterate to count the certificates, and look for the signer */
109 Iterator icertificates;
111 icertificates = token.getX509Certificates();
112 } catch (SAMLException e1) {
115 while (icertificates.hasNext()) {
116 X509Certificate certificate = (X509Certificate) icertificates.next();
118 token.verify(certificate);
119 // This is the certificate that signed the object
120 certificateEE = certificate;
121 certificates.add(certificate);
122 } catch (SAMLException e) {
123 certificates.add(certificate);
127 if (certificateEE == null) return false; // No key validates the signature
129 // With a count we can now build a typed array
130 X509Certificate[] certificateChain = new X509Certificate[certificates.size()];
132 for (icertificates = certificates.iterator(); icertificates.hasNext();) {
133 certificateChain[i++] = (X509Certificate) icertificates.next();
135 return validate(certificateEE, certificateChain, descriptor);
139 * @see edu.internet2.middleware.shibboleth.common.Trust#validate(java.security.cert.X509Certificate,
140 * java.security.cert.X509Certificate[], edu.internet2.middleware.shibboleth.metadata.RoleDescriptor, boolean)
142 public boolean validate(X509Certificate certificateEE, X509Certificate[] certificateChain,
143 RoleDescriptor descriptor, boolean checkName) {
145 // If we can successfully validate with an inline key, that's fine
146 boolean defaultValidation = super.validate(certificateEE, certificateChain, descriptor, checkName);
147 if (defaultValidation == true) { return true; }
149 // Make sure we have the data we need
150 if (descriptor == null || certificateEE == null) {
151 log.error("Appropriate data was not supplied for trust evaluation.");
154 log.debug("Inline validation was unsuccessful. Attmping PKIX...");
155 // If not, try PKIX validation against the shib-custom metadata extensions
157 // First, we want to see if we can match a keyName from the metadata against the cert
158 // Iterator through all the keys in the metadata
161 if (matchProviderId(certificateChain[0], descriptor.getEntityDescriptor().getId())) {
165 Iterator keyDescriptors = descriptor.getKeyDescriptors();
166 while (checkName && keyDescriptors.hasNext()) {
167 // Look for a key descriptor with the right usage bits
168 KeyDescriptor keyDescriptor = (KeyDescriptor) keyDescriptors.next();
169 if (keyDescriptor.getUse() == KeyDescriptor.ENCRYPTION) {
170 log.debug("Skipping key descriptor with inappropriate usage indicator.");
174 // We found one, see if we can match the metadata's keyName against the cert
175 KeyInfo keyInfo = keyDescriptor.getKeyInfo();
176 if (keyInfo.containsKeyName()) {
177 for (int i = 0; i < keyInfo.lengthKeyName(); i++) {
179 if (matchKeyName(certificateChain[0], keyInfo.itemKeyName(i))) {
183 } catch (XMLSecurityException e) {
184 log.error("Problem retrieving key name from metadata: " + e);
193 log.error("cannot match certificate subject against acceptable key names based on the "
194 + "metadata entityId or KeyDescriptors");
198 if (pkixValidate(certificateEE, certificateChain, descriptor.getEntityDescriptor())) { return true; }
202 private boolean pkixValidate(X509Certificate certEE, X509Certificate[] certChain, EntityDescriptor entity) {
204 if (entity instanceof ExtendedEntityDescriptor) {
205 Iterator keyAuthorities = ((ExtendedEntityDescriptor) entity).getKeyAuthorities();
206 // if we have any key authorities, construct a flat list of trust anchors representing each and attempt to
207 // validate against them in turn
208 while (keyAuthorities.hasNext()) {
209 if (pkixValidate(certEE, certChain, (KeyAuthority) keyAuthorities.next())) { return true; }
213 // We couldn't do path validation based on metadata attached to the entity, we now need to walk up the chain of
214 // nested entities and attempt to validate at each group level
215 EntitiesDescriptor group = entity.getEntitiesDescriptor();
217 if (pkixValidate(certEE, certChain, group)) { return true; }
220 // We've walked the entire metadata chain with no success, so fail
224 private boolean pkixValidate(X509Certificate certEE, X509Certificate[] certChain, EntitiesDescriptor group) {
226 log.debug("Attemping to validate against parent group.");
227 if (group instanceof ExtendedEntitiesDescriptor) {
228 Iterator keyAuthorities = ((ExtendedEntitiesDescriptor) group).getKeyAuthorities();
229 // if we have any key authorities, construct a flat list of trust anchors representing each and attempt to
230 // validate against them in turn
231 while (keyAuthorities.hasNext()) {
232 if (pkixValidate(certEE, certChain, (KeyAuthority) keyAuthorities.next())) { return true; }
236 // If not, attempt to walk up the chain for validation
237 EntitiesDescriptor parent = group.getEntitiesDescriptor();
238 if (parent != null) {
239 if (pkixValidate(certEE, certChain, parent)) { return true; }
245 private boolean pkixValidate(X509Certificate certEE, X509Certificate[] certChain, KeyAuthority authority) {
247 Set anchors = new HashSet();
248 Set crls = new HashSet();
249 Iterator keyInfos = authority.getKeyInfos();
250 while (keyInfos.hasNext()) {
251 KeyInfo keyInfo = (KeyInfo) keyInfos.next();
252 if (keyInfo.containsX509Data()) {
254 // Add all certificates in the authority as trust anchors
255 for (int i = 0; i < keyInfo.lengthX509Data(); i++) {
256 X509Data data = keyInfo.itemX509Data(i);
257 if (data.containsCertificate()) {
258 for (int j = 0; j < data.lengthCertificate(); j++) {
259 XMLX509Certificate xmlCert = data.itemCertificate(j);
260 anchors.add(new TrustAnchor(xmlCert.getX509Certificate(), null));
263 // Compile all CRLs in the authority
264 if (data.containsCRL()) {
265 for (int j = 0; j < data.lengthCRL(); j++) {
266 XMLX509CRL xmlCrl = data.itemCRL(j);
268 X509CRL crl = (X509CRL) CertificateFactory.getInstance("X.509").generateCRL(
269 new ByteArrayInputStream(xmlCrl.getCRLBytes()));
270 if (crl.getRevokedCertificates() != null && crl.getRevokedCertificates().size() > 0) {
273 } catch (GeneralSecurityException e) {
274 log.error("Encountered an error parsing CRL from shibboleth metadata: " + e);
280 } catch (XMLSecurityException e) {
281 log.error("Encountered an error constructing trust list from shibboleth metadata: " + e);
286 // alright, if we were able to create a trust list, attempt a pkix validation against the list
287 if (anchors.size() > 0) {
288 log.debug("Constructed a trust list from key authority. Attempting path validation...");
290 CertPathValidator validator = CertPathValidator.getInstance("PKIX");
292 X509CertSelector selector = new X509CertSelector();
293 selector.setCertificate(certEE);
294 PKIXBuilderParameters params = new PKIXBuilderParameters(anchors, selector);
295 params.setMaxPathLength(authority.getVerifyDepth());
296 List storeMaterial = new ArrayList(crls);
297 storeMaterial.addAll(Arrays.asList(certChain));
298 CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(storeMaterial));
299 List stores = new ArrayList();
301 params.setCertStores(stores);
302 if (crls.size() > 0) {
303 params.setRevocationEnabled(true);
305 params.setRevocationEnabled(false);
307 // System.err.println(params.toString());
308 CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
309 PKIXCertPathBuilderResult buildResult = (PKIXCertPathBuilderResult) builder.build(params);
311 PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) validator.validate(buildResult
312 .getCertPath(), params);
313 log.debug("Path successfully validated.");
316 } catch (CertPathValidatorException e) {
317 log.debug("Path failed to validate: " + e);
318 } catch (GeneralSecurityException e) {
319 log.error("Encountered an error during validation: " + e);
325 private static boolean matchKeyName(X509Certificate certificate, KeyName keyName) {
327 // First, try to match DN against metadata
329 if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253).equals(
330 new X500Principal(keyName.getKeyName()).getName(X500Principal.RFC2253))) {
331 log.debug("Matched against DN.");
334 } catch (IllegalArgumentException iae) {
335 // squelch this runtime exception, since
336 // this might be a valid case
339 // If that doesn't work, we try matching against
340 // some Subject Alt Names
342 Collection altNames = certificate.getSubjectAlternativeNames();
343 if (altNames != null) {
344 for (Iterator nameIterator = altNames.iterator(); nameIterator.hasNext();) {
345 List altName = (List) nameIterator.next();
346 if (altName.get(0).equals(new Integer(2)) || altName.get(0).equals(new Integer(6))) {
347 // 2 is DNS, 6 is URI
348 if (altName.get(0).equals(keyName.getKeyName())) {
349 log.debug("Matched against SubjectAltName.");
355 } catch (CertificateParsingException e1) {
356 log.error("Encountered an problem trying to extract Subject Alternate "
357 + "Name from supplied certificate: " + e1);
360 // If that doesn't work, try to match using
361 // SSL-style hostname matching
362 if (getHostNameFromDN(certificate.getSubjectX500Principal()).equals(keyName.getKeyName())) {
363 log.debug("Matched against hostname.");
370 public static String[] getCredentialNames(X509Certificate certificate) {
371 ArrayList names = new ArrayList();
372 names.add(certificate.getSubjectX500Principal().getName(X500Principal.RFC2253));
374 Collection altNames = certificate.getSubjectAlternativeNames();
375 if (altNames != null) {
376 for (Iterator nameIterator = altNames.iterator(); nameIterator.hasNext();) {
377 List altName = (List) nameIterator.next();
378 if (altName.get(0).equals(new Integer(2))) { // 2 is DNS
379 names.add(altName.get(1));
381 else if (altName.get(0).equals(new Integer(6))) { // 6 is URI
382 names.add(altName.get(1));
386 } catch (CertificateParsingException e1) {
387 log.error("Encountered an problem trying to extract Subject Alternate "
388 + "Name from supplied certificate: " + e1);
390 names.add(getHostNameFromDN(certificate.getSubjectX500Principal()));
391 return (String[]) names.toArray(new String[1]);
394 private static boolean matchProviderId(X509Certificate certificate, String id) {
396 // Try matching against URI Subject Alt Names
398 Collection altNames = certificate.getSubjectAlternativeNames();
399 if (altNames != null) {
400 for (Iterator nameIterator = altNames.iterator(); nameIterator.hasNext();) {
401 List altName = (List) nameIterator.next();
402 if (altName.get(0).equals(new Integer(6))) { // 6 is URI
403 if (altName.get(1).equals(id)) {
404 log.debug("Entity ID matched against SubjectAltName.");
410 } catch (CertificateParsingException e1) {
411 log.error("Encountered an problem trying to extract Subject Alternate "
412 + "Name from supplied certificate: " + e1);
415 // If that doesn't work, try to match using
416 // SSL-style hostname matching
417 if (getHostNameFromDN(certificate.getSubjectX500Principal()).equals(id)) {
418 log.debug("Entity ID matched against hostname.");
425 public static String getHostNameFromDN(X500Principal dn) {
427 // Parse the ASN.1 representation of the dn and grab the last CN component that we find
428 // We used to do this with the dn string, but the JDK's default parsing caused problems with some DNs
430 ASN1InputStream asn1Stream = new ASN1InputStream(dn.getEncoded());
431 DERObject parent = asn1Stream.readObject();
433 if (!(parent instanceof DERSequence)) {
434 log.error("Unable to extract host name name from certificate subject DN: incorrect ASN.1 encoding.");
439 for (int i = 0; i < ((DERSequence) parent).size(); i++) {
440 DERObject dnComponent = ((DERSequence) parent).getObjectAt(i).getDERObject();
441 if (!(dnComponent instanceof DERSet)) {
442 log.debug("No DN components.");
446 // Each DN component is a set
447 for (int j = 0; j < ((DERSet) dnComponent).size(); j++) {
448 DERObject grandChild = ((DERSet) dnComponent).getObjectAt(j).getDERObject();
450 if (((DERSequence) grandChild).getObjectAt(0) != null
451 && ((DERSequence) grandChild).getObjectAt(0).getDERObject() instanceof DERObjectIdentifier) {
452 DERObjectIdentifier componentId = (DERObjectIdentifier) ((DERSequence) grandChild).getObjectAt(
455 if (CN_OID.equals(componentId.getId())) {
456 // OK, this dn component is actually a cn attribute
457 if (((DERSequence) grandChild).getObjectAt(1) != null
458 && ((DERSequence) grandChild).getObjectAt(1).getDERObject() instanceof DERString) {
459 cn = ((DERString) ((DERSequence) grandChild).getObjectAt(1).getDERObject()).getString();
468 } catch (IOException e) {
469 log.error("Unable to extract host name name from certificate subject DN: ASN.1 parsing failed: " + e);
474 public void initialize(Node dom) throws XmlException, ShibbolethConfigurationException {
478 public void initialize(Element dom) throws SAMLException, XmlException, ShibbolethConfigurationException {