Added a function to extract possible match names from cert, fixed bug in altName...
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / common / provider / ShibbolethTrust.java
1 /*
2  * Copyright [2005] [University Corporation for Advanced Internet Development, Inc.]
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package edu.internet2.middleware.shibboleth.common.provider;
18
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;
42 import java.util.Set;
43
44 import javax.security.auth.x500.X500Principal;
45
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;
64
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;
75
76 /**
77  * <code>Trust</code> implementation that does PKIX validation against key authorities included in shibboleth-specific
78  * extensions to SAML 2 metadata.
79  * 
80  * @author Walter Hoehn
81  */
82 public class ShibbolethTrust extends BasicTrust implements Trust, PluggableConfigurationComponent {
83
84         private static Logger log = Logger.getLogger(ShibbolethTrust.class.getName());
85         private static final String CN_OID = "2.5.4.3";
86
87         /*
88          * @see edu.internet2.middleware.shibboleth.common.Trust#validate(java.security.cert.X509Certificate,
89          *      java.security.cert.X509Certificate[], edu.internet2.middleware.shibboleth.metadata.RoleDescriptor)
90          */
91         public boolean validate(X509Certificate certificateEE, X509Certificate[] certificateChain, RoleDescriptor descriptor) {
92
93                 return validate(certificateEE, certificateChain, descriptor, true);
94         }
95
96         /*
97          * @see edu.internet2.middleware.shibboleth.common.Trust#validate(org.opensaml.SAMLSignedObject,
98          *      edu.internet2.middleware.shibboleth.metadata.RoleDescriptor)
99          */
100         public boolean validate(SAMLSignedObject token, RoleDescriptor descriptor) {
101
102                 if (super.validate(token, descriptor)) return true;
103
104                 /* Certificates supplied with the signed object */
105                 ArrayList/* <X509Certificate> */certificates = new ArrayList/* <X509Certificate> */();
106                 X509Certificate certificateEE = null;
107
108                 /* Iterate to count the certificates, and look for the signer */
109                 Iterator icertificates;
110                 try {
111                         icertificates = token.getX509Certificates();
112                 } catch (SAMLException e1) {
113                         return false;
114                 }
115                 while (icertificates.hasNext()) {
116                         X509Certificate certificate = (X509Certificate) icertificates.next();
117                         try {
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);
124                         }
125                 }
126
127                 if (certificateEE == null) return false; // No key validates the signature
128
129                 // With a count we can now build a typed array
130                 X509Certificate[] certificateChain = new X509Certificate[certificates.size()];
131                 int i = 0;
132                 for (icertificates = certificates.iterator(); icertificates.hasNext();) {
133                         certificateChain[i++] = (X509Certificate) icertificates.next();
134                 }
135                 return validate(certificateEE, certificateChain, descriptor);
136         }
137
138         /*
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)
141          */
142         public boolean validate(X509Certificate certificateEE, X509Certificate[] certificateChain,
143                         RoleDescriptor descriptor, boolean checkName) {
144
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; }
148
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.");
152                         return false;
153                 }
154                 log.debug("Inline validation was unsuccessful.  Attmping PKIX...");
155                 // If not, try PKIX validation against the shib-custom metadata extensions
156
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
159                 if (checkName) {
160
161                         if (matchProviderId(certificateChain[0], descriptor.getEntityDescriptor().getId())) {
162                                 checkName = false;
163                         } else {
164
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.");
171                                                 continue;
172                                         }
173
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++) {
178                                                         try {
179                                                                 if (matchKeyName(certificateChain[0], keyInfo.itemKeyName(i))) {
180                                                                         checkName = false;
181                                                                         break;
182                                                                 }
183                                                         } catch (XMLSecurityException e) {
184                                                                 log.error("Problem retrieving key name from metadata: " + e);
185                                                         }
186                                                 }
187                                         }
188                                 }
189                         }
190                 }
191
192                 if (checkName) {
193                         log.error("cannot match certificate subject against acceptable key names based on the "
194                                         + "metadata entityId or KeyDescriptors");
195                         return false;
196                 }
197
198                 if (pkixValidate(certificateEE, certificateChain, descriptor.getEntityDescriptor())) { return true; }
199                 return false;
200         }
201
202         private boolean pkixValidate(X509Certificate certEE, X509Certificate[] certChain, EntityDescriptor entity) {
203
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; }
210                         }
211                 }
212
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();
216                 if (group != null) {
217                         if (pkixValidate(certEE, certChain, group)) { return true; }
218                 }
219
220                 // We've walked the entire metadata chain with no success, so fail
221                 return false;
222         }
223
224         private boolean pkixValidate(X509Certificate certEE, X509Certificate[] certChain, EntitiesDescriptor group) {
225
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; }
233                         }
234                 }
235
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; }
240                 }
241
242                 return false;
243         }
244
245         private boolean pkixValidate(X509Certificate certEE, X509Certificate[] certChain, KeyAuthority authority) {
246
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()) {
253                                 try {
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));
261                                                         }
262                                                 }
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);
267                                                                 try {
268                                                                         X509CRL crl = (X509CRL) CertificateFactory.getInstance("X.509").generateCRL(
269                                                                                         new ByteArrayInputStream(xmlCrl.getCRLBytes()));
270                                                                         if (crl.getRevokedCertificates() != null && crl.getRevokedCertificates().size() > 0) {
271                                                                                 crls.add(crl);
272                                                                         }
273                                                                 } catch (GeneralSecurityException e) {
274                                                                         log.error("Encountered an error parsing CRL from shibboleth metadata: " + e);
275                                                                 }
276                                                         }
277                                                 }
278                                         }
279
280                                 } catch (XMLSecurityException e) {
281                                         log.error("Encountered an error constructing trust list from shibboleth metadata: " + e);
282                                 }
283                         }
284                 }
285
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...");
289                         try {
290                                 CertPathValidator validator = CertPathValidator.getInstance("PKIX");
291
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();
300                                 stores.add(store);
301                                 params.setCertStores(stores);
302                                 if (crls.size() > 0) {
303                                         params.setRevocationEnabled(true);
304                                 } else {
305                                         params.setRevocationEnabled(false);
306                                 }
307                                 // System.err.println(params.toString());
308                                 CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
309                                 PKIXCertPathBuilderResult buildResult = (PKIXCertPathBuilderResult) builder.build(params);
310
311                                 PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) validator.validate(buildResult
312                                                 .getCertPath(), params);
313                                 log.debug("Path successfully validated.");
314                                 return true;
315
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);
320                         }
321                 }
322                 return false;
323         }
324
325         private static boolean matchKeyName(X509Certificate certificate, KeyName keyName) {
326
327                 // First, try to match DN against metadata
328                 try {
329                         if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253).equals(
330                                         new X500Principal(keyName.getKeyName()).getName(X500Principal.RFC2253))) {
331                                 log.debug("Matched against DN.");
332                                 return true;
333                         }
334                 } catch (IllegalArgumentException iae) {
335                         // squelch this runtime exception, since
336                         // this might be a valid case
337                 }
338
339                 // If that doesn't work, we try matching against
340                 // some Subject Alt Names
341                 try {
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.");
350                                                         return true;
351                                                 }
352                                         }
353                                 }
354                         }
355                 } catch (CertificateParsingException e1) {
356                         log.error("Encountered an problem trying to extract Subject Alternate "
357                                         + "Name from supplied certificate: " + e1);
358                 }
359
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.");
364                         return true;
365                 }
366
367                 return false;
368         }
369
370         public static String[] getCredentialNames(X509Certificate certificate) {
371                 ArrayList names = new ArrayList();
372                 names.add(certificate.getSubjectX500Principal().getName(X500Principal.RFC2253));
373                 try {
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));
380                                         }
381                                         else if (altName.get(0).equals(new Integer(6))) { // 6 is URI
382                                                 names.add(altName.get(1));
383                                         }
384                                 }
385                         }
386                 } catch (CertificateParsingException e1) {
387                         log.error("Encountered an problem trying to extract Subject Alternate "
388                                         + "Name from supplied certificate: " + e1);
389                 }
390                 names.add(getHostNameFromDN(certificate.getSubjectX500Principal()));
391                 return (String[]) names.toArray();
392         }
393         
394         private static boolean matchProviderId(X509Certificate certificate, String id) {
395
396                 // Try matching against URI Subject Alt Names
397                 try {
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.");
405                                                         return true;
406                                                 }
407                                         }
408                                 }
409                         }
410                 } catch (CertificateParsingException e1) {
411                         log.error("Encountered an problem trying to extract Subject Alternate "
412                                         + "Name from supplied certificate: " + e1);
413                 }
414
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.");
419                         return true;
420                 }
421
422                 return false;
423         }
424
425         public static String getHostNameFromDN(X500Principal dn) {
426
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
429                 try {
430                         ASN1InputStream asn1Stream = new ASN1InputStream(dn.getEncoded());
431                         DERObject parent = asn1Stream.readObject();
432
433                         if (!(parent instanceof DERSequence)) {
434                                 log.error("Unable to extract host name name from certificate subject DN: incorrect ASN.1 encoding.");
435                                 return null;
436                         }
437
438                         String cn = null;
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.");
443                                         continue;
444                                 }
445
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();
449
450                                         if (((DERSequence) grandChild).getObjectAt(0) != null
451                                                         && ((DERSequence) grandChild).getObjectAt(0).getDERObject() instanceof DERObjectIdentifier) {
452                                                 DERObjectIdentifier componentId = (DERObjectIdentifier) ((DERSequence) grandChild).getObjectAt(
453                                                                 0).getDERObject();
454
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();
460                                                         }
461                                                 }
462                                         }
463                                 }
464                         }
465                         asn1Stream.close();
466                         return cn;
467
468                 } catch (IOException e) {
469                         log.error("Unable to extract host name name from certificate subject DN: ASN.1 parsing failed: " + e);
470                         return null;
471                 }
472         }
473
474         public void initialize(Node dom) throws XmlException, ShibbolethConfigurationException {
475                 
476         }
477
478         public void initialize(Element dom) throws SAMLException, XmlException, ShibbolethConfigurationException {
479                 
480         }
481
482 }