Adjustments to trust interface and providers for token handling.
[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.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;
49 import java.util.Set;
50 import java.util.regex.Matcher;
51 import java.util.regex.Pattern;
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.opensaml.SAMLSignedObject;
63
64 import edu.internet2.middleware.shibboleth.common.Trust;
65 import edu.internet2.middleware.shibboleth.metadata.EntitiesDescriptor;
66 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
67 import edu.internet2.middleware.shibboleth.metadata.ExtendedEntitiesDescriptor;
68 import edu.internet2.middleware.shibboleth.metadata.ExtendedEntityDescriptor;
69 import edu.internet2.middleware.shibboleth.metadata.KeyAuthority;
70 import edu.internet2.middleware.shibboleth.metadata.KeyDescriptor;
71 import edu.internet2.middleware.shibboleth.metadata.RoleDescriptor;
72
73 /**
74  * <code>Trust</code> implementation that does PKIX validation against key authorities included in shibboleth-specific
75  * extensions to SAML 2 metadata.
76  * 
77  * @author Walter Hoehn
78  */
79 public class ShibbolethTrust extends BasicTrust implements Trust {
80
81         private static Logger log = Logger.getLogger(ShibbolethTrust.class.getName());
82         private static Pattern regex = Pattern.compile(".*?CN=([^,/]+).*");
83
84     /*
85      * @see edu.internet2.middleware.shibboleth.common.Trust#validate(java.security.cert.X509Certificate, java.security.cert.X509Certificate[], edu.internet2.middleware.shibboleth.metadata.RoleDescriptor)
86      */
87     public boolean validate(X509Certificate certificateEE, X509Certificate[] certificateChain, RoleDescriptor descriptor) {
88         return validate(certificateEE, certificateChain, descriptor, true);
89     }
90
91     /*
92      * @see edu.internet2.middleware.shibboleth.common.Trust#validate(org.opensaml.SAMLSignedObject, edu.internet2.middleware.shibboleth.metadata.RoleDescriptor)
93      */
94     public boolean validate(SAMLSignedObject token, RoleDescriptor descriptor) {
95         // TODO Auto-generated method stub
96         
97         /*
98          * Proposed algorithm for this (will modify C++ to match:
99          * 
100          * - get the certificates from the token
101          * - iterate over them in order, until one verifies the signature
102          * - pass that as the EE cert to the other validate method, with the full set as a chain
103          */ 
104         return false;
105     }
106
107     /*
108      * @see edu.internet2.middleware.shibboleth.common.Trust#validate(java.security.cert.X509Certificate,
109      *  java.security.cert.X509Certificate[], edu.internet2.middleware.shibboleth.metadata.RoleDescriptor, boolean)
110      */
111     public boolean validate(X509Certificate certificateEE, X509Certificate[] certificateChain, RoleDescriptor descriptor, boolean checkName) {
112
113                 // If we can successfully validate with an inline key, that's fine
114                 boolean defaultValidation = super.validate(certificateEE, certificateChain, descriptor, checkName);
115                 if (defaultValidation == true) { return true; }
116
117                 // Make sure we have the data we need
118                 if (descriptor == null || certificateEE == null) {
119                         log.error("Appropriate data was not supplied for trust evaluation.");
120                         return false;
121                 }
122                 log.debug("Inline validation was unsuccessful.  Attmping PKIX...");
123                 // If not, try PKIX validation against the shib-custom metadata extensions
124
125                 // First, we want to see if we can match a keyName from the metadata against the cert
126                 // Iterator through all the keys in the metadata
127         if (checkName) {
128             Iterator keyDescriptors = descriptor.getKeyDescriptors();
129                 while (checkName && keyDescriptors.hasNext()) {
130                         // Look for a key descriptor with the right usage bits
131                         KeyDescriptor keyDescriptor = (KeyDescriptor) keyDescriptors.next();
132                         if (keyDescriptor.getUse() == KeyDescriptor.ENCRYPTION) {
133                     log.debug("Skipping key descriptor with inappropriate usage indicator.");
134                                 continue;
135                         }
136
137                         // We found one, see if we can match the metadata's keyName against the cert
138                         KeyInfo keyInfo = keyDescriptor.getKeyInfo();
139                         if (keyInfo.containsKeyName()) {
140                             for (int i = 0; i < keyInfo.lengthKeyName(); i++) {
141                                 try {
142                                     if (matchKeyName(certificateChain[0], keyInfo.itemKeyName(i))) {
143                                         checkName = false;
144                                 break;
145                             }
146                                         } catch (XMLSecurityException e) {
147                                                 log.error("Problem retrieving key name from metadata: " + e);
148                                         }
149                                 }
150                         }
151                 }
152         }
153
154         if (checkName) {
155             log.error("cannot match certificate subject against acceptable key names based on KeyDescriptors");
156             return false;
157         }
158         
159         if (pkixValidate(certificateEE, certificateChain, descriptor.getEntityDescriptor())) { return true; }
160         return false;    
161         }
162
163         private boolean pkixValidate(X509Certificate certEE, X509Certificate[] certChain, EntityDescriptor entity) {
164
165                 if (entity instanceof ExtendedEntityDescriptor) {
166                         Iterator keyAuthorities = ((ExtendedEntityDescriptor) entity).getKeyAuthorities();
167                         // if we have any key authorities, construct a flat list of trust anchors representing each and attempt to
168                         // validate against them in turn
169                         while (keyAuthorities.hasNext()) {
170                                 if (pkixValidate(certEE, certChain, (KeyAuthority) keyAuthorities.next())) { return true; }
171                         }
172                 }
173
174                 // We couldn't do path validation based on metadata attached to the entity, we now need to walk up the chain of
175                 // nested entities and attempt to validate at each group level
176                 EntitiesDescriptor group = entity.getEntitiesDescriptor();
177                 if (group != null) {
178                         if (pkixValidate(certEE, certChain, group)) { return true; }
179                 }
180
181                 // We've walked the entire metadata chain with no success, so fail
182                 return false;
183         }
184
185         private boolean pkixValidate(X509Certificate certEE, X509Certificate[] certChain, EntitiesDescriptor group) {
186
187                 log.debug("Attemping to validate against parent group.");
188                 if (group instanceof ExtendedEntitiesDescriptor) {
189                         Iterator keyAuthorities = ((ExtendedEntitiesDescriptor) group).getKeyAuthorities();
190                         // if we have any key authorities, construct a flat list of trust anchors representing each and attempt to
191                         // validate against them in turn
192                         while (keyAuthorities.hasNext()) {
193                                 if (pkixValidate(certEE, certChain, (KeyAuthority) keyAuthorities.next())) { return true; }
194                         }
195                 }
196
197                 // If not, attempt to walk up the chain for validation
198                 EntitiesDescriptor parent = group.getEntitiesDescriptor();
199                 if (parent != null) {
200                         if (pkixValidate(certEE, certChain, parent)) { return true; }
201                 }
202
203                 return false;
204         }
205
206         private boolean pkixValidate(X509Certificate certEE, X509Certificate[] certChain, KeyAuthority authority) {
207
208                 Set anchors = new HashSet();
209                 Set crls = new HashSet();
210                 Iterator keyInfos = authority.getKeyInfos();
211                 while (keyInfos.hasNext()) {
212                         KeyInfo keyInfo = (KeyInfo) keyInfos.next();
213                         if (keyInfo.containsX509Data()) {
214                                 try {
215                                         //Add all certificates in the authority as trust anchors
216                                         for (int i = 0; i < keyInfo.lengthX509Data(); i++) {
217                                                 X509Data data = keyInfo.itemX509Data(i);
218                                                 if (data.containsCertificate()) {
219                                                         for (int j = 0; j < data.lengthCertificate(); j++) {
220                                                                 XMLX509Certificate xmlCert = data.itemCertificate(j);
221                                                                 anchors.add(new TrustAnchor(xmlCert.getX509Certificate(), null));
222                                                         }
223                                                 }
224                                                 // Compile all CRLs in the authority
225                                                 if (data.containsCRL()) {
226                                                         for (int j = 0; j < data.lengthCRL(); j++) {
227                                                                 XMLX509CRL xmlCrl = data.itemCRL(j);
228                                                                 try {
229                                                                         crls.add(CertificateFactory.getInstance("X.509").generateCRL(
230                                                                                         new ByteArrayInputStream(xmlCrl.getCRLBytes())));
231                                                                 } catch (GeneralSecurityException e) {
232                                                                         log.error("Encountered an error parsing CRL from shibboleth metadata: " + e);
233                                                                 }
234                                                         }
235                                                 }
236                                         }
237
238                                 } catch (XMLSecurityException e) {
239                                         log.error("Encountered an error constructing trust list from shibboleth metadata: " + e);
240                                 }
241                         }
242                 }
243
244                 // alright, if we were able to create a trust list, attempt a pkix validation against the list
245                 if (anchors.size() > 0) {
246                         log.debug("Constructed a trust list from key authority.  Attempting path validation...");
247                         try {
248                                 CertPathValidator validator = CertPathValidator.getInstance("PKIX");
249
250                                 X509CertSelector selector = new X509CertSelector();
251                                 selector.setCertificate(certEE);
252                                 PKIXBuilderParameters params = new PKIXBuilderParameters(anchors, selector);
253                                 params.setMaxPathLength(authority.getVerifyDepth());
254                                 List storeMaterial = new ArrayList(crls);
255                                 storeMaterial.addAll(Arrays.asList(certChain));
256                                 CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(storeMaterial));
257                                 List stores = new ArrayList();
258                                 stores.add(store);
259                                 params.setCertStores(stores);
260                                 if (crls.size() > 0) {
261                                         params.setRevocationEnabled(true);
262                                 } else {
263                                         params.setRevocationEnabled(false);
264                                 }
265
266                                 CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
267                                 PKIXCertPathBuilderResult buildResult = (PKIXCertPathBuilderResult) builder.build(params);
268
269                                 PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) validator.validate(buildResult
270                                                 .getCertPath(), params);
271                                 log.debug("Path successfully validated.");
272                                 return true;
273
274                         } catch (CertPathValidatorException e) {
275                                 log.debug("Path failed to validate: " + e);
276                         } catch (GeneralSecurityException e) {
277                                 log.error("Encountered an error during validation: " + e);
278                         }
279                 }
280                 return false;
281         }
282
283         private static boolean matchKeyName(X509Certificate certificate, KeyName keyName) {
284
285                 // First, try to match DN against metadata
286                 try {
287                         if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253).equals(
288                                         new X500Principal(keyName.getKeyName()).getName(X500Principal.RFC2253))) {
289                                 log.debug("Matched against DN.");
290                                 return true;
291                         }
292                 } catch (IllegalArgumentException iae) {
293                         // squelch this runtime exception, since
294                         // this might be a valid case
295                 }
296
297                 // If that doesn't work, we try matching against
298                 // some Subject Alt Names
299                 try {
300                         Collection altNames = certificate.getSubjectAlternativeNames();
301                         if (altNames != null) {
302                                 for (Iterator nameIterator = altNames.iterator(); nameIterator.hasNext();) {
303                                         List altName = (List) nameIterator.next();
304                                         if (altName.get(0).equals(new Integer(2)) || altName.get(0).equals(new Integer(6))) {
305                                                 // 2 is DNS, 6 is URI
306                                                 if (altName.get(0).equals(keyName.getKeyName())) {
307                                                         log.debug("Matched against SubjectAltName.");
308                                                         return true;
309                                                 }
310                                         }
311                                 }
312                         }
313                 } catch (CertificateParsingException e1) {
314                         log.error("Encountered an problem trying to extract Subject Alternate "
315                                         + "Name from supplied certificate: " + e1);
316                 }
317
318                 // If that doesn't work, try to match using
319                 // SSL-style hostname matching
320                 if (getHostNameFromDN(certificate.getSubjectX500Principal()).equals(keyName.getKeyName())) {
321                         log.debug("Matched against hostname.");
322                         return true;
323                 }
324
325                 return false;
326         }
327
328         private static String getHostNameFromDN(X500Principal dn) {
329
330                 Matcher matches = regex.matcher(dn.getName(X500Principal.RFC2253));
331                 if (!matches.find() || matches.groupCount() > 1) {
332                         log.error("Unable to extract host name name from certificate subject DN.");
333                         return null;
334                 }
335                 return matches.group(1);
336         }
337
338 }