Removed DN parsing code duplication.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / common / provider / ShibbolethTrust.java
1 /*
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.
24  */
25
26 package edu.internet2.middleware.shibboleth.common.provider;
27
28 import java.io.ByteArrayInputStream;
29 import java.io.IOException;
30 import java.security.GeneralSecurityException;
31 import java.security.cert.CertPathBuilder;
32 import java.security.cert.CertPathValidator;
33 import java.security.cert.CertPathValidatorException;
34 import java.security.cert.CertStore;
35 import java.security.cert.CertificateFactory;
36 import java.security.cert.CertificateParsingException;
37 import java.security.cert.CollectionCertStoreParameters;
38 import java.security.cert.PKIXBuilderParameters;
39 import java.security.cert.PKIXCertPathBuilderResult;
40 import java.security.cert.PKIXCertPathValidatorResult;
41 import java.security.cert.TrustAnchor;
42 import java.security.cert.X509CRL;
43 import java.security.cert.X509CertSelector;
44 import java.security.cert.X509Certificate;
45 import java.util.ArrayList;
46 import java.util.Arrays;
47 import java.util.Collection;
48 import java.util.HashSet;
49 import java.util.Iterator;
50 import java.util.List;
51 import java.util.Set;
52
53 import javax.security.auth.x500.X500Principal;
54
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;
62 import org.bouncycastle.asn1.ASN1InputStream;
63 import org.bouncycastle.asn1.DERObject;
64 import org.bouncycastle.asn1.DERObjectIdentifier;
65 import org.bouncycastle.asn1.DERPrintableString;
66 import org.bouncycastle.asn1.DERSequence;
67 import org.bouncycastle.asn1.DERSet;
68 import org.opensaml.SAMLException;
69 import org.opensaml.SAMLSignedObject;
70
71 import edu.internet2.middleware.shibboleth.common.Trust;
72 import edu.internet2.middleware.shibboleth.metadata.EntitiesDescriptor;
73 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
74 import edu.internet2.middleware.shibboleth.metadata.ExtendedEntitiesDescriptor;
75 import edu.internet2.middleware.shibboleth.metadata.ExtendedEntityDescriptor;
76 import edu.internet2.middleware.shibboleth.metadata.KeyAuthority;
77 import edu.internet2.middleware.shibboleth.metadata.KeyDescriptor;
78 import edu.internet2.middleware.shibboleth.metadata.RoleDescriptor;
79
80 /**
81  * <code>Trust</code> implementation that does PKIX validation against key authorities included in shibboleth-specific
82  * extensions to SAML 2 metadata.
83  * 
84  * @author Walter Hoehn
85  */
86 public class ShibbolethTrust extends BasicTrust implements Trust {
87
88         private static Logger log = Logger.getLogger(ShibbolethTrust.class.getName());
89         private static final String CN_OID = "2.5.4.3";
90
91         /*
92          * @see edu.internet2.middleware.shibboleth.common.Trust#validate(java.security.cert.X509Certificate,
93          *      java.security.cert.X509Certificate[], edu.internet2.middleware.shibboleth.metadata.RoleDescriptor)
94          */
95         public boolean validate(X509Certificate certificateEE, X509Certificate[] certificateChain, RoleDescriptor descriptor) {
96
97                 return validate(certificateEE, certificateChain, descriptor, true);
98         }
99
100         /*
101          * @see edu.internet2.middleware.shibboleth.common.Trust#validate(org.opensaml.SAMLSignedObject,
102          *      edu.internet2.middleware.shibboleth.metadata.RoleDescriptor)
103          */
104         public boolean validate(SAMLSignedObject token, RoleDescriptor descriptor) {
105
106                 if (super.validate(token, descriptor)) return true;
107
108                 /* Certificates supplied with the signed object */
109                 ArrayList/* <X509Certificate> */certificates = new ArrayList/* <X509Certificate> */();
110                 X509Certificate certificateEE = null;
111
112                 /* Iterate to count the certificates, and look for the signer */
113                 Iterator icertificates;
114                 try {
115                         icertificates = token.getX509Certificates();
116                 } catch (SAMLException e1) {
117                         return false;
118                 }
119                 while (icertificates.hasNext()) {
120                         X509Certificate certificate = (X509Certificate) icertificates.next();
121                         try {
122                                 token.verify(certificate);
123                                 // This is the certificate that signed the object
124                                 certificateEE = certificate;
125                                 certificates.add(certificate);
126                         } catch (SAMLException e) {
127                                 certificates.add(certificate);
128                         }
129                 }
130
131                 if (certificateEE == null) return false; // No key validates the signature
132
133                 // With a count we can now build a typed array
134                 X509Certificate[] certificateChain = new X509Certificate[certificates.size()];
135                 int i = 0;
136                 for (icertificates = certificates.iterator(); icertificates.hasNext();) {
137                         certificateChain[i++] = (X509Certificate) icertificates.next();
138                 }
139                 return validate(certificateEE, certificateChain, descriptor);
140         }
141
142         /*
143          * @see edu.internet2.middleware.shibboleth.common.Trust#validate(java.security.cert.X509Certificate,
144          *      java.security.cert.X509Certificate[], edu.internet2.middleware.shibboleth.metadata.RoleDescriptor, boolean)
145          */
146         public boolean validate(X509Certificate certificateEE, X509Certificate[] certificateChain,
147                         RoleDescriptor descriptor, boolean checkName) {
148
149                 // If we can successfully validate with an inline key, that's fine
150                 boolean defaultValidation = super.validate(certificateEE, certificateChain, descriptor, checkName);
151                 if (defaultValidation == true) { return true; }
152
153                 // Make sure we have the data we need
154                 if (descriptor == null || certificateEE == null) {
155                         log.error("Appropriate data was not supplied for trust evaluation.");
156                         return false;
157                 }
158                 log.debug("Inline validation was unsuccessful.  Attmping PKIX...");
159                 // If not, try PKIX validation against the shib-custom metadata extensions
160
161                 // First, we want to see if we can match a keyName from the metadata against the cert
162                 // Iterator through all the keys in the metadata
163                 if (checkName) {
164
165                         if (matchProviderId(certificateChain[0], descriptor.getEntityDescriptor().getId())) {
166                                 checkName = false;
167                         } else {
168
169                                 Iterator keyDescriptors = descriptor.getKeyDescriptors();
170                                 while (checkName && keyDescriptors.hasNext()) {
171                                         // Look for a key descriptor with the right usage bits
172                                         KeyDescriptor keyDescriptor = (KeyDescriptor) keyDescriptors.next();
173                                         if (keyDescriptor.getUse() == KeyDescriptor.ENCRYPTION) {
174                                                 log.debug("Skipping key descriptor with inappropriate usage indicator.");
175                                                 continue;
176                                         }
177
178                                         // We found one, see if we can match the metadata's keyName against the cert
179                                         KeyInfo keyInfo = keyDescriptor.getKeyInfo();
180                                         if (keyInfo.containsKeyName()) {
181                                                 for (int i = 0; i < keyInfo.lengthKeyName(); i++) {
182                                                         try {
183                                                                 if (matchKeyName(certificateChain[0], keyInfo.itemKeyName(i))) {
184                                                                         checkName = false;
185                                                                         break;
186                                                                 }
187                                                         } catch (XMLSecurityException e) {
188                                                                 log.error("Problem retrieving key name from metadata: " + e);
189                                                         }
190                                                 }
191                                         }
192                                 }
193                         }
194                 }
195
196                 if (checkName) {
197                         log.error("cannot match certificate subject against acceptable key names based on the "
198                                         + "metadata entityId or KeyDescriptors");
199                         return false;
200                 }
201
202                 if (pkixValidate(certificateEE, certificateChain, descriptor.getEntityDescriptor())) { return true; }
203                 return false;
204         }
205
206         private boolean pkixValidate(X509Certificate certEE, X509Certificate[] certChain, EntityDescriptor entity) {
207
208                 if (entity instanceof ExtendedEntityDescriptor) {
209                         Iterator keyAuthorities = ((ExtendedEntityDescriptor) entity).getKeyAuthorities();
210                         // if we have any key authorities, construct a flat list of trust anchors representing each and attempt to
211                         // validate against them in turn
212                         while (keyAuthorities.hasNext()) {
213                                 if (pkixValidate(certEE, certChain, (KeyAuthority) keyAuthorities.next())) { return true; }
214                         }
215                 }
216
217                 // We couldn't do path validation based on metadata attached to the entity, we now need to walk up the chain of
218                 // nested entities and attempt to validate at each group level
219                 EntitiesDescriptor group = entity.getEntitiesDescriptor();
220                 if (group != null) {
221                         if (pkixValidate(certEE, certChain, group)) { return true; }
222                 }
223
224                 // We've walked the entire metadata chain with no success, so fail
225                 return false;
226         }
227
228         private boolean pkixValidate(X509Certificate certEE, X509Certificate[] certChain, EntitiesDescriptor group) {
229
230                 log.debug("Attemping to validate against parent group.");
231                 if (group instanceof ExtendedEntitiesDescriptor) {
232                         Iterator keyAuthorities = ((ExtendedEntitiesDescriptor) group).getKeyAuthorities();
233                         // if we have any key authorities, construct a flat list of trust anchors representing each and attempt to
234                         // validate against them in turn
235                         while (keyAuthorities.hasNext()) {
236                                 if (pkixValidate(certEE, certChain, (KeyAuthority) keyAuthorities.next())) { return true; }
237                         }
238                 }
239
240                 // If not, attempt to walk up the chain for validation
241                 EntitiesDescriptor parent = group.getEntitiesDescriptor();
242                 if (parent != null) {
243                         if (pkixValidate(certEE, certChain, parent)) { return true; }
244                 }
245
246                 return false;
247         }
248
249         private boolean pkixValidate(X509Certificate certEE, X509Certificate[] certChain, KeyAuthority authority) {
250
251                 Set anchors = new HashSet();
252                 Set crls = new HashSet();
253                 Iterator keyInfos = authority.getKeyInfos();
254                 while (keyInfos.hasNext()) {
255                         KeyInfo keyInfo = (KeyInfo) keyInfos.next();
256                         if (keyInfo.containsX509Data()) {
257                                 try {
258                                         // Add all certificates in the authority as trust anchors
259                                         for (int i = 0; i < keyInfo.lengthX509Data(); i++) {
260                                                 X509Data data = keyInfo.itemX509Data(i);
261                                                 if (data.containsCertificate()) {
262                                                         for (int j = 0; j < data.lengthCertificate(); j++) {
263                                                                 XMLX509Certificate xmlCert = data.itemCertificate(j);
264                                                                 anchors.add(new TrustAnchor(xmlCert.getX509Certificate(), null));
265                                                         }
266                                                 }
267                                                 // Compile all CRLs in the authority
268                                                 if (data.containsCRL()) {
269                                                         for (int j = 0; j < data.lengthCRL(); j++) {
270                                                                 XMLX509CRL xmlCrl = data.itemCRL(j);
271                                                                 try {
272                                                                         X509CRL crl = (X509CRL) CertificateFactory.getInstance("X.509").generateCRL(
273                                                                                         new ByteArrayInputStream(xmlCrl.getCRLBytes()));
274                                                                         if (crl.getRevokedCertificates() != null && crl.getRevokedCertificates().size() > 0) {
275                                                                                 crls.add(crl);
276                                                                         }
277                                                                 } catch (GeneralSecurityException e) {
278                                                                         log.error("Encountered an error parsing CRL from shibboleth metadata: " + e);
279                                                                 }
280                                                         }
281                                                 }
282                                         }
283
284                                 } catch (XMLSecurityException e) {
285                                         log.error("Encountered an error constructing trust list from shibboleth metadata: " + e);
286                                 }
287                         }
288                 }
289
290                 // alright, if we were able to create a trust list, attempt a pkix validation against the list
291                 if (anchors.size() > 0) {
292                         log.debug("Constructed a trust list from key authority.  Attempting path validation...");
293                         try {
294                                 CertPathValidator validator = CertPathValidator.getInstance("PKIX");
295
296                                 X509CertSelector selector = new X509CertSelector();
297                                 selector.setCertificate(certEE);
298                                 PKIXBuilderParameters params = new PKIXBuilderParameters(anchors, selector);
299                                 params.setMaxPathLength(authority.getVerifyDepth());
300                                 List storeMaterial = new ArrayList(crls);
301                                 storeMaterial.addAll(Arrays.asList(certChain));
302                                 CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(storeMaterial));
303                                 List stores = new ArrayList();
304                                 stores.add(store);
305                                 params.setCertStores(stores);
306                                 if (crls.size() > 0) {
307                                         params.setRevocationEnabled(true);
308                                 } else {
309                                         params.setRevocationEnabled(false);
310                                 }
311                                 // System.err.println(params.toString());
312                                 CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
313                                 PKIXCertPathBuilderResult buildResult = (PKIXCertPathBuilderResult) builder.build(params);
314
315                                 PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) validator.validate(buildResult
316                                                 .getCertPath(), params);
317                                 log.debug("Path successfully validated.");
318                                 return true;
319
320                         } catch (CertPathValidatorException e) {
321                                 log.debug("Path failed to validate: " + e);
322                         } catch (GeneralSecurityException e) {
323                                 log.error("Encountered an error during validation: " + e);
324                         }
325                 }
326                 return false;
327         }
328
329         private static boolean matchKeyName(X509Certificate certificate, KeyName keyName) {
330
331                 // First, try to match DN against metadata
332                 try {
333                         if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253).equals(
334                                         new X500Principal(keyName.getKeyName()).getName(X500Principal.RFC2253))) {
335                                 log.debug("Matched against DN.");
336                                 return true;
337                         }
338                 } catch (IllegalArgumentException iae) {
339                         // squelch this runtime exception, since
340                         // this might be a valid case
341                 }
342
343                 // If that doesn't work, we try matching against
344                 // some Subject Alt Names
345                 try {
346                         Collection altNames = certificate.getSubjectAlternativeNames();
347                         if (altNames != null) {
348                                 for (Iterator nameIterator = altNames.iterator(); nameIterator.hasNext();) {
349                                         List altName = (List) nameIterator.next();
350                                         if (altName.get(0).equals(new Integer(2)) || altName.get(0).equals(new Integer(6))) {
351                                                 // 2 is DNS, 6 is URI
352                                                 if (altName.get(0).equals(keyName.getKeyName())) {
353                                                         log.debug("Matched against SubjectAltName.");
354                                                         return true;
355                                                 }
356                                         }
357                                 }
358                         }
359                 } catch (CertificateParsingException e1) {
360                         log.error("Encountered an problem trying to extract Subject Alternate "
361                                         + "Name from supplied certificate: " + e1);
362                 }
363
364                 // If that doesn't work, try to match using
365                 // SSL-style hostname matching
366                 if (getHostNameFromDN(certificate.getSubjectX500Principal()).equals(keyName.getKeyName())) {
367                         log.debug("Matched against hostname.");
368                         return true;
369                 }
370
371                 return false;
372         }
373
374         private static boolean matchProviderId(X509Certificate certificate, String id) {
375
376                 // Try matching against URI Subject Alt Names
377                 try {
378                         Collection altNames = certificate.getSubjectAlternativeNames();
379                         if (altNames != null) {
380                                 for (Iterator nameIterator = altNames.iterator(); nameIterator.hasNext();) {
381                                         List altName = (List) nameIterator.next();
382                                         if (altName.get(0).equals(new Integer(6))) { // 6 is URI
383                                                 if (altName.get(0).equals(id)) {
384                                                         log.debug("Entity ID matched against SubjectAltName.");
385                                                         return true;
386                                                 }
387                                         }
388                                 }
389                         }
390                 } catch (CertificateParsingException e1) {
391                         log.error("Encountered an problem trying to extract Subject Alternate "
392                                         + "Name from supplied certificate: " + e1);
393                 }
394
395                 // If that doesn't work, try to match using
396                 // SSL-style hostname matching
397                 if (getHostNameFromDN(certificate.getSubjectX500Principal()).equals(id)) {
398                         log.debug("Entity ID matched against hostname.");
399                         return true;
400                 }
401
402                 return false;
403         }
404
405         public static String getHostNameFromDN(X500Principal dn) {
406
407                 // Parse the ASN.1 representation of the dn and grab the last CN component that we find
408                 // We used to do this with the dn string, but the JDK's default parsing caused problems with some DNs
409
410                 try {
411                         ASN1InputStream asn1Stream = new ASN1InputStream(dn.getEncoded());
412                         DERObject parent = asn1Stream.readObject();
413
414                         if (!(parent instanceof DERSequence)) {
415                                 log.error("Unable to extract host name name from certificate subject DN: incorrect ASN.1 encoding.");
416                                 return null;
417                         }
418
419                         String cn = null;
420                         for (int i = 0; i < ((DERSequence) parent).size(); i++) {
421                                 DERObject dnComponent = ((DERSequence) parent).getObjectAt(i).getDERObject();
422                                 if (!(dnComponent instanceof DERSet)) {
423                                         continue;
424                                 }
425
426                                 // Each DN component is a set
427                                 for (int j = 0; j < ((DERSet) dnComponent).size(); j++) {
428                                         DERObject grandChild = ((DERSet) dnComponent).getObjectAt(j).getDERObject();
429
430                                         if (((DERSequence) grandChild).getObjectAt(0) != null
431                                                         && ((DERSequence) grandChild).getObjectAt(0).getDERObject() instanceof DERObjectIdentifier) {
432                                                 DERObjectIdentifier componentId = (DERObjectIdentifier) ((DERSequence) grandChild).getObjectAt(
433                                                                 0).getDERObject();
434
435                                                 if (CN_OID.equals(componentId.getId())) {
436                                                         // OK, this dn component is actually a cn attribute
437                                                         if (((DERSequence) grandChild).getObjectAt(1) != null
438                                                                         && ((DERSequence) grandChild).getObjectAt(1).getDERObject() instanceof DERPrintableString) {
439                                                                 cn = ((DERPrintableString) ((DERSequence) grandChild).getObjectAt(1).getDERObject())
440                                                                                 .getString();
441                                                         }
442                                                 }
443                                         }
444                                 }
445                         }
446                         asn1Stream.close();
447                         return cn;
448
449                 } catch (IOException e) {
450                         log.error("Unable to extract host name name from certificate subject DN: ASN.1 parsing failed: " + e);
451                         return null;
452                 }
453         }
454
455 }